You've already forked json-iterator
mirror of
https://github.com/json-iterator/go.git
synced 2025-06-15 22:50:24 +02:00
Compare commits
244 Commits
jsoniter-g
...
1.0.1
Author | SHA1 | Date | |
---|---|---|---|
92772579dd | |||
ae57d167e8 | |||
eef35e549b | |||
005d86dc44 | |||
e658f6597a | |||
f8eb43eda3 | |||
18a241d40b | |||
0fdf883ac0 | |||
34fbec74ad | |||
90574c5ca3 | |||
6a4ba7bfa9 | |||
0828e559d0 | |||
2c67d0f68a | |||
f29a0391bc | |||
374e68a144 | |||
b134d86290 | |||
bc3221879d | |||
8c7fc7584a | |||
db32ee8c2d | |||
d80309af3b | |||
36b14963da | |||
f706335302 | |||
2dc0031b26 | |||
cdbd2ed810 | |||
39e9d67807 | |||
2066b01acb | |||
ac3b3cd160 | |||
887789156a | |||
7df5a67d0d | |||
9c358632dc | |||
1cfa233923 | |||
d249b05a85 | |||
abbd16da6c | |||
b67201557a | |||
5124683f24 | |||
4892de725b | |||
34a2174be3 | |||
24ecaff2a1 | |||
c15b4d116c | |||
12cd299fa8 | |||
60ba332980 | |||
f705934fbf | |||
17a26a6e20 | |||
156284b028 | |||
6b6938829d | |||
e066e54964 | |||
18d6ae2668 | |||
c966eaa031 | |||
f6da8e62c3 | |||
5eded4f6ae | |||
9b3ec40fd9 | |||
0d604da7d7 | |||
b6ace7d51b | |||
6a4fbb9892 | |||
4ae426c4b7 | |||
b46d0a2324 | |||
8b03604184 | |||
93ce14316d | |||
779c3e2164 | |||
4b33139ad0 | |||
dc388588a3 | |||
bd4364ab7c | |||
b9dc3ebda7 | |||
90137b4a60 | |||
be9d4ded4f | |||
7b1fd129cf | |||
b91b7ac682 | |||
845d8438db | |||
d37197e176 | |||
45c22b130b | |||
4a84b0b30e | |||
0187038bad | |||
c38e47d169 | |||
b27718d16b | |||
a447a8f797 | |||
0d6dae80e1 | |||
d336ee6da6 | |||
3606750b83 | |||
db3f5046d7 | |||
f0487718f6 | |||
46574e7d09 | |||
3a6ecf051c | |||
5862c51768 | |||
ce479f3476 | |||
bede1d7f40 | |||
d3448d3dbd | |||
8fbed91768 | |||
3b6853d209 | |||
4351a2e6e9 | |||
891d33b415 | |||
ad20f12c34 | |||
9ecb1fd36d | |||
6d0e6f3733 | |||
711f836582 | |||
37ba1b32b5 | |||
2c10d8e6bb | |||
aaf6160146 | |||
b1afefe058 | |||
3bb49c1e47 | |||
eb68fff85c | |||
e07a4ca5ec | |||
dfa4bdf888 | |||
b74ffb2e03 | |||
a46060dedc | |||
5eadecbb66 | |||
5bc013d6a3 | |||
f7df62f1b5 | |||
07f423d248 | |||
d4c0cb2986 | |||
84ed6b3caf | |||
ee6536c50a | |||
b6eb62e96b | |||
8675af13bf | |||
21ca11f96a | |||
dd88d25090 | |||
6a289f32c2 | |||
4907dc00f6 | |||
2350982504 | |||
27725b7139 | |||
ca6a524d4f | |||
1de44419ea | |||
550531a046 | |||
1745078ab7 | |||
6129e85d53 | |||
ee3313111c | |||
4e65952c09 | |||
3829a470ae | |||
3f35bed884 | |||
8d7efe886c | |||
f245011c7d | |||
4ea96ac7c3 | |||
50beb4f15d | |||
e5d7a65616 | |||
d7b6b4e0bb | |||
712ddb1942 | |||
ca8dd93d0b | |||
ac8dd56dfb | |||
d8dbf14af4 | |||
402c6c79e2 | |||
2e10d5fdad | |||
f0b07a2313 | |||
919a2eff5c | |||
a743df1b8a | |||
8700644196 | |||
6a7bf91c45 | |||
e417330822 | |||
af876518e1 | |||
21b9254da4 | |||
c009421781 | |||
c4f54740f7 | |||
368bd0c1d8 | |||
11975d2a26 | |||
e7404f3065 | |||
f60a6a17c2 | |||
2dfdcdd9db | |||
496a8ea225 | |||
ed6c434851 | |||
bf002a02be | |||
815aa331a8 | |||
54ab168362 | |||
87d1ea0c60 | |||
6268a1cbc8 | |||
d56566286c | |||
f2c50ef73b | |||
d0c5988985 | |||
17eed15fb5 | |||
e260979001 | |||
3cf9b7c253 | |||
800df52ccd | |||
e3ba0e7b7e | |||
e366c72b81 | |||
69551ef38f | |||
abcf9a8d76 | |||
fa0965a968 | |||
04eae11ba5 | |||
ea8fa7cc63 | |||
6540266aaf | |||
ddfbb0c62e | |||
a3a2d1cd25 | |||
401a56bc20 | |||
cfaa11f837 | |||
c1411e0ad5 | |||
9ec64591b6 | |||
b07d1abc4f | |||
79c4040505 | |||
7fa780bd5d | |||
7244d730b9 | |||
12be6e0d43 | |||
3cfe590a13 | |||
678c297af3 | |||
1253b8edd3 | |||
fb382c0ec1 | |||
09cb1d9236 | |||
e6c24947ee | |||
a6673c983a | |||
ec7b40d104 | |||
84fa033353 | |||
4e608af2c7 | |||
3458ccdb20 | |||
45ccfb031f | |||
545a32f2a1 | |||
08dbc98040 | |||
82dabdcdbf | |||
76e62088df | |||
faaa59222a | |||
91ef89a6a2 | |||
3e3caf9184 | |||
03a2daaeee | |||
4652ac6cc2 | |||
8a9f2b9179 | |||
0db2d74de8 | |||
d6ef711c18 | |||
628fedf63c | |||
5bb7a1f7af | |||
c2c9981062 | |||
e40d614037 | |||
1589ab2fd7 | |||
97ee4ad4a2 | |||
f09f778ca9 | |||
9fc858b117 | |||
f93d25f8b1 | |||
7cd7a6cc7c | |||
7d6c9374e8 | |||
e16ee7f8ac | |||
cf6367546b | |||
dc44e85a86 | |||
85f7a1b0b3 | |||
507a446eda | |||
76eefc25ba | |||
21a16bd252 | |||
0c0c9f119f | |||
cf77980493 | |||
7d681fe2c2 | |||
0c07128d3c | |||
f771d32291 | |||
d100b0d41f | |||
81e64121ba | |||
dcc91365ee | |||
8f3de9c412 | |||
5d3508979f | |||
8f8e16b4c2 | |||
d7ea1acd3f | |||
ebed7df895 | |||
caaa04195e |
3
.codecov.yml
Normal file
3
.codecov.yml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
ignore:
|
||||||
|
- "output_tests/.*"
|
||||||
|
|
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
.idea
|
||||||
|
/coverage.txt
|
||||||
|
/profile.out
|
14
.travis.yml
Normal file
14
.travis.yml
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
language: go
|
||||||
|
|
||||||
|
go:
|
||||||
|
- 1.8.x
|
||||||
|
- 1.x
|
||||||
|
|
||||||
|
before_install:
|
||||||
|
- go get -t -v ./...
|
||||||
|
|
||||||
|
script:
|
||||||
|
- ./test.sh
|
||||||
|
|
||||||
|
after_success:
|
||||||
|
- bash <(curl -s https://codecov.io/bash)
|
18
README.md
18
README.md
@ -1,6 +1,16 @@
|
|||||||
|
[](https://sourcegraph.com/github.com/json-iterator/go?badge)
|
||||||
|
[](http://godoc.org/github.com/json-iterator/go)
|
||||||
|
[](https://travis-ci.org/json-iterator/go)
|
||||||
|
[](https://codecov.io/gh/json-iterator/go)
|
||||||
[](https://goreportcard.com/report/github.com/json-iterator/go)
|
[](https://goreportcard.com/report/github.com/json-iterator/go)
|
||||||
|
[](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE)
|
||||||
|
[](https://gitter.im/json-iterator/Lobby)
|
||||||
|
|
||||||
jsoniter (json-iterator) is fast and flexible JSON parser available in [Java](https://github.com/json-iterator/java) and [Go](https://github.com/json-iterator/go)
|
A high-performance 100% compatible drop-in replacement of "encoding/json"
|
||||||
|
|
||||||
|
```
|
||||||
|
Go开发者们请加入我们,滴滴出行平台技术部 taowen@didichuxing.com
|
||||||
|
```
|
||||||
|
|
||||||
# Benchmark
|
# Benchmark
|
||||||
|
|
||||||
@ -61,4 +71,10 @@ go get github.com/json-iterator/go
|
|||||||
|
|
||||||
# Contribution Welcomed !
|
# Contribution Welcomed !
|
||||||
|
|
||||||
|
Contributors
|
||||||
|
|
||||||
|
* [thockin](https://github.com/thockin)
|
||||||
|
* [mattn](https://github.com/mattn)
|
||||||
|
* [cch123](https://github.com/cch123)
|
||||||
|
|
||||||
Report issue or pull request, or email taowen@gmail.com, or [](https://gitter.im/json-iterator/Lobby)
|
Report issue or pull request, or email taowen@gmail.com, or [](https://gitter.im/json-iterator/Lobby)
|
||||||
|
1017
assert/assertions.go
1017
assert/assertions.go
File diff suppressed because it is too large
Load Diff
@ -1,10 +1,8 @@
|
|||||||
package jsoniter_test
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/json-iterator/go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ExampleMarshal() {
|
func ExampleMarshal() {
|
||||||
@ -18,7 +16,7 @@ func ExampleMarshal() {
|
|||||||
Name: "Reds",
|
Name: "Reds",
|
||||||
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
|
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
|
||||||
}
|
}
|
||||||
b, err := jsoniter.Marshal(group)
|
b, err := Marshal(group)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("error:", err)
|
fmt.Println("error:", err)
|
||||||
}
|
}
|
||||||
@ -37,7 +35,7 @@ func ExampleUnmarshal() {
|
|||||||
Order string
|
Order string
|
||||||
}
|
}
|
||||||
var animals []Animal
|
var animals []Animal
|
||||||
err := jsoniter.Unmarshal(jsonBlob, &animals)
|
err := Unmarshal(jsonBlob, &animals)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("error:", err)
|
fmt.Println("error:", err)
|
||||||
}
|
}
|
||||||
@ -46,7 +44,7 @@ func ExampleUnmarshal() {
|
|||||||
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
|
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleMarshalWithBestPerformance() {
|
func ExampleConfigFastest_Marshal() {
|
||||||
type ColorGroup struct {
|
type ColorGroup struct {
|
||||||
ID int
|
ID int
|
||||||
Name string
|
Name string
|
||||||
@ -57,8 +55,8 @@ func ExampleMarshalWithBestPerformance() {
|
|||||||
Name: "Reds",
|
Name: "Reds",
|
||||||
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
|
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
|
||||||
}
|
}
|
||||||
stream := jsoniter.ConfigFastest.BorrowStream(nil)
|
stream := ConfigFastest.BorrowStream(nil)
|
||||||
defer jsoniter.ConfigFastest.ReturnStream(stream)
|
defer ConfigFastest.ReturnStream(stream)
|
||||||
stream.WriteVal(group)
|
stream.WriteVal(group)
|
||||||
if stream.Error != nil {
|
if stream.Error != nil {
|
||||||
fmt.Println("error:", stream.Error)
|
fmt.Println("error:", stream.Error)
|
||||||
@ -68,7 +66,7 @@ func ExampleMarshalWithBestPerformance() {
|
|||||||
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
|
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleUnmarshalWithBestPerformance() {
|
func ExampleConfigFastest_Unmarshal() {
|
||||||
var jsonBlob = []byte(`[
|
var jsonBlob = []byte(`[
|
||||||
{"Name": "Platypus", "Order": "Monotremata"},
|
{"Name": "Platypus", "Order": "Monotremata"},
|
||||||
{"Name": "Quoll", "Order": "Dasyuromorphia"}
|
{"Name": "Quoll", "Order": "Dasyuromorphia"}
|
||||||
@ -78,8 +76,8 @@ func ExampleUnmarshalWithBestPerformance() {
|
|||||||
Order string
|
Order string
|
||||||
}
|
}
|
||||||
var animals []Animal
|
var animals []Animal
|
||||||
iter := jsoniter.ConfigFastest.BorrowIterator(jsonBlob)
|
iter := ConfigFastest.BorrowIterator(jsonBlob)
|
||||||
defer jsoniter.ConfigFastest.ReturnIterator(iter)
|
defer ConfigFastest.ReturnIterator(iter)
|
||||||
iter.ReadVal(&animals)
|
iter.ReadVal(&animals)
|
||||||
if iter.Error != nil {
|
if iter.Error != nil {
|
||||||
fmt.Println("error:", iter.Error)
|
fmt.Println("error:", iter.Error)
|
||||||
@ -89,9 +87,9 @@ func ExampleUnmarshalWithBestPerformance() {
|
|||||||
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
|
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleOneLine() {
|
func ExampleGet() {
|
||||||
val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`)
|
val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`)
|
||||||
fmt.Printf(jsoniter.Get(val, "Colors", 0).ToString())
|
fmt.Printf(Get(val, "Colors", 0).ToString())
|
||||||
// Output:
|
// Output:
|
||||||
// Crimson
|
// Crimson
|
||||||
}
|
}
|
||||||
|
@ -2,26 +2,30 @@ package extra
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go"
|
"io"
|
||||||
"math"
|
"math"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/json-iterator/go"
|
||||||
)
|
)
|
||||||
|
|
||||||
const MaxUint = ^uint(0)
|
const maxUint = ^uint(0)
|
||||||
const MaxInt = int(MaxUint >> 1)
|
const maxInt = int(maxUint >> 1)
|
||||||
const MinInt = -MaxInt - 1
|
const minInt = -maxInt - 1
|
||||||
|
|
||||||
|
// RegisterFuzzyDecoders decode input from PHP with tolerance.
|
||||||
|
// It will handle string/number auto conversation, and treat empty [] as empty struct.
|
||||||
func RegisterFuzzyDecoders() {
|
func RegisterFuzzyDecoders() {
|
||||||
jsoniter.RegisterExtension(&tolerateEmptyArrayExtension{})
|
jsoniter.RegisterExtension(&tolerateEmptyArrayExtension{})
|
||||||
jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
|
jsoniter.RegisterTypeDecoder("string", &fuzzyStringDecoder{})
|
||||||
jsoniter.RegisterTypeDecoder("float32", &FuzzyFloat32Decoder{})
|
jsoniter.RegisterTypeDecoder("float32", &fuzzyFloat32Decoder{})
|
||||||
jsoniter.RegisterTypeDecoder("float64", &FuzzyFloat64Decoder{})
|
jsoniter.RegisterTypeDecoder("float64", &fuzzyFloat64Decoder{})
|
||||||
jsoniter.RegisterTypeDecoder("int", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("int", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(MaxInt) || val < float64(MinInt) {
|
if val > float64(maxInt) || val < float64(minInt) {
|
||||||
iter.ReportError("fuzzy decode int", "exceed range")
|
iter.ReportError("fuzzy decode int", "exceed range")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -30,10 +34,10 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*int)(ptr)) = iter.ReadInt()
|
*((*int)(ptr)) = iter.ReadInt()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("uint", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("uint", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(MaxUint) || val < 0 {
|
if val > float64(maxUint) || val < 0 {
|
||||||
iter.ReportError("fuzzy decode uint", "exceed range")
|
iter.ReportError("fuzzy decode uint", "exceed range")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -42,7 +46,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*uint)(ptr)) = iter.ReadUint()
|
*((*uint)(ptr)) = iter.ReadUint()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("int8", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("int8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
|
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
|
||||||
@ -54,7 +58,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*int8)(ptr)) = iter.ReadInt8()
|
*((*int8)(ptr)) = iter.ReadInt8()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("uint8", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("uint8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxUint8) || val < 0 {
|
if val > float64(math.MaxUint8) || val < 0 {
|
||||||
@ -66,7 +70,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*uint8)(ptr)) = iter.ReadUint8()
|
*((*uint8)(ptr)) = iter.ReadUint8()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("int16", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("int16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
|
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
|
||||||
@ -78,7 +82,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*int16)(ptr)) = iter.ReadInt16()
|
*((*int16)(ptr)) = iter.ReadInt16()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("uint16", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("uint16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxUint16) || val < 0 {
|
if val > float64(math.MaxUint16) || val < 0 {
|
||||||
@ -90,7 +94,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*uint16)(ptr)) = iter.ReadUint16()
|
*((*uint16)(ptr)) = iter.ReadUint16()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("int32", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("int32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
|
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
|
||||||
@ -102,7 +106,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*int32)(ptr)) = iter.ReadInt32()
|
*((*int32)(ptr)) = iter.ReadInt32()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("uint32", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("uint32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxUint32) || val < 0 {
|
if val > float64(math.MaxUint32) || val < 0 {
|
||||||
@ -114,7 +118,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*uint32)(ptr)) = iter.ReadUint32()
|
*((*uint32)(ptr)) = iter.ReadUint32()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("int64", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("int64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
|
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
|
||||||
@ -126,7 +130,7 @@ func RegisterFuzzyDecoders() {
|
|||||||
*((*int64)(ptr)) = iter.ReadInt64()
|
*((*int64)(ptr)) = iter.ReadInt64()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
jsoniter.RegisterTypeDecoder("uint64", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
jsoniter.RegisterTypeDecoder("uint64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if isFloat {
|
if isFloat {
|
||||||
val := iter.ReadFloat64()
|
val := iter.ReadFloat64()
|
||||||
if val > float64(math.MaxUint64) || val < 0 {
|
if val > float64(math.MaxUint64) || val < 0 {
|
||||||
@ -156,99 +160,119 @@ type tolerateEmptyArrayDecoder struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
if iter.WhatIsNext() == jsoniter.Array {
|
if iter.WhatIsNext() == jsoniter.ArrayValue {
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
newIter := iter.Config().BorrowIterator([]byte("{}"))
|
newIter := iter.Pool().BorrowIterator([]byte("{}"))
|
||||||
defer iter.Config().ReturnIterator(newIter)
|
defer iter.Pool().ReturnIterator(newIter)
|
||||||
decoder.valDecoder.Decode(ptr, newIter)
|
decoder.valDecoder.Decode(ptr, newIter)
|
||||||
} else {
|
} else {
|
||||||
decoder.valDecoder.Decode(ptr, iter)
|
decoder.valDecoder.Decode(ptr, iter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type FuzzyStringDecoder struct {
|
type fuzzyStringDecoder struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *FuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
func (decoder *fuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
valueType := iter.WhatIsNext()
|
valueType := iter.WhatIsNext()
|
||||||
switch valueType {
|
switch valueType {
|
||||||
case jsoniter.Number:
|
case jsoniter.NumberValue:
|
||||||
var number json.Number
|
var number json.Number
|
||||||
iter.ReadVal(&number)
|
iter.ReadVal(&number)
|
||||||
*((*string)(ptr)) = string(number)
|
*((*string)(ptr)) = string(number)
|
||||||
case jsoniter.String:
|
case jsoniter.StringValue:
|
||||||
*((*string)(ptr)) = iter.ReadString()
|
*((*string)(ptr)) = iter.ReadString()
|
||||||
default:
|
default:
|
||||||
iter.ReportError("FuzzyStringDecoder", "not number or string")
|
iter.ReportError("fuzzyStringDecoder", "not number or string")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type FuzzyIntegerDecoder struct {
|
type fuzzyIntegerDecoder struct {
|
||||||
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
|
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *FuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
func (decoder *fuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
valueType := iter.WhatIsNext()
|
valueType := iter.WhatIsNext()
|
||||||
var str string
|
var str string
|
||||||
switch valueType {
|
switch valueType {
|
||||||
case jsoniter.Number:
|
case jsoniter.NumberValue:
|
||||||
var number json.Number
|
var number json.Number
|
||||||
iter.ReadVal(&number)
|
iter.ReadVal(&number)
|
||||||
str = string(number)
|
str = string(number)
|
||||||
case jsoniter.String:
|
case jsoniter.StringValue:
|
||||||
str = iter.ReadString()
|
str = iter.ReadString()
|
||||||
|
case jsoniter.BoolValue:
|
||||||
|
if iter.ReadBool() {
|
||||||
|
str = "1"
|
||||||
|
} else {
|
||||||
|
str = "0"
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
iter.ReportError("FuzzyIntegerDecoder", "not number or string")
|
iter.ReportError("fuzzyIntegerDecoder", "not number or string")
|
||||||
}
|
}
|
||||||
newIter := iter.Config().BorrowIterator([]byte(str))
|
newIter := iter.Pool().BorrowIterator([]byte(str))
|
||||||
defer iter.Config().ReturnIterator(newIter)
|
defer iter.Pool().ReturnIterator(newIter)
|
||||||
isFloat := strings.IndexByte(str, '.') != -1
|
isFloat := strings.IndexByte(str, '.') != -1
|
||||||
decoder.fun(isFloat, ptr, newIter)
|
decoder.fun(isFloat, ptr, newIter)
|
||||||
if newIter.Error != nil {
|
if newIter.Error != nil && newIter.Error != io.EOF {
|
||||||
iter.Error = newIter.Error
|
iter.Error = newIter.Error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type FuzzyFloat32Decoder struct {
|
type fuzzyFloat32Decoder struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *FuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
func (decoder *fuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
valueType := iter.WhatIsNext()
|
valueType := iter.WhatIsNext()
|
||||||
var str string
|
var str string
|
||||||
switch valueType {
|
switch valueType {
|
||||||
case jsoniter.Number:
|
case jsoniter.NumberValue:
|
||||||
*((*float32)(ptr)) = iter.ReadFloat32()
|
*((*float32)(ptr)) = iter.ReadFloat32()
|
||||||
case jsoniter.String:
|
case jsoniter.StringValue:
|
||||||
str = iter.ReadString()
|
str = iter.ReadString()
|
||||||
newIter := iter.Config().BorrowIterator([]byte(str))
|
newIter := iter.Pool().BorrowIterator([]byte(str))
|
||||||
defer iter.Config().ReturnIterator(newIter)
|
defer iter.Pool().ReturnIterator(newIter)
|
||||||
*((*float32)(ptr)) = newIter.ReadFloat32()
|
*((*float32)(ptr)) = newIter.ReadFloat32()
|
||||||
if newIter.Error != nil {
|
if newIter.Error != nil && newIter.Error != io.EOF {
|
||||||
iter.Error = newIter.Error
|
iter.Error = newIter.Error
|
||||||
}
|
}
|
||||||
|
case jsoniter.BoolValue:
|
||||||
|
// support bool to float32
|
||||||
|
if iter.ReadBool() {
|
||||||
|
*((*float32)(ptr)) = 1
|
||||||
|
} else {
|
||||||
|
*((*float32)(ptr)) = 0
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
iter.ReportError("FuzzyFloat32Decoder", "not number or string")
|
iter.ReportError("fuzzyFloat32Decoder", "not number or string")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type FuzzyFloat64Decoder struct {
|
type fuzzyFloat64Decoder struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *FuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
func (decoder *fuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
valueType := iter.WhatIsNext()
|
valueType := iter.WhatIsNext()
|
||||||
var str string
|
var str string
|
||||||
switch valueType {
|
switch valueType {
|
||||||
case jsoniter.Number:
|
case jsoniter.NumberValue:
|
||||||
*((*float64)(ptr)) = iter.ReadFloat64()
|
*((*float64)(ptr)) = iter.ReadFloat64()
|
||||||
case jsoniter.String:
|
case jsoniter.StringValue:
|
||||||
str = iter.ReadString()
|
str = iter.ReadString()
|
||||||
newIter := iter.Config().BorrowIterator([]byte(str))
|
newIter := iter.Pool().BorrowIterator([]byte(str))
|
||||||
defer iter.Config().ReturnIterator(newIter)
|
defer iter.Pool().ReturnIterator(newIter)
|
||||||
*((*float64)(ptr)) = newIter.ReadFloat64()
|
*((*float64)(ptr)) = newIter.ReadFloat64()
|
||||||
if newIter.Error != nil {
|
if newIter.Error != nil && newIter.Error != io.EOF {
|
||||||
iter.Error = newIter.Error
|
iter.Error = newIter.Error
|
||||||
}
|
}
|
||||||
|
case jsoniter.BoolValue:
|
||||||
|
// support bool to float64
|
||||||
|
if iter.ReadBool() {
|
||||||
|
*((*float64)(ptr)) = 1
|
||||||
|
} else {
|
||||||
|
*((*float64)(ptr)) = 0
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
iter.ReportError("FuzzyFloat32Decoder", "not number or string")
|
iter.ReportError("fuzzyFloat32Decoder", "not number or string")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,89 +1,326 @@
|
|||||||
package extra
|
package extra
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go"
|
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/json-iterator/go"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
RegisterFuzzyDecoders()
|
RegisterFuzzyDecoders()
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_string_to_string(t *testing.T) {
|
func Test_any_to_string(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
var val string
|
var val string
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
should.Equal("100", val)
|
should.Equal("100", val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString("10", &val))
|
||||||
|
should.Equal("10", val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString("10.1", &val))
|
||||||
|
should.Equal("10.1", val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal("10.1", val)
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
}
|
}
|
||||||
|
func Test_any_to_int64(t *testing.T) {
|
||||||
func Test_int_to_string(t *testing.T) {
|
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
var val string
|
var val int64
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`100`, &val))
|
|
||||||
should.Equal("100", val)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_float_to_string(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
var val string
|
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`12.0`, &val))
|
|
||||||
should.Equal("12.0", val)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_string_to_int(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
var val int
|
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
should.Equal(100, val)
|
should.Equal(int64(100), val)
|
||||||
}
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(int64(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(int64(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(int64(10), val)
|
||||||
|
|
||||||
func Test_int_to_int(t *testing.T) {
|
// bool part
|
||||||
should := require.New(t)
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
var val int
|
should.Equal(int64(0), val)
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`100`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
should.Equal(100, val)
|
should.Equal(int64(1), val)
|
||||||
}
|
|
||||||
|
|
||||||
func Test_float_to_int(t *testing.T) {
|
should.Nil(jsoniter.UnmarshalFromString(`-10`, &val))
|
||||||
should := require.New(t)
|
should.Equal(int64(-10), val)
|
||||||
var val int
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
should.Equal(1, val)
|
// large float to int
|
||||||
}
|
|
||||||
|
|
||||||
func Test_large_float_to_int(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
var val int
|
|
||||||
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_string_to_float32(t *testing.T) {
|
func Test_any_to_int(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val int
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(100, val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(10, val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(10, val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(10, val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(0, val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(1, val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_int16(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val int16
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(int16(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(int16(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(int16(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(int16(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(int16(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(int16(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_int32(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val int32
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(int32(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(int32(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(int32(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(int32(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(int32(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(int32(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_int8(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val int8
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(int8(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(int8(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(int8(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(int8(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(int8(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(int8(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_uint8(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val uint8
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(uint8(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(uint8(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(uint8(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(uint8(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(uint8(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(uint8(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_uint64(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val uint64
|
||||||
|
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(uint64(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(uint64(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(uint64(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(uint64(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(uint64(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(uint64(1), val)
|
||||||
|
|
||||||
|
// TODO fix?
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
|
||||||
|
should.Equal(uint64(0), val)
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
func Test_any_to_uint32(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val uint32
|
||||||
|
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(uint32(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(uint32(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(uint32(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(uint32(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(uint32(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(uint32(1), val)
|
||||||
|
|
||||||
|
// TODO fix?
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
|
||||||
|
should.Equal(uint32(0), val)
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
func Test_any_to_uint16(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val uint16
|
||||||
|
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(uint16(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(uint16(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(uint16(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(uint16(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(uint16(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(uint16(1), val)
|
||||||
|
|
||||||
|
// TODO fix?
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
|
||||||
|
should.Equal(uint16(0), val)
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
func Test_any_to_uint(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var val uint
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
|
should.Equal(uint(100), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(uint(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(uint(10), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(uint(10), val)
|
||||||
|
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(uint(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(uint(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
|
// large float to int
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_any_to_float32(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
var val float32
|
var val float32
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
should.Equal(float32(100), val)
|
should.Equal(float32(100), val)
|
||||||
|
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
|
should.Equal(float32(10.1), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
|
should.Equal(float32(10.1), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(float32(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(float32(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(float32(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_float_to_float32(t *testing.T) {
|
func Test_any_to_float64(t *testing.T) {
|
||||||
should := require.New(t)
|
|
||||||
var val float32
|
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
|
|
||||||
should.Equal(float32(1.23), val)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_string_to_float64(t *testing.T) {
|
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
var val float64
|
var val float64
|
||||||
|
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||||
should.Equal(float64(100), val)
|
should.Equal(float64(100), val)
|
||||||
}
|
|
||||||
|
|
||||||
func Test_float_to_float64(t *testing.T) {
|
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
|
||||||
should := require.New(t)
|
should.Equal(float64(10.1), val)
|
||||||
var val float64
|
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
|
||||||
should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
|
should.Equal(float64(10.1), val)
|
||||||
should.Equal(float64(1.23), val)
|
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
|
||||||
|
should.Equal(float64(10), val)
|
||||||
|
|
||||||
|
// bool part
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
|
||||||
|
should.Equal(float64(0), val)
|
||||||
|
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
|
||||||
|
should.Equal(float64(1), val)
|
||||||
|
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
|
||||||
|
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_empty_array_as_map(t *testing.T) {
|
func Test_empty_array_as_map(t *testing.T) {
|
||||||
@ -99,3 +336,24 @@ func Test_empty_array_as_object(t *testing.T) {
|
|||||||
should.Nil(jsoniter.UnmarshalFromString(`[]`, &val))
|
should.Nil(jsoniter.UnmarshalFromString(`[]`, &val))
|
||||||
should.Equal(struct{}{}, val)
|
should.Equal(struct{}{}, val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_bad_case(t *testing.T) {
|
||||||
|
var jsonstr = `
|
||||||
|
{
|
||||||
|
"extra_type": 181760,
|
||||||
|
"combo_type": 0,
|
||||||
|
"trigger_time_ms": 1498800398000,
|
||||||
|
"_create_time": "2017-06-16 11:21:39",
|
||||||
|
"_msg_type": 41000
|
||||||
|
}
|
||||||
|
`
|
||||||
|
|
||||||
|
type OrderEventRequestParams struct {
|
||||||
|
ExtraType uint64 `json:"extra_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var a OrderEventRequestParams
|
||||||
|
err := jsoniter.UnmarshalFromString(jsonstr, &a)
|
||||||
|
should := require.New(t)
|
||||||
|
should.Nil(err)
|
||||||
|
}
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetNamingStrategy rename struct fields uniformly
|
||||||
func SetNamingStrategy(translate func(string) string) {
|
func SetNamingStrategy(translate func(string) string) {
|
||||||
jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})
|
jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})
|
||||||
}
|
}
|
||||||
@ -21,6 +22,7 @@ func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescripto
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
|
||||||
func LowerCaseWithUnderscores(name string) string {
|
func LowerCaseWithUnderscores(name string) string {
|
||||||
newName := []rune{}
|
newName := []rune{}
|
||||||
for i, c := range name {
|
for i, c := range name {
|
||||||
|
@ -2,7 +2,7 @@ package extra
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go"
|
"github.com/json-iterator/go"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SupportPrivateFields include private fields when encoding/decoding
|
||||||
func SupportPrivateFields() {
|
func SupportPrivateFields() {
|
||||||
jsoniter.RegisterExtension(&privateFieldsExtension{})
|
jsoniter.RegisterExtension(&privateFieldsExtension{})
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@ package extra
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go"
|
"github.com/json-iterator/go"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ import (
|
|||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
// keep epoch milliseconds
|
// RegisterTimeAsInt64Codec encode/decode time since number of unit since epoch. the precision is the unit.
|
||||||
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
||||||
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
||||||
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
|
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
|
||||||
|
@ -2,7 +2,7 @@ package extra
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go"
|
"github.com/json-iterator/go"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@ -19,6 +19,7 @@ func Test_time_as_int64(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
||||||
|
t.Skip("conflict")
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
RegisterTimeAsInt64Codec(time.Microsecond)
|
RegisterTimeAsInt64Codec(time.Microsecond)
|
||||||
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
||||||
|
@ -1,14 +1,3 @@
|
|||||||
// Package jsoniter implements encoding and decoding of JSON as defined in
|
|
||||||
// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json.
|
|
||||||
// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter
|
|
||||||
// and variable type declarations (if any).
|
|
||||||
// jsoniter interfaces gives 100% compatibility with code using standard lib.
|
|
||||||
//
|
|
||||||
// "JSON and Go"
|
|
||||||
// (https://golang.org/doc/articles/json_and_go.html)
|
|
||||||
// gives a description of how Marshal/Unmarshal operate
|
|
||||||
// between arbitrary or predefined json objects and bytes,
|
|
||||||
// and it applies to jsoniter.Marshal/Unmarshal as well.
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@ -16,6 +5,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// RawMessage to make replace json with jsoniter
|
||||||
type RawMessage []byte
|
type RawMessage []byte
|
||||||
|
|
||||||
// Unmarshal adapts to json/encoding Unmarshal API
|
// Unmarshal adapts to json/encoding Unmarshal API
|
||||||
@ -35,10 +25,12 @@ func lastNotSpacePos(data []byte) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UnmarshalFromString convenient method to read from string instead of []byte
|
||||||
func UnmarshalFromString(str string, v interface{}) error {
|
func UnmarshalFromString(str string, v interface{}) error {
|
||||||
return ConfigDefault.UnmarshalFromString(str, v)
|
return ConfigDefault.UnmarshalFromString(str, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get quick method to get value from deeply nested JSON structure
|
||||||
func Get(data []byte, path ...interface{}) Any {
|
func Get(data []byte, path ...interface{}) Any {
|
||||||
return ConfigDefault.Get(data, path...)
|
return ConfigDefault.Get(data, path...)
|
||||||
}
|
}
|
||||||
@ -51,6 +43,12 @@ func Marshal(v interface{}) ([]byte, error) {
|
|||||||
return ConfigDefault.Marshal(v)
|
return ConfigDefault.Marshal(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MarshalIndent same as json.MarshalIndent. Prefix is not supported.
|
||||||
|
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
|
||||||
|
return ConfigDefault.MarshalIndent(v, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalToString convenient method to write as string instead of []byte
|
||||||
func MarshalToString(v interface{}) (string, error) {
|
func MarshalToString(v interface{}) (string, error) {
|
||||||
return ConfigDefault.MarshalToString(v)
|
return ConfigDefault.MarshalToString(v)
|
||||||
}
|
}
|
||||||
@ -71,6 +69,7 @@ type Decoder struct {
|
|||||||
iter *Iterator
|
iter *Iterator
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decode decode JSON into interface{}
|
||||||
func (adapter *Decoder) Decode(obj interface{}) error {
|
func (adapter *Decoder) Decode(obj interface{}) error {
|
||||||
adapter.iter.ReadVal(obj)
|
adapter.iter.ReadVal(obj)
|
||||||
err := adapter.iter.Error
|
err := adapter.iter.Error
|
||||||
@ -80,41 +79,49 @@ func (adapter *Decoder) Decode(obj interface{}) error {
|
|||||||
return adapter.iter.Error
|
return adapter.iter.Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// More is there more?
|
||||||
func (adapter *Decoder) More() bool {
|
func (adapter *Decoder) More() bool {
|
||||||
return adapter.iter.head != adapter.iter.tail
|
return adapter.iter.head != adapter.iter.tail
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Buffered remaining buffer
|
||||||
func (adapter *Decoder) Buffered() io.Reader {
|
func (adapter *Decoder) Buffered() io.Reader {
|
||||||
remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail]
|
remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail]
|
||||||
return bytes.NewReader(remaining)
|
return bytes.NewReader(remaining)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *Decoder) UseNumber() {
|
// UseNumber for number JSON element, use float64 or json.NumberValue (alias of string)
|
||||||
origCfg := decoder.iter.cfg.configBeforeFrozen
|
func (adapter *Decoder) UseNumber() {
|
||||||
|
origCfg := adapter.iter.cfg.configBeforeFrozen
|
||||||
origCfg.UseNumber = true
|
origCfg.UseNumber = true
|
||||||
decoder.iter.cfg = origCfg.Froze()
|
adapter.iter.cfg = origCfg.Froze().(*frozenConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewEncoder same as json.NewEncoder
|
||||||
func NewEncoder(writer io.Writer) *Encoder {
|
func NewEncoder(writer io.Writer) *Encoder {
|
||||||
return ConfigDefault.NewEncoder(writer)
|
return ConfigDefault.NewEncoder(writer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encoder same as json.Encoder
|
||||||
type Encoder struct {
|
type Encoder struct {
|
||||||
stream *Stream
|
stream *Stream
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encode encode interface{} as JSON to io.Writer
|
||||||
func (adapter *Encoder) Encode(val interface{}) error {
|
func (adapter *Encoder) Encode(val interface{}) error {
|
||||||
adapter.stream.WriteVal(val)
|
adapter.stream.WriteVal(val)
|
||||||
adapter.stream.Flush()
|
adapter.stream.Flush()
|
||||||
return adapter.stream.Error
|
return adapter.stream.Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetIndent set the indention. Prefix is not supported
|
||||||
func (adapter *Encoder) SetIndent(prefix, indent string) {
|
func (adapter *Encoder) SetIndent(prefix, indent string) {
|
||||||
adapter.stream.cfg.indentionStep = len(indent)
|
adapter.stream.cfg.indentionStep = len(indent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (adapter *Encoder) SetEscapeHTML(escapeHtml bool) {
|
// SetEscapeHTML escape html by default, set to false to disable
|
||||||
|
func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) {
|
||||||
config := adapter.stream.cfg.configBeforeFrozen
|
config := adapter.stream.cfg.configBeforeFrozen
|
||||||
config.EscapeHtml = escapeHtml
|
config.EscapeHTML = escapeHTML
|
||||||
adapter.stream.cfg = config.Froze()
|
adapter.stream.cfg = config.Froze().(*frozenConfig)
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,8 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Any generic object representation.
|
||||||
|
// The lazy json implementation holds []byte and parse lazily.
|
||||||
type Any interface {
|
type Any interface {
|
||||||
LastError() error
|
LastError() error
|
||||||
ValueType() ValueType
|
ValueType() ValueType
|
||||||
@ -25,10 +27,6 @@ type Any interface {
|
|||||||
// TODO: add Set
|
// TODO: add Set
|
||||||
Size() int
|
Size() int
|
||||||
Keys() []string
|
Keys() []string
|
||||||
// TODO: remove me
|
|
||||||
GetArray() []Any
|
|
||||||
// TODO: remove me
|
|
||||||
GetObject() map[string]Any
|
|
||||||
GetInterface() interface{}
|
GetInterface() interface{}
|
||||||
WriteTo(stream *Stream)
|
WriteTo(stream *Stream)
|
||||||
}
|
}
|
||||||
@ -47,42 +45,41 @@ func (any *baseAny) Keys() []string {
|
|||||||
return []string{}
|
return []string{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *baseAny) GetArray() []Any {
|
|
||||||
return []Any{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *baseAny) GetObject() map[string]Any {
|
|
||||||
return map[string]Any{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *baseAny) ToVal(obj interface{}) {
|
func (any *baseAny) ToVal(obj interface{}) {
|
||||||
panic("not implemented")
|
panic("not implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapInt32 turn int32 into Any interface
|
||||||
func WrapInt32(val int32) Any {
|
func WrapInt32(val int32) Any {
|
||||||
return &int32Any{baseAny{}, val}
|
return &int32Any{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapInt64 turn int64 into Any interface
|
||||||
func WrapInt64(val int64) Any {
|
func WrapInt64(val int64) Any {
|
||||||
return &int64Any{baseAny{}, val}
|
return &int64Any{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapUint32 turn uint32 into Any interface
|
||||||
func WrapUint32(val uint32) Any {
|
func WrapUint32(val uint32) Any {
|
||||||
return &uint32Any{baseAny{}, val}
|
return &uint32Any{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapUint64 turn uint64 into Any interface
|
||||||
func WrapUint64(val uint64) Any {
|
func WrapUint64(val uint64) Any {
|
||||||
return &uint64Any{baseAny{}, val}
|
return &uint64Any{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapFloat64 turn float64 into Any interface
|
||||||
func WrapFloat64(val float64) Any {
|
func WrapFloat64(val float64) Any {
|
||||||
return &floatAny{baseAny{}, val}
|
return &floatAny{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapString turn string into Any interface
|
||||||
func WrapString(val string) Any {
|
func WrapString(val string) Any {
|
||||||
return &stringAny{baseAny{}, val}
|
return &stringAny{baseAny{}, val}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Wrap turn a go object into Any interface
|
||||||
func Wrap(val interface{}) Any {
|
func Wrap(val interface{}) Any {
|
||||||
if val == nil {
|
if val == nil {
|
||||||
return &nilAny{}
|
return &nilAny{}
|
||||||
@ -91,8 +88,8 @@ func Wrap(val interface{}) Any {
|
|||||||
if isAny {
|
if isAny {
|
||||||
return asAny
|
return asAny
|
||||||
}
|
}
|
||||||
type_ := reflect.TypeOf(val)
|
typ := reflect.TypeOf(val)
|
||||||
switch type_.Kind() {
|
switch typ.Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
return wrapArray(val)
|
return wrapArray(val)
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
@ -128,13 +125,13 @@ func Wrap(val interface{}) Any {
|
|||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
if val.(bool) == true {
|
if val.(bool) == true {
|
||||||
return &trueAny{}
|
return &trueAny{}
|
||||||
} else {
|
|
||||||
return &falseAny{}
|
|
||||||
}
|
}
|
||||||
|
return &falseAny{}
|
||||||
}
|
}
|
||||||
return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", type_)}
|
return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadAny read next JSON element as an Any object. It is a better json.RawMessage.
|
||||||
func (iter *Iterator) ReadAny() Any {
|
func (iter *Iterator) ReadAny() Any {
|
||||||
return iter.readAny()
|
return iter.readAny()
|
||||||
}
|
}
|
||||||
@ -146,13 +143,13 @@ func (iter *Iterator) readAny() Any {
|
|||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
return &stringAny{baseAny{}, iter.ReadString()}
|
return &stringAny{baseAny{}, iter.ReadString()}
|
||||||
case 'n':
|
case 'n':
|
||||||
iter.skipFixedBytes(3) // null
|
iter.skipThreeBytes('u', 'l', 'l') // null
|
||||||
return &nilAny{}
|
return &nilAny{}
|
||||||
case 't':
|
case 't':
|
||||||
iter.skipFixedBytes(3) // true
|
iter.skipThreeBytes('r', 'u', 'e') // true
|
||||||
return &trueAny{}
|
return &trueAny{}
|
||||||
case 'f':
|
case 'f':
|
||||||
iter.skipFixedBytes(4) // false
|
iter.skipFourBytes('a', 'l', 's', 'e') // false
|
||||||
return &falseAny{}
|
return &falseAny{}
|
||||||
case '{':
|
case '{':
|
||||||
return iter.readObjectAny()
|
return iter.readObjectAny()
|
||||||
@ -232,9 +229,8 @@ func locatePath(iter *Iterator, path []interface{}) Any {
|
|||||||
case int32:
|
case int32:
|
||||||
if '*' == pathKey {
|
if '*' == pathKey {
|
||||||
return iter.readAny().Get(path[i:]...)
|
return iter.readAny().Get(path[i:]...)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path[i:])
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path[i:])
|
||||||
default:
|
default:
|
||||||
return newInvalidAny(path[i:])
|
return newInvalidAny(path[i:])
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ type arrayLazyAny struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ValueType() ValueType {
|
func (any *arrayLazyAny) ValueType() ValueType {
|
||||||
return Array
|
return ArrayValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) MustBeValid() Any {
|
func (any *arrayLazyAny) MustBeValid() Any {
|
||||||
@ -33,65 +33,57 @@ func (any *arrayLazyAny) ToBool() bool {
|
|||||||
func (any *arrayLazyAny) ToInt() int {
|
func (any *arrayLazyAny) ToInt() int {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToInt32() int32 {
|
func (any *arrayLazyAny) ToInt32() int32 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToInt64() int64 {
|
func (any *arrayLazyAny) ToInt64() int64 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToUint() uint {
|
func (any *arrayLazyAny) ToUint() uint {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToUint32() uint32 {
|
func (any *arrayLazyAny) ToUint32() uint32 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToUint64() uint64 {
|
func (any *arrayLazyAny) ToUint64() uint64 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToFloat32() float32 {
|
func (any *arrayLazyAny) ToFloat32() float32 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToFloat64() float64 {
|
func (any *arrayLazyAny) ToFloat64() float64 {
|
||||||
if any.ToBool() {
|
if any.ToBool() {
|
||||||
return 1
|
return 1
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) ToString() string {
|
func (any *arrayLazyAny) ToString() string {
|
||||||
@ -115,10 +107,9 @@ func (any *arrayLazyAny) Get(path ...interface{}) Any {
|
|||||||
valueBytes := locateArrayElement(iter, firstPath)
|
valueBytes := locateArrayElement(iter, firstPath)
|
||||||
if valueBytes == nil {
|
if valueBytes == nil {
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
} else {
|
|
||||||
iter.ResetBytes(valueBytes)
|
|
||||||
return locatePath(iter, path[1:])
|
|
||||||
}
|
}
|
||||||
|
iter.ResetBytes(valueBytes)
|
||||||
|
return locatePath(iter, path[1:])
|
||||||
case int32:
|
case int32:
|
||||||
if '*' == firstPath {
|
if '*' == firstPath {
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
iter := any.cfg.BorrowIterator(any.buf)
|
||||||
@ -126,15 +117,14 @@ func (any *arrayLazyAny) Get(path ...interface{}) Any {
|
|||||||
arr := make([]Any, 0)
|
arr := make([]Any, 0)
|
||||||
iter.ReadArrayCB(func(iter *Iterator) bool {
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
found := iter.readAny().Get(path[1:]...)
|
found := iter.readAny().Get(path[1:]...)
|
||||||
if found.ValueType() != Invalid {
|
if found.ValueType() != InvalidValue {
|
||||||
arr = append(arr, found)
|
arr = append(arr, found)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return wrapArray(arr)
|
return wrapArray(arr)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path)
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path)
|
||||||
default:
|
default:
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
}
|
}
|
||||||
@ -152,17 +142,6 @@ func (any *arrayLazyAny) Size() int {
|
|||||||
return size
|
return size
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayLazyAny) GetArray() []Any {
|
|
||||||
elements := make([]Any, 0)
|
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
|
||||||
defer any.cfg.ReturnIterator(iter)
|
|
||||||
iter.ReadArrayCB(func(iter *Iterator) bool {
|
|
||||||
elements = append(elements, iter.ReadAny())
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return elements
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *arrayLazyAny) WriteTo(stream *Stream) {
|
func (any *arrayLazyAny) WriteTo(stream *Stream) {
|
||||||
stream.Write(any.buf)
|
stream.Write(any.buf)
|
||||||
}
|
}
|
||||||
@ -183,7 +162,7 @@ func wrapArray(val interface{}) *arrayAny {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayAny) ValueType() ValueType {
|
func (any *arrayAny) ValueType() ValueType {
|
||||||
return Array
|
return ArrayValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayAny) MustBeValid() Any {
|
func (any *arrayAny) MustBeValid() Any {
|
||||||
@ -274,14 +253,13 @@ func (any *arrayAny) Get(path ...interface{}) Any {
|
|||||||
mappedAll := make([]Any, 0)
|
mappedAll := make([]Any, 0)
|
||||||
for i := 0; i < any.val.Len(); i++ {
|
for i := 0; i < any.val.Len(); i++ {
|
||||||
mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...)
|
mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...)
|
||||||
if mapped.ValueType() != Invalid {
|
if mapped.ValueType() != InvalidValue {
|
||||||
mappedAll = append(mappedAll, mapped)
|
mappedAll = append(mappedAll, mapped)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return wrapArray(mappedAll)
|
return wrapArray(mappedAll)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path)
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path)
|
||||||
default:
|
default:
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
}
|
}
|
||||||
@ -291,14 +269,6 @@ func (any *arrayAny) Size() int {
|
|||||||
return any.val.Len()
|
return any.val.Len()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *arrayAny) GetArray() []Any {
|
|
||||||
elements := make([]Any, any.val.Len())
|
|
||||||
for i := 0; i < any.val.Len(); i++ {
|
|
||||||
elements[i] = Wrap(any.val.Index(i).Interface())
|
|
||||||
}
|
|
||||||
return elements
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *arrayAny) WriteTo(stream *Stream) {
|
func (any *arrayAny) WriteTo(stream *Stream) {
|
||||||
stream.WriteVal(any.val)
|
stream.WriteVal(any.val)
|
||||||
}
|
}
|
||||||
|
@ -61,7 +61,7 @@ func (any *trueAny) GetInterface() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *trueAny) ValueType() ValueType {
|
func (any *trueAny) ValueType() ValueType {
|
||||||
return Bool
|
return BoolValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *trueAny) MustBeValid() Any {
|
func (any *trueAny) MustBeValid() Any {
|
||||||
@ -129,7 +129,7 @@ func (any *falseAny) GetInterface() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *falseAny) ValueType() ValueType {
|
func (any *falseAny) ValueType() ValueType {
|
||||||
return Bool
|
return BoolValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *falseAny) MustBeValid() Any {
|
func (any *falseAny) MustBeValid() Any {
|
||||||
|
@ -14,7 +14,7 @@ func (any *floatAny) Parse() *Iterator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) ValueType() ValueType {
|
func (any *floatAny) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) MustBeValid() Any {
|
func (any *floatAny) MustBeValid() Any {
|
||||||
@ -42,15 +42,24 @@ func (any *floatAny) ToInt64() int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) ToUint() uint {
|
func (any *floatAny) ToUint() uint {
|
||||||
return uint(any.val)
|
if any.val > 0 {
|
||||||
|
return uint(any.val)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) ToUint32() uint32 {
|
func (any *floatAny) ToUint32() uint32 {
|
||||||
return uint32(any.val)
|
if any.val > 0 {
|
||||||
|
return uint32(any.val)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) ToUint64() uint64 {
|
func (any *floatAny) ToUint64() uint64 {
|
||||||
return uint64(any.val)
|
if any.val > 0 {
|
||||||
|
return uint64(any.val)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *floatAny) ToFloat32() float32 {
|
func (any *floatAny) ToFloat32() float32 {
|
||||||
|
@ -14,7 +14,7 @@ func (any *int32Any) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *int32Any) ValueType() ValueType {
|
func (any *int32Any) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *int32Any) MustBeValid() Any {
|
func (any *int32Any) MustBeValid() Any {
|
||||||
|
@ -14,7 +14,7 @@ func (any *int64Any) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *int64Any) ValueType() ValueType {
|
func (any *int64Any) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *int64Any) MustBeValid() Any {
|
func (any *int64Any) MustBeValid() Any {
|
||||||
|
@ -16,12 +16,11 @@ func (any *invalidAny) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *invalidAny) ValueType() ValueType {
|
func (any *invalidAny) ValueType() ValueType {
|
||||||
return Invalid
|
return InvalidValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *invalidAny) MustBeValid() Any {
|
func (any *invalidAny) MustBeValid() Any {
|
||||||
panic(any.err)
|
panic(any.err)
|
||||||
return any
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *invalidAny) ToBool() bool {
|
func (any *invalidAny) ToBool() bool {
|
||||||
@ -70,9 +69,8 @@ func (any *invalidAny) WriteTo(stream *Stream) {
|
|||||||
func (any *invalidAny) Get(path ...interface{}) Any {
|
func (any *invalidAny) Get(path ...interface{}) Any {
|
||||||
if any.err == nil {
|
if any.err == nil {
|
||||||
return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)}
|
return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)}
|
||||||
} else {
|
|
||||||
return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)}
|
|
||||||
}
|
}
|
||||||
|
return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *invalidAny) Parse() *Iterator {
|
func (any *invalidAny) Parse() *Iterator {
|
||||||
|
@ -9,7 +9,7 @@ func (any *nilAny) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *nilAny) ValueType() ValueType {
|
func (any *nilAny) ValueType() ValueType {
|
||||||
return Nil
|
return NilValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *nilAny) MustBeValid() Any {
|
func (any *nilAny) MustBeValid() Any {
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import "unsafe"
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
type numberLazyAny struct {
|
type numberLazyAny struct {
|
||||||
baseAny
|
baseAny
|
||||||
@ -12,7 +10,7 @@ type numberLazyAny struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *numberLazyAny) ValueType() ValueType {
|
func (any *numberLazyAny) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *numberLazyAny) MustBeValid() Any {
|
func (any *numberLazyAny) MustBeValid() Any {
|
||||||
|
@ -13,7 +13,7 @@ type objectLazyAny struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ValueType() ValueType {
|
func (any *objectLazyAny) ValueType() ValueType {
|
||||||
return Object
|
return ObjectValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) MustBeValid() Any {
|
func (any *objectLazyAny) MustBeValid() Any {
|
||||||
@ -25,73 +25,39 @@ func (any *objectLazyAny) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToBool() bool {
|
func (any *objectLazyAny) ToBool() bool {
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
return true
|
||||||
defer any.cfg.ReturnIterator(iter)
|
|
||||||
return iter.ReadObject() != ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToInt() int {
|
func (any *objectLazyAny) ToInt() int {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToInt32() int32 {
|
func (any *objectLazyAny) ToInt32() int32 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToInt64() int64 {
|
func (any *objectLazyAny) ToInt64() int64 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToUint() uint {
|
func (any *objectLazyAny) ToUint() uint {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToUint32() uint32 {
|
func (any *objectLazyAny) ToUint32() uint32 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToUint64() uint64 {
|
func (any *objectLazyAny) ToUint64() uint64 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToFloat32() float32 {
|
func (any *objectLazyAny) ToFloat32() float32 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToFloat64() float64 {
|
func (any *objectLazyAny) ToFloat64() float64 {
|
||||||
if any.ToBool() {
|
return 0
|
||||||
return 1
|
|
||||||
} else {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) ToString() string {
|
func (any *objectLazyAny) ToString() string {
|
||||||
@ -115,26 +81,24 @@ func (any *objectLazyAny) Get(path ...interface{}) Any {
|
|||||||
valueBytes := locateObjectField(iter, firstPath)
|
valueBytes := locateObjectField(iter, firstPath)
|
||||||
if valueBytes == nil {
|
if valueBytes == nil {
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
} else {
|
|
||||||
iter.ResetBytes(valueBytes)
|
|
||||||
return locatePath(iter, path[1:])
|
|
||||||
}
|
}
|
||||||
|
iter.ResetBytes(valueBytes)
|
||||||
|
return locatePath(iter, path[1:])
|
||||||
case int32:
|
case int32:
|
||||||
if '*' == firstPath {
|
if '*' == firstPath {
|
||||||
mappedAll := map[string]Any{}
|
mappedAll := map[string]Any{}
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
iter := any.cfg.BorrowIterator(any.buf)
|
||||||
defer any.cfg.ReturnIterator(iter)
|
defer any.cfg.ReturnIterator(iter)
|
||||||
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
iter.ReadMapCB(func(iter *Iterator, field string) bool {
|
||||||
mapped := locatePath(iter, path[1:])
|
mapped := locatePath(iter, path[1:])
|
||||||
if mapped.ValueType() != Invalid {
|
if mapped.ValueType() != InvalidValue {
|
||||||
mappedAll[field] = mapped
|
mappedAll[field] = mapped
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return wrapMap(mappedAll)
|
return wrapMap(mappedAll)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path)
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path)
|
||||||
default:
|
default:
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
}
|
}
|
||||||
@ -144,7 +108,7 @@ func (any *objectLazyAny) Keys() []string {
|
|||||||
keys := []string{}
|
keys := []string{}
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
iter := any.cfg.BorrowIterator(any.buf)
|
||||||
defer any.cfg.ReturnIterator(iter)
|
defer any.cfg.ReturnIterator(iter)
|
||||||
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
iter.ReadMapCB(func(iter *Iterator, field string) bool {
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
keys = append(keys, field)
|
keys = append(keys, field)
|
||||||
return true
|
return true
|
||||||
@ -164,17 +128,6 @@ func (any *objectLazyAny) Size() int {
|
|||||||
return size
|
return size
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectLazyAny) GetObject() map[string]Any {
|
|
||||||
asMap := map[string]Any{}
|
|
||||||
iter := any.cfg.BorrowIterator(any.buf)
|
|
||||||
defer any.cfg.ReturnIterator(iter)
|
|
||||||
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
|
||||||
asMap[field] = iter.ReadAny()
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return asMap
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *objectLazyAny) WriteTo(stream *Stream) {
|
func (any *objectLazyAny) WriteTo(stream *Stream) {
|
||||||
stream.Write(any.buf)
|
stream.Write(any.buf)
|
||||||
}
|
}
|
||||||
@ -196,7 +149,7 @@ func wrapStruct(val interface{}) *objectAny {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ValueType() ValueType {
|
func (any *objectAny) ValueType() ValueType {
|
||||||
return Object
|
return ObjectValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) MustBeValid() Any {
|
func (any *objectAny) MustBeValid() Any {
|
||||||
@ -216,59 +169,35 @@ func (any *objectAny) ToBool() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToInt() int {
|
func (any *objectAny) ToInt() int {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToInt32() int32 {
|
func (any *objectAny) ToInt32() int32 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToInt64() int64 {
|
func (any *objectAny) ToInt64() int64 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToUint() uint {
|
func (any *objectAny) ToUint() uint {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToUint32() uint32 {
|
func (any *objectAny) ToUint32() uint32 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToUint64() uint64 {
|
func (any *objectAny) ToUint64() uint64 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToFloat32() float32 {
|
func (any *objectAny) ToFloat32() float32 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToFloat64() float64 {
|
func (any *objectAny) ToFloat64() float64 {
|
||||||
if any.val.NumField() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) ToString() string {
|
func (any *objectAny) ToString() string {
|
||||||
@ -295,15 +224,14 @@ func (any *objectAny) Get(path ...interface{}) Any {
|
|||||||
field := any.val.Field(i)
|
field := any.val.Field(i)
|
||||||
if field.CanInterface() {
|
if field.CanInterface() {
|
||||||
mapped := Wrap(field.Interface()).Get(path[1:]...)
|
mapped := Wrap(field.Interface()).Get(path[1:]...)
|
||||||
if mapped.ValueType() != Invalid {
|
if mapped.ValueType() != InvalidValue {
|
||||||
mappedAll[any.val.Type().Field(i).Name] = mapped
|
mappedAll[any.val.Type().Field(i).Name] = mapped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return wrapMap(mappedAll)
|
return wrapMap(mappedAll)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path)
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path)
|
||||||
default:
|
default:
|
||||||
return newInvalidAny(path)
|
return newInvalidAny(path)
|
||||||
}
|
}
|
||||||
@ -321,17 +249,6 @@ func (any *objectAny) Size() int {
|
|||||||
return any.val.NumField()
|
return any.val.NumField()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *objectAny) GetObject() map[string]Any {
|
|
||||||
object := map[string]Any{}
|
|
||||||
for i := 0; i < any.val.NumField(); i++ {
|
|
||||||
field := any.val.Field(i)
|
|
||||||
if field.CanInterface() {
|
|
||||||
object[any.val.Type().Field(i).Name] = Wrap(field.Interface())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return object
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *objectAny) WriteTo(stream *Stream) {
|
func (any *objectAny) WriteTo(stream *Stream) {
|
||||||
stream.WriteVal(any.val)
|
stream.WriteVal(any.val)
|
||||||
}
|
}
|
||||||
@ -351,7 +268,7 @@ func wrapMap(val interface{}) *mapAny {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ValueType() ValueType {
|
func (any *mapAny) ValueType() ValueType {
|
||||||
return Object
|
return ObjectValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) MustBeValid() Any {
|
func (any *mapAny) MustBeValid() Any {
|
||||||
@ -367,63 +284,39 @@ func (any *mapAny) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToBool() bool {
|
func (any *mapAny) ToBool() bool {
|
||||||
return any.val.Len() != 0
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToInt() int {
|
func (any *mapAny) ToInt() int {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToInt32() int32 {
|
func (any *mapAny) ToInt32() int32 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToInt64() int64 {
|
func (any *mapAny) ToInt64() int64 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToUint() uint {
|
func (any *mapAny) ToUint() uint {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToUint32() uint32 {
|
func (any *mapAny) ToUint32() uint32 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToUint64() uint64 {
|
func (any *mapAny) ToUint64() uint64 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToFloat32() float32 {
|
func (any *mapAny) ToFloat32() float32 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToFloat64() float64 {
|
func (any *mapAny) ToFloat64() float64 {
|
||||||
if any.val.Len() == 0 {
|
return 0
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) ToString() string {
|
func (any *mapAny) ToString() string {
|
||||||
@ -444,14 +337,13 @@ func (any *mapAny) Get(path ...interface{}) Any {
|
|||||||
keyAsStr := key.String()
|
keyAsStr := key.String()
|
||||||
element := Wrap(any.val.MapIndex(key).Interface())
|
element := Wrap(any.val.MapIndex(key).Interface())
|
||||||
mapped := element.Get(path[1:]...)
|
mapped := element.Get(path[1:]...)
|
||||||
if mapped.ValueType() != Invalid {
|
if mapped.ValueType() != InvalidValue {
|
||||||
mappedAll[keyAsStr] = mapped
|
mappedAll[keyAsStr] = mapped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return wrapMap(mappedAll)
|
return wrapMap(mappedAll)
|
||||||
} else {
|
|
||||||
return newInvalidAny(path)
|
|
||||||
}
|
}
|
||||||
|
return newInvalidAny(path)
|
||||||
default:
|
default:
|
||||||
value := any.val.MapIndex(reflect.ValueOf(firstPath))
|
value := any.val.MapIndex(reflect.ValueOf(firstPath))
|
||||||
if !value.IsValid() {
|
if !value.IsValid() {
|
||||||
@ -473,16 +365,6 @@ func (any *mapAny) Size() int {
|
|||||||
return any.val.Len()
|
return any.val.Len()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *mapAny) GetObject() map[string]Any {
|
|
||||||
object := map[string]Any{}
|
|
||||||
for _, key := range any.val.MapKeys() {
|
|
||||||
keyAsStr := key.String()
|
|
||||||
element := Wrap(any.val.MapIndex(key).Interface())
|
|
||||||
object[keyAsStr] = element
|
|
||||||
}
|
|
||||||
return object
|
|
||||||
}
|
|
||||||
|
|
||||||
func (any *mapAny) WriteTo(stream *Stream) {
|
func (any *mapAny) WriteTo(stream *Stream) {
|
||||||
stream.WriteVal(any.val)
|
stream.WriteVal(any.val)
|
||||||
}
|
}
|
||||||
|
@ -22,7 +22,7 @@ func (any *stringAny) Parse() *Iterator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ValueType() ValueType {
|
func (any *stringAny) ValueType() ValueType {
|
||||||
return String
|
return StringValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) MustBeValid() Any {
|
func (any *stringAny) MustBeValid() Any {
|
||||||
@ -35,7 +35,7 @@ func (any *stringAny) LastError() error {
|
|||||||
|
|
||||||
func (any *stringAny) ToBool() bool {
|
func (any *stringAny) ToBool() bool {
|
||||||
str := any.ToString()
|
str := any.ToString()
|
||||||
if str == "false" {
|
if str == "0" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for _, c := range str {
|
for _, c := range str {
|
||||||
@ -49,42 +49,107 @@ func (any *stringAny) ToBool() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToInt() int {
|
func (any *stringAny) ToInt() int {
|
||||||
parsed, _ := strconv.ParseInt(any.val, 10, 64)
|
return int(any.ToInt64())
|
||||||
return int(parsed)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToInt32() int32 {
|
func (any *stringAny) ToInt32() int32 {
|
||||||
parsed, _ := strconv.ParseInt(any.val, 10, 32)
|
return int32(any.ToInt64())
|
||||||
return int32(parsed)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToInt64() int64 {
|
func (any *stringAny) ToInt64() int64 {
|
||||||
parsed, _ := strconv.ParseInt(any.val, 10, 64)
|
if any.val == "" {
|
||||||
return parsed
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
flag := 1
|
||||||
|
startPos := 0
|
||||||
|
endPos := 0
|
||||||
|
if any.val[0] == '+' || any.val[0] == '-' {
|
||||||
|
startPos = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if any.val[0] == '-' {
|
||||||
|
flag = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := startPos; i < len(any.val); i++ {
|
||||||
|
if any.val[i] >= '0' && any.val[i] <= '9' {
|
||||||
|
endPos = i + 1
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64)
|
||||||
|
return int64(flag) * parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToUint() uint {
|
func (any *stringAny) ToUint() uint {
|
||||||
parsed, _ := strconv.ParseUint(any.val, 10, 64)
|
return uint(any.ToUint64())
|
||||||
return uint(parsed)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToUint32() uint32 {
|
func (any *stringAny) ToUint32() uint32 {
|
||||||
parsed, _ := strconv.ParseUint(any.val, 10, 32)
|
return uint32(any.ToUint64())
|
||||||
return uint32(parsed)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToUint64() uint64 {
|
func (any *stringAny) ToUint64() uint64 {
|
||||||
parsed, _ := strconv.ParseUint(any.val, 10, 64)
|
if any.val == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
startPos := 0
|
||||||
|
endPos := 0
|
||||||
|
|
||||||
|
if any.val[0] == '-' {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if any.val[0] == '+' {
|
||||||
|
startPos = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := startPos; i < len(any.val); i++ {
|
||||||
|
if any.val[i] >= '0' && any.val[i] <= '9' {
|
||||||
|
endPos = i + 1
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64)
|
||||||
return parsed
|
return parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToFloat32() float32 {
|
func (any *stringAny) ToFloat32() float32 {
|
||||||
parsed, _ := strconv.ParseFloat(any.val, 32)
|
return float32(any.ToFloat64())
|
||||||
return float32(parsed)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *stringAny) ToFloat64() float64 {
|
func (any *stringAny) ToFloat64() float64 {
|
||||||
parsed, _ := strconv.ParseFloat(any.val, 64)
|
if len(any.val) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// first char invalid
|
||||||
|
if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract valid num expression from string
|
||||||
|
// eg 123true => 123, -12.12xxa => -12.12
|
||||||
|
endPos := 1
|
||||||
|
for i := 1; i < len(any.val); i++ {
|
||||||
|
if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' {
|
||||||
|
endPos = i + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// end position is the first char which is not digit
|
||||||
|
if any.val[i] >= '0' && any.val[i] <= '9' {
|
||||||
|
endPos = i + 1
|
||||||
|
} else {
|
||||||
|
endPos = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parsed, _ := strconv.ParseFloat(any.val[:endPos], 64)
|
||||||
return parsed
|
return parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -14,7 +14,7 @@ func (any *uint32Any) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *uint32Any) ValueType() ValueType {
|
func (any *uint32Any) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *uint32Any) MustBeValid() Any {
|
func (any *uint32Any) MustBeValid() Any {
|
||||||
|
@ -14,7 +14,7 @@ func (any *uint64Any) LastError() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (any *uint64Any) ValueType() ValueType {
|
func (any *uint64Any) ValueType() ValueType {
|
||||||
return Number
|
return NumberValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (any *uint64Any) MustBeValid() Any {
|
func (any *uint64Any) MustBeValid() Any {
|
||||||
|
@ -9,12 +9,16 @@ import (
|
|||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Config customize how the API should behave.
|
||||||
|
// The API is created from Config by Froze.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
IndentionStep int
|
IndentionStep int
|
||||||
MarshalFloatWith6Digits bool
|
MarshalFloatWith6Digits bool
|
||||||
EscapeHtml bool
|
EscapeHTML bool
|
||||||
SortMapKeys bool
|
SortMapKeys bool
|
||||||
UseNumber bool
|
UseNumber bool
|
||||||
|
TagKey string
|
||||||
|
ValidateJsonRawMessage bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type frozenConfig struct {
|
type frozenConfig struct {
|
||||||
@ -28,9 +32,14 @@ type frozenConfig struct {
|
|||||||
iteratorPool chan *Iterator
|
iteratorPool chan *Iterator
|
||||||
}
|
}
|
||||||
|
|
||||||
type Api interface {
|
// API the public interface of this package.
|
||||||
|
// Primary Marshal and Unmarshal.
|
||||||
|
type API interface {
|
||||||
|
IteratorPool
|
||||||
|
StreamPool
|
||||||
MarshalToString(v interface{}) (string, error)
|
MarshalToString(v interface{}) (string, error)
|
||||||
Marshal(v interface{}) ([]byte, error)
|
Marshal(v interface{}) ([]byte, error)
|
||||||
|
MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
|
||||||
UnmarshalFromString(str string, v interface{}) error
|
UnmarshalFromString(str string, v interface{}) error
|
||||||
Unmarshal(data []byte, v interface{}) error
|
Unmarshal(data []byte, v interface{}) error
|
||||||
Get(data []byte, path ...interface{}) Any
|
Get(data []byte, path ...interface{}) Any
|
||||||
@ -38,21 +47,27 @@ type Api interface {
|
|||||||
NewDecoder(reader io.Reader) *Decoder
|
NewDecoder(reader io.Reader) *Decoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConfigDefault the default API
|
||||||
var ConfigDefault = Config{
|
var ConfigDefault = Config{
|
||||||
EscapeHtml: true,
|
EscapeHTML: true,
|
||||||
}.Froze()
|
}.Froze()
|
||||||
|
|
||||||
// Trying to be 100% compatible with standard library behavior
|
// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
|
||||||
var ConfigCompatibleWithStandardLibrary = Config{
|
var ConfigCompatibleWithStandardLibrary = Config{
|
||||||
EscapeHtml: true,
|
EscapeHTML: true,
|
||||||
SortMapKeys: true,
|
SortMapKeys: true,
|
||||||
|
ValidateJsonRawMessage: true,
|
||||||
}.Froze()
|
}.Froze()
|
||||||
|
|
||||||
|
// ConfigFastest marshals float with only 6 digits precision
|
||||||
var ConfigFastest = Config{
|
var ConfigFastest = Config{
|
||||||
|
EscapeHTML: false,
|
||||||
MarshalFloatWith6Digits: true,
|
MarshalFloatWith6Digits: true,
|
||||||
}.Froze()
|
}.Froze()
|
||||||
|
|
||||||
func (cfg Config) Froze() *frozenConfig {
|
// Froze forge API from config
|
||||||
|
func (cfg Config) Froze() API {
|
||||||
|
// TODO: cache frozen config
|
||||||
frozenConfig := &frozenConfig{
|
frozenConfig := &frozenConfig{
|
||||||
sortMapKeys: cfg.SortMapKeys,
|
sortMapKeys: cfg.SortMapKeys,
|
||||||
indentionStep: cfg.IndentionStep,
|
indentionStep: cfg.IndentionStep,
|
||||||
@ -64,25 +79,53 @@ func (cfg Config) Froze() *frozenConfig {
|
|||||||
if cfg.MarshalFloatWith6Digits {
|
if cfg.MarshalFloatWith6Digits {
|
||||||
frozenConfig.marshalFloatWith6Digits()
|
frozenConfig.marshalFloatWith6Digits()
|
||||||
}
|
}
|
||||||
if cfg.EscapeHtml {
|
if cfg.EscapeHTML {
|
||||||
frozenConfig.escapeHtml()
|
frozenConfig.escapeHTML()
|
||||||
}
|
}
|
||||||
if cfg.UseNumber {
|
if cfg.UseNumber {
|
||||||
frozenConfig.useNumber()
|
frozenConfig.useNumber()
|
||||||
}
|
}
|
||||||
|
if cfg.ValidateJsonRawMessage {
|
||||||
|
frozenConfig.validateJsonRawMessage()
|
||||||
|
}
|
||||||
frozenConfig.configBeforeFrozen = cfg
|
frozenConfig.configBeforeFrozen = cfg
|
||||||
return frozenConfig
|
return frozenConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cfg *frozenConfig) validateJsonRawMessage() {
|
||||||
|
encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
|
||||||
|
rawMessage := *(*json.RawMessage)(ptr)
|
||||||
|
iter := cfg.BorrowIterator([]byte(rawMessage))
|
||||||
|
iter.Read()
|
||||||
|
if iter.Error != nil {
|
||||||
|
stream.WriteRaw("null")
|
||||||
|
} else {
|
||||||
|
cfg.ReturnIterator(iter)
|
||||||
|
stream.WriteRaw(string(rawMessage))
|
||||||
|
}
|
||||||
|
}, func(ptr unsafe.Pointer) bool {
|
||||||
|
return false
|
||||||
|
}}
|
||||||
|
cfg.addEncoderToCache(reflect.TypeOf((*json.RawMessage)(nil)).Elem(), encoder)
|
||||||
|
cfg.addEncoderToCache(reflect.TypeOf((*RawMessage)(nil)).Elem(), encoder)
|
||||||
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) useNumber() {
|
func (cfg *frozenConfig) useNumber() {
|
||||||
cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
|
cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
if iter.WhatIsNext() == Number {
|
if iter.WhatIsNext() == NumberValue {
|
||||||
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
|
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
|
||||||
} else {
|
} else {
|
||||||
*((*interface{})(ptr)) = iter.Read()
|
*((*interface{})(ptr)) = iter.Read()
|
||||||
}
|
}
|
||||||
}})
|
}})
|
||||||
}
|
}
|
||||||
|
func (cfg *frozenConfig) getTagKey() string {
|
||||||
|
tagKey := cfg.configBeforeFrozen.TagKey
|
||||||
|
if tagKey == "" {
|
||||||
|
return "json"
|
||||||
|
}
|
||||||
|
return tagKey
|
||||||
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) registerExtension(extension Extension) {
|
func (cfg *frozenConfig) registerExtension(extension Extension) {
|
||||||
cfg.extensions = append(cfg.extensions, extension)
|
cfg.extensions = append(cfg.extensions, extension)
|
||||||
@ -131,7 +174,7 @@ type htmlEscapedStringEncoder struct {
|
|||||||
|
|
||||||
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
str := *((*string)(ptr))
|
str := *((*string)(ptr))
|
||||||
stream.WriteStringWithHtmlEscaped(str)
|
stream.WriteStringWithHTMLEscaped(str)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
@ -142,8 +185,7 @@ func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
|||||||
return *((*string)(ptr)) == ""
|
return *((*string)(ptr)) == ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) escapeHtml() {
|
func (cfg *frozenConfig) escapeHTML() {
|
||||||
// for better performance
|
|
||||||
cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
|
cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,18 +229,16 @@ func (cfg *frozenConfig) getEncoderFromCache(cacheKey reflect.Type) ValEncoder {
|
|||||||
return cache[cacheKey]
|
return cache[cacheKey]
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanDecoders cleans decoders registered or cached
|
|
||||||
func (cfg *frozenConfig) cleanDecoders() {
|
func (cfg *frozenConfig) cleanDecoders() {
|
||||||
typeDecoders = map[string]ValDecoder{}
|
typeDecoders = map[string]ValDecoder{}
|
||||||
fieldDecoders = map[string]ValDecoder{}
|
fieldDecoders = map[string]ValDecoder{}
|
||||||
atomic.StorePointer(&cfg.decoderCache, unsafe.Pointer(&map[string]ValDecoder{}))
|
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanEncoders cleans encoders registered or cached
|
|
||||||
func (cfg *frozenConfig) cleanEncoders() {
|
func (cfg *frozenConfig) cleanEncoders() {
|
||||||
typeEncoders = map[string]ValEncoder{}
|
typeEncoders = map[string]ValEncoder{}
|
||||||
fieldEncoders = map[string]ValEncoder{}
|
fieldEncoders = map[string]ValEncoder{}
|
||||||
atomic.StorePointer(&cfg.encoderCache, unsafe.Pointer(&map[string]ValEncoder{}))
|
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
|
func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
|
||||||
@ -224,6 +264,20 @@ func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
|
|||||||
return copied, nil
|
return copied, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
|
||||||
|
if prefix != "" {
|
||||||
|
panic("prefix is not supported")
|
||||||
|
}
|
||||||
|
for _, r := range indent {
|
||||||
|
if r != ' ' {
|
||||||
|
panic("indent can only be space")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newCfg := cfg.configBeforeFrozen
|
||||||
|
newCfg.IndentionStep = len(indent)
|
||||||
|
return newCfg.Froze().Marshal(v)
|
||||||
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
|
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
|
||||||
data := []byte(str)
|
data := []byte(str)
|
||||||
data = data[:lastNotSpacePos(data)]
|
data = data[:lastNotSpacePos(data)]
|
||||||
|
147
feature_iter.go
147
feature_iter.go
@ -1,26 +1,29 @@
|
|||||||
//
|
|
||||||
// Besides, jsoniter.Iterator provides a different set of interfaces
|
|
||||||
// iterating given bytes/string/reader
|
|
||||||
// and yielding parsed elements one by one.
|
|
||||||
// This set of interfaces reads input as required and gives
|
|
||||||
// better performance.
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ValueType the type for JSON element
|
||||||
type ValueType int
|
type ValueType int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
Invalid ValueType = iota
|
// InvalidValue invalid JSON element
|
||||||
String
|
InvalidValue ValueType = iota
|
||||||
Number
|
// StringValue JSON element "string"
|
||||||
Nil
|
StringValue
|
||||||
Bool
|
// NumberValue JSON element 100 or 0.10
|
||||||
Array
|
NumberValue
|
||||||
Object
|
// NilValue JSON element null
|
||||||
|
NilValue
|
||||||
|
// BoolValue JSON element true or false
|
||||||
|
BoolValue
|
||||||
|
// ArrayValue JSON element []
|
||||||
|
ArrayValue
|
||||||
|
// ObjectValue JSON element {}
|
||||||
|
ObjectValue
|
||||||
)
|
)
|
||||||
|
|
||||||
var hexDigits []byte
|
var hexDigits []byte
|
||||||
@ -42,28 +45,29 @@ func init() {
|
|||||||
}
|
}
|
||||||
valueTypes = make([]ValueType, 256)
|
valueTypes = make([]ValueType, 256)
|
||||||
for i := 0; i < len(valueTypes); i++ {
|
for i := 0; i < len(valueTypes); i++ {
|
||||||
valueTypes[i] = Invalid
|
valueTypes[i] = InvalidValue
|
||||||
}
|
}
|
||||||
valueTypes['"'] = String
|
valueTypes['"'] = StringValue
|
||||||
valueTypes['-'] = Number
|
valueTypes['-'] = NumberValue
|
||||||
valueTypes['0'] = Number
|
valueTypes['0'] = NumberValue
|
||||||
valueTypes['1'] = Number
|
valueTypes['1'] = NumberValue
|
||||||
valueTypes['2'] = Number
|
valueTypes['2'] = NumberValue
|
||||||
valueTypes['3'] = Number
|
valueTypes['3'] = NumberValue
|
||||||
valueTypes['4'] = Number
|
valueTypes['4'] = NumberValue
|
||||||
valueTypes['5'] = Number
|
valueTypes['5'] = NumberValue
|
||||||
valueTypes['6'] = Number
|
valueTypes['6'] = NumberValue
|
||||||
valueTypes['7'] = Number
|
valueTypes['7'] = NumberValue
|
||||||
valueTypes['8'] = Number
|
valueTypes['8'] = NumberValue
|
||||||
valueTypes['9'] = Number
|
valueTypes['9'] = NumberValue
|
||||||
valueTypes['t'] = Bool
|
valueTypes['t'] = BoolValue
|
||||||
valueTypes['f'] = Bool
|
valueTypes['f'] = BoolValue
|
||||||
valueTypes['n'] = Nil
|
valueTypes['n'] = NilValue
|
||||||
valueTypes['['] = Array
|
valueTypes['['] = ArrayValue
|
||||||
valueTypes['{'] = Object
|
valueTypes['{'] = ObjectValue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iterator is a fast and flexible JSON parser
|
// Iterator is a io.Reader like object, with JSON specific read functions.
|
||||||
|
// Error is not returned as return value, but stored as Error member on this iterator instance.
|
||||||
type Iterator struct {
|
type Iterator struct {
|
||||||
cfg *frozenConfig
|
cfg *frozenConfig
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
@ -75,10 +79,10 @@ type Iterator struct {
|
|||||||
Error error
|
Error error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create creates an empty Iterator instance
|
// NewIterator creates an empty Iterator instance
|
||||||
func NewIterator(cfg *frozenConfig) *Iterator {
|
func NewIterator(cfg API) *Iterator {
|
||||||
return &Iterator{
|
return &Iterator{
|
||||||
cfg: cfg,
|
cfg: cfg.(*frozenConfig),
|
||||||
reader: nil,
|
reader: nil,
|
||||||
buf: nil,
|
buf: nil,
|
||||||
head: 0,
|
head: 0,
|
||||||
@ -86,10 +90,10 @@ func NewIterator(cfg *frozenConfig) *Iterator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse parses a json buffer in io.Reader into an Iterator instance
|
// Parse creates an Iterator instance from io.Reader
|
||||||
func Parse(cfg *frozenConfig, reader io.Reader, bufSize int) *Iterator {
|
func Parse(cfg API, reader io.Reader, bufSize int) *Iterator {
|
||||||
return &Iterator{
|
return &Iterator{
|
||||||
cfg: cfg,
|
cfg: cfg.(*frozenConfig),
|
||||||
reader: reader,
|
reader: reader,
|
||||||
buf: make([]byte, bufSize),
|
buf: make([]byte, bufSize),
|
||||||
head: 0,
|
head: 0,
|
||||||
@ -97,10 +101,10 @@ func Parse(cfg *frozenConfig, reader io.Reader, bufSize int) *Iterator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseBytes parses a json byte slice into an Iterator instance
|
// ParseBytes creates an Iterator instance from byte array
|
||||||
func ParseBytes(cfg *frozenConfig, input []byte) *Iterator {
|
func ParseBytes(cfg API, input []byte) *Iterator {
|
||||||
return &Iterator{
|
return &Iterator{
|
||||||
cfg: cfg,
|
cfg: cfg.(*frozenConfig),
|
||||||
reader: nil,
|
reader: nil,
|
||||||
buf: input,
|
buf: input,
|
||||||
head: 0,
|
head: 0,
|
||||||
@ -108,16 +112,17 @@ func ParseBytes(cfg *frozenConfig, input []byte) *Iterator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseString parses a json string into an Iterator instance
|
// ParseString creates an Iterator instance from string
|
||||||
func ParseString(cfg *frozenConfig, input string) *Iterator {
|
func ParseString(cfg API, input string) *Iterator {
|
||||||
return ParseBytes(cfg, []byte(input))
|
return ParseBytes(cfg, []byte(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (iter *Iterator) Config() *frozenConfig {
|
// Pool returns a pool can provide more iterator with same configuration
|
||||||
|
func (iter *Iterator) Pool() IteratorPool {
|
||||||
return iter.cfg
|
return iter.cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset can reset an Iterator instance for another json buffer in io.Reader
|
// Reset reuse iterator instance by specifying another reader
|
||||||
func (iter *Iterator) Reset(reader io.Reader) *Iterator {
|
func (iter *Iterator) Reset(reader io.Reader) *Iterator {
|
||||||
iter.reader = reader
|
iter.reader = reader
|
||||||
iter.head = 0
|
iter.head = 0
|
||||||
@ -125,7 +130,7 @@ func (iter *Iterator) Reset(reader io.Reader) *Iterator {
|
|||||||
return iter
|
return iter
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResetBytes can reset an Iterator instance for another json byte slice
|
// ResetBytes reuse iterator instance by specifying another byte array as input
|
||||||
func (iter *Iterator) ResetBytes(input []byte) *Iterator {
|
func (iter *Iterator) ResetBytes(input []byte) *Iterator {
|
||||||
iter.reader = nil
|
iter.reader = nil
|
||||||
iter.buf = input
|
iter.buf = input
|
||||||
@ -134,7 +139,7 @@ func (iter *Iterator) ResetBytes(input []byte) *Iterator {
|
|||||||
return iter
|
return iter
|
||||||
}
|
}
|
||||||
|
|
||||||
// WhatIsNext gets ValueType of relatively next json object
|
// WhatIsNext gets ValueType of relatively next json element
|
||||||
func (iter *Iterator) WhatIsNext() ValueType {
|
func (iter *Iterator) WhatIsNext() ValueType {
|
||||||
valueType := valueTypes[iter.nextToken()]
|
valueType := valueTypes[iter.nextToken()]
|
||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
@ -154,6 +159,18 @@ func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) isObjectEnd() bool {
|
||||||
|
c := iter.nextToken()
|
||||||
|
if c == ',' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if c == '}' {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
iter.ReportError("isObjectEnd", "object ended prematurely")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (iter *Iterator) nextToken() byte {
|
func (iter *Iterator) nextToken() byte {
|
||||||
// a variation of skip whitespaces, returning the next non-whitespace token
|
// a variation of skip whitespaces, returning the next non-whitespace token
|
||||||
for {
|
for {
|
||||||
@ -172,6 +189,7 @@ func (iter *Iterator) nextToken() byte {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReportError record a error in iterator instance with current position.
|
||||||
func (iter *Iterator) ReportError(operation string, msg string) {
|
func (iter *Iterator) ReportError(operation string, msg string) {
|
||||||
if iter.Error != nil {
|
if iter.Error != nil {
|
||||||
if iter.Error != io.EOF {
|
if iter.Error != io.EOF {
|
||||||
@ -186,7 +204,7 @@ func (iter *Iterator) ReportError(operation string, msg string) {
|
|||||||
string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail]))
|
string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail]))
|
||||||
}
|
}
|
||||||
|
|
||||||
// CurrentBuffer gets current buffer as string
|
// CurrentBuffer gets current buffer as string for debugging purpose
|
||||||
func (iter *Iterator) CurrentBuffer() string {
|
func (iter *Iterator) CurrentBuffer() string {
|
||||||
peekStart := iter.head - 10
|
peekStart := iter.head - 10
|
||||||
if peekStart < 0 {
|
if peekStart < 0 {
|
||||||
@ -218,7 +236,7 @@ func (iter *Iterator) loadMore() bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if iter.captureStartedAt != -1 {
|
if iter.captured != nil {
|
||||||
iter.captured = append(iter.captured,
|
iter.captured = append(iter.captured,
|
||||||
iter.buf[iter.captureStartedAt:iter.tail]...)
|
iter.buf[iter.captureStartedAt:iter.tail]...)
|
||||||
iter.captureStartedAt = 0
|
iter.captureStartedAt = 0
|
||||||
@ -241,37 +259,44 @@ func (iter *Iterator) loadMore() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (iter *Iterator) unreadByte() {
|
func (iter *Iterator) unreadByte() {
|
||||||
if iter.head == 0 {
|
if iter.Error != nil {
|
||||||
iter.ReportError("unreadByte", "unread too many bytes")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
iter.head--
|
iter.head--
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read read the next JSON element as generic interface{}.
|
||||||
func (iter *Iterator) Read() interface{} {
|
func (iter *Iterator) Read() interface{} {
|
||||||
valueType := iter.WhatIsNext()
|
valueType := iter.WhatIsNext()
|
||||||
switch valueType {
|
switch valueType {
|
||||||
case String:
|
case StringValue:
|
||||||
return iter.ReadString()
|
return iter.ReadString()
|
||||||
case Number:
|
case NumberValue:
|
||||||
|
if iter.cfg.configBeforeFrozen.UseNumber {
|
||||||
|
return json.Number(iter.readNumberAsString())
|
||||||
|
}
|
||||||
return iter.ReadFloat64()
|
return iter.ReadFloat64()
|
||||||
case Nil:
|
case NilValue:
|
||||||
iter.skipFixedBytes(4) // null
|
iter.skipFourBytes('n', 'u', 'l', 'l')
|
||||||
return nil
|
return nil
|
||||||
case Bool:
|
case BoolValue:
|
||||||
return iter.ReadBool()
|
return iter.ReadBool()
|
||||||
case Array:
|
case ArrayValue:
|
||||||
arr := []interface{}{}
|
arr := []interface{}{}
|
||||||
iter.ReadArrayCB(func(iter *Iterator) bool {
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
arr = append(arr, iter.Read())
|
var elem interface{}
|
||||||
|
iter.ReadVal(&elem)
|
||||||
|
arr = append(arr, elem)
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return arr
|
return arr
|
||||||
case Object:
|
case ObjectValue:
|
||||||
obj := map[string]interface{}{}
|
obj := map[string]interface{}{}
|
||||||
iter.ReadObjectCB(func(Iter *Iterator, field string) bool {
|
iter.ReadMapCB(func(Iter *Iterator, field string) bool {
|
||||||
obj[field] = iter.Read()
|
var elem interface{}
|
||||||
|
iter.ReadVal(&elem)
|
||||||
|
obj[field] = elem
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return obj
|
return obj
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
|
// ReadArray read array element, tells if the array has more element to read.
|
||||||
func (iter *Iterator) ReadArray() (ret bool) {
|
func (iter *Iterator) ReadArray() (ret bool) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
switch c {
|
switch c {
|
||||||
case 'n':
|
case 'n':
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return false // null
|
return false // null
|
||||||
case '[':
|
case '[':
|
||||||
c = iter.nextToken()
|
c = iter.nextToken()
|
||||||
@ -23,6 +24,7 @@ func (iter *Iterator) ReadArray() (ret bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadArrayCB read array with callback
|
||||||
func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) {
|
func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '[' {
|
if c == '[' {
|
||||||
@ -32,17 +34,23 @@ func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) {
|
|||||||
if !callback(iter) {
|
if !callback(iter) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for iter.nextToken() == ',' {
|
c = iter.nextToken()
|
||||||
|
for c == ',' {
|
||||||
if !callback(iter) {
|
if !callback(iter) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
c = iter.nextToken()
|
||||||
|
}
|
||||||
|
if c != ']' {
|
||||||
|
iter.ReportError("ReadArrayCB", "expect ] in the end")
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if c == 'n' {
|
if c == 'n' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return true // null
|
return true // null
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadArrayCB", "expect [ or n, but found: "+string([]byte{c}))
|
iter.ReportError("ReadArrayCB", "expect [ or n, but found: "+string([]byte{c}))
|
||||||
|
@ -4,6 +4,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math/big"
|
"math/big"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -30,6 +31,7 @@ func init() {
|
|||||||
floatDigits['.'] = dotInNumber
|
floatDigits['.'] = dotInNumber
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadBigFloat read big.Float
|
||||||
func (iter *Iterator) ReadBigFloat() (ret *big.Float) {
|
func (iter *Iterator) ReadBigFloat() (ret *big.Float) {
|
||||||
str := iter.readNumberAsString()
|
str := iter.readNumberAsString()
|
||||||
if iter.Error != nil && iter.Error != io.EOF {
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
@ -47,6 +49,7 @@ func (iter *Iterator) ReadBigFloat() (ret *big.Float) {
|
|||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadBigInt read big.Int
|
||||||
func (iter *Iterator) ReadBigInt() (ret *big.Int) {
|
func (iter *Iterator) ReadBigInt() (ret *big.Int) {
|
||||||
str := iter.readNumberAsString()
|
str := iter.readNumberAsString()
|
||||||
if iter.Error != nil && iter.Error != io.EOF {
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
@ -62,20 +65,49 @@ func (iter *Iterator) ReadBigInt() (ret *big.Int) {
|
|||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//ReadFloat32 read float32
|
||||||
func (iter *Iterator) ReadFloat32() (ret float32) {
|
func (iter *Iterator) ReadFloat32() (ret float32) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
return -iter.readPositiveFloat32()
|
return -iter.readPositiveFloat32()
|
||||||
} else {
|
|
||||||
iter.unreadByte()
|
|
||||||
return iter.readPositiveFloat32()
|
|
||||||
}
|
}
|
||||||
|
iter.unreadByte()
|
||||||
|
return iter.readPositiveFloat32()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (iter *Iterator) readPositiveFloat32() (ret float32) {
|
func (iter *Iterator) readPositiveFloat32() (ret float32) {
|
||||||
value := uint64(0)
|
value := uint64(0)
|
||||||
c := byte(' ')
|
c := byte(' ')
|
||||||
i := iter.head
|
i := iter.head
|
||||||
|
// first char
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat32SlowPath()
|
||||||
|
}
|
||||||
|
c = iter.buf[i]
|
||||||
|
i++
|
||||||
|
ind := floatDigits[c]
|
||||||
|
switch ind {
|
||||||
|
case invalidCharForNumber:
|
||||||
|
return iter.readFloat32SlowPath()
|
||||||
|
case endOfNumber:
|
||||||
|
iter.ReportError("readFloat32", "empty number")
|
||||||
|
return
|
||||||
|
case dotInNumber:
|
||||||
|
iter.ReportError("readFloat32", "leading dot is invalid")
|
||||||
|
return
|
||||||
|
case 0:
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat32SlowPath()
|
||||||
|
}
|
||||||
|
c = iter.buf[i]
|
||||||
|
switch c {
|
||||||
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
iter.ReportError("readFloat32", "leading zero is invalid")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
value = uint64(ind)
|
||||||
|
// chars before dot
|
||||||
non_decimal_loop:
|
non_decimal_loop:
|
||||||
for ; i < iter.tail; i++ {
|
for ; i < iter.tail; i++ {
|
||||||
c = iter.buf[i]
|
c = iter.buf[i]
|
||||||
@ -94,17 +126,21 @@ non_decimal_loop:
|
|||||||
}
|
}
|
||||||
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
|
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
|
||||||
}
|
}
|
||||||
|
// chars after dot
|
||||||
if c == '.' {
|
if c == '.' {
|
||||||
i++
|
i++
|
||||||
decimalPlaces := 0
|
decimalPlaces := 0
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat32SlowPath()
|
||||||
|
}
|
||||||
for ; i < iter.tail; i++ {
|
for ; i < iter.tail; i++ {
|
||||||
c = iter.buf[i]
|
c = iter.buf[i]
|
||||||
ind := floatDigits[c]
|
ind := floatDigits[c]
|
||||||
switch ind {
|
switch ind {
|
||||||
case endOfNumber:
|
case endOfNumber:
|
||||||
if decimalPlaces > 0 && decimalPlaces < len(_POW10) {
|
if decimalPlaces > 0 && decimalPlaces < len(pow10) {
|
||||||
iter.head = i
|
iter.head = i
|
||||||
return float32(float64(value) / float64(_POW10[decimalPlaces]))
|
return float32(float64(value) / float64(pow10[decimalPlaces]))
|
||||||
}
|
}
|
||||||
// too many decimal places
|
// too many decimal places
|
||||||
return iter.readFloat32SlowPath()
|
return iter.readFloat32SlowPath()
|
||||||
@ -131,7 +167,7 @@ load_loop:
|
|||||||
for i := iter.head; i < iter.tail; i++ {
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
c := iter.buf[i]
|
c := iter.buf[i]
|
||||||
switch c {
|
switch c {
|
||||||
case '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
str = append(str, c)
|
str = append(str, c)
|
||||||
continue
|
continue
|
||||||
default:
|
default:
|
||||||
@ -157,6 +193,11 @@ func (iter *Iterator) readFloat32SlowPath() (ret float32) {
|
|||||||
if iter.Error != nil && iter.Error != io.EOF {
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
errMsg := validateFloat(str)
|
||||||
|
if errMsg != "" {
|
||||||
|
iter.ReportError("readFloat32SlowPath", errMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
val, err := strconv.ParseFloat(str, 32)
|
val, err := strconv.ParseFloat(str, 32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
iter.Error = err
|
iter.Error = err
|
||||||
@ -165,20 +206,49 @@ func (iter *Iterator) readFloat32SlowPath() (ret float32) {
|
|||||||
return float32(val)
|
return float32(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadFloat64 read float64
|
||||||
func (iter *Iterator) ReadFloat64() (ret float64) {
|
func (iter *Iterator) ReadFloat64() (ret float64) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
return -iter.readPositiveFloat64()
|
return -iter.readPositiveFloat64()
|
||||||
} else {
|
|
||||||
iter.unreadByte()
|
|
||||||
return iter.readPositiveFloat64()
|
|
||||||
}
|
}
|
||||||
|
iter.unreadByte()
|
||||||
|
return iter.readPositiveFloat64()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (iter *Iterator) readPositiveFloat64() (ret float64) {
|
func (iter *Iterator) readPositiveFloat64() (ret float64) {
|
||||||
value := uint64(0)
|
value := uint64(0)
|
||||||
c := byte(' ')
|
c := byte(' ')
|
||||||
i := iter.head
|
i := iter.head
|
||||||
|
// first char
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat64SlowPath()
|
||||||
|
}
|
||||||
|
c = iter.buf[i]
|
||||||
|
i++
|
||||||
|
ind := floatDigits[c]
|
||||||
|
switch ind {
|
||||||
|
case invalidCharForNumber:
|
||||||
|
return iter.readFloat64SlowPath()
|
||||||
|
case endOfNumber:
|
||||||
|
iter.ReportError("readFloat64", "empty number")
|
||||||
|
return
|
||||||
|
case dotInNumber:
|
||||||
|
iter.ReportError("readFloat64", "leading dot is invalid")
|
||||||
|
return
|
||||||
|
case 0:
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat64SlowPath()
|
||||||
|
}
|
||||||
|
c = iter.buf[i]
|
||||||
|
switch c {
|
||||||
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
iter.ReportError("readFloat64", "leading zero is invalid")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
value = uint64(ind)
|
||||||
|
// chars before dot
|
||||||
non_decimal_loop:
|
non_decimal_loop:
|
||||||
for ; i < iter.tail; i++ {
|
for ; i < iter.tail; i++ {
|
||||||
c = iter.buf[i]
|
c = iter.buf[i]
|
||||||
@ -197,17 +267,21 @@ non_decimal_loop:
|
|||||||
}
|
}
|
||||||
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
|
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
|
||||||
}
|
}
|
||||||
|
// chars after dot
|
||||||
if c == '.' {
|
if c == '.' {
|
||||||
i++
|
i++
|
||||||
decimalPlaces := 0
|
decimalPlaces := 0
|
||||||
|
if i == iter.tail {
|
||||||
|
return iter.readFloat64SlowPath()
|
||||||
|
}
|
||||||
for ; i < iter.tail; i++ {
|
for ; i < iter.tail; i++ {
|
||||||
c = iter.buf[i]
|
c = iter.buf[i]
|
||||||
ind := floatDigits[c]
|
ind := floatDigits[c]
|
||||||
switch ind {
|
switch ind {
|
||||||
case endOfNumber:
|
case endOfNumber:
|
||||||
if decimalPlaces > 0 && decimalPlaces < len(_POW10) {
|
if decimalPlaces > 0 && decimalPlaces < len(pow10) {
|
||||||
iter.head = i
|
iter.head = i
|
||||||
return float64(value) / float64(_POW10[decimalPlaces])
|
return float64(value) / float64(pow10[decimalPlaces])
|
||||||
}
|
}
|
||||||
// too many decimal places
|
// too many decimal places
|
||||||
return iter.readFloat64SlowPath()
|
return iter.readFloat64SlowPath()
|
||||||
@ -231,6 +305,11 @@ func (iter *Iterator) readFloat64SlowPath() (ret float64) {
|
|||||||
if iter.Error != nil && iter.Error != io.EOF {
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
errMsg := validateFloat(str)
|
||||||
|
if errMsg != "" {
|
||||||
|
iter.ReportError("readFloat64SlowPath", errMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
val, err := strconv.ParseFloat(str, 64)
|
val, err := strconv.ParseFloat(str, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
iter.Error = err
|
iter.Error = err
|
||||||
@ -238,3 +317,25 @@ func (iter *Iterator) readFloat64SlowPath() (ret float64) {
|
|||||||
}
|
}
|
||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateFloat(str string) string {
|
||||||
|
// strconv.ParseFloat is not validating `1.` or `1.e1`
|
||||||
|
if len(str) == 0 {
|
||||||
|
return "empty number"
|
||||||
|
}
|
||||||
|
if str[0] == '-' {
|
||||||
|
return "-- is not valid"
|
||||||
|
}
|
||||||
|
dotPos := strings.IndexByte(str, '.')
|
||||||
|
if dotPos != -1 {
|
||||||
|
if dotPos == len(str)-1 {
|
||||||
|
return "dot can not be last character"
|
||||||
|
}
|
||||||
|
switch str[dotPos+1] {
|
||||||
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
default:
|
||||||
|
return "missing digit after dot"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
@ -20,14 +20,17 @@ func init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadUint read uint
|
||||||
func (iter *Iterator) ReadUint() uint {
|
func (iter *Iterator) ReadUint() uint {
|
||||||
return uint(iter.ReadUint64())
|
return uint(iter.ReadUint64())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadInt read int
|
||||||
func (iter *Iterator) ReadInt() int {
|
func (iter *Iterator) ReadInt() int {
|
||||||
return int(iter.ReadInt64())
|
return int(iter.ReadInt64())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadInt8 read int8
|
||||||
func (iter *Iterator) ReadInt8() (ret int8) {
|
func (iter *Iterator) ReadInt8() (ret int8) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
@ -37,16 +40,16 @@ func (iter *Iterator) ReadInt8() (ret int8) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
return -int8(val)
|
return -int8(val)
|
||||||
} else {
|
|
||||||
val := iter.readUint32(c)
|
|
||||||
if val > math.MaxInt8 {
|
|
||||||
iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return int8(val)
|
|
||||||
}
|
}
|
||||||
|
val := iter.readUint32(c)
|
||||||
|
if val > math.MaxInt8 {
|
||||||
|
iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return int8(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadUint8 read uint8
|
||||||
func (iter *Iterator) ReadUint8() (ret uint8) {
|
func (iter *Iterator) ReadUint8() (ret uint8) {
|
||||||
val := iter.readUint32(iter.nextToken())
|
val := iter.readUint32(iter.nextToken())
|
||||||
if val > math.MaxUint8 {
|
if val > math.MaxUint8 {
|
||||||
@ -56,6 +59,7 @@ func (iter *Iterator) ReadUint8() (ret uint8) {
|
|||||||
return uint8(val)
|
return uint8(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadInt16 read int16
|
||||||
func (iter *Iterator) ReadInt16() (ret int16) {
|
func (iter *Iterator) ReadInt16() (ret int16) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
@ -65,16 +69,16 @@ func (iter *Iterator) ReadInt16() (ret int16) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
return -int16(val)
|
return -int16(val)
|
||||||
} else {
|
|
||||||
val := iter.readUint32(c)
|
|
||||||
if val > math.MaxInt16 {
|
|
||||||
iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return int16(val)
|
|
||||||
}
|
}
|
||||||
|
val := iter.readUint32(c)
|
||||||
|
if val > math.MaxInt16 {
|
||||||
|
iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return int16(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadUint16 read uint16
|
||||||
func (iter *Iterator) ReadUint16() (ret uint16) {
|
func (iter *Iterator) ReadUint16() (ret uint16) {
|
||||||
val := iter.readUint32(iter.nextToken())
|
val := iter.readUint32(iter.nextToken())
|
||||||
if val > math.MaxUint16 {
|
if val > math.MaxUint16 {
|
||||||
@ -84,6 +88,7 @@ func (iter *Iterator) ReadUint16() (ret uint16) {
|
|||||||
return uint16(val)
|
return uint16(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadInt32 read int32
|
||||||
func (iter *Iterator) ReadInt32() (ret int32) {
|
func (iter *Iterator) ReadInt32() (ret int32) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
@ -93,16 +98,16 @@ func (iter *Iterator) ReadInt32() (ret int32) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
return -int32(val)
|
return -int32(val)
|
||||||
} else {
|
|
||||||
val := iter.readUint32(c)
|
|
||||||
if val > math.MaxInt32 {
|
|
||||||
iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return int32(val)
|
|
||||||
}
|
}
|
||||||
|
val := iter.readUint32(c)
|
||||||
|
if val > math.MaxInt32 {
|
||||||
|
iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return int32(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadUint32 read uint32
|
||||||
func (iter *Iterator) ReadUint32() (ret uint32) {
|
func (iter *Iterator) ReadUint32() (ret uint32) {
|
||||||
return iter.readUint32(iter.nextToken())
|
return iter.readUint32(iter.nextToken())
|
||||||
}
|
}
|
||||||
@ -182,10 +187,9 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) {
|
|||||||
if value2 < value {
|
if value2 < value {
|
||||||
iter.ReportError("readUint32", "overflow")
|
iter.ReportError("readUint32", "overflow")
|
||||||
return
|
return
|
||||||
} else {
|
|
||||||
value = value2
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
value = value2
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
value = (value << 3) + (value << 1) + uint32(ind)
|
value = (value << 3) + (value << 1) + uint32(ind)
|
||||||
}
|
}
|
||||||
@ -195,6 +199,7 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadInt64 read int64
|
||||||
func (iter *Iterator) ReadInt64() (ret int64) {
|
func (iter *Iterator) ReadInt64() (ret int64) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '-' {
|
if c == '-' {
|
||||||
@ -204,16 +209,16 @@ func (iter *Iterator) ReadInt64() (ret int64) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
return -int64(val)
|
return -int64(val)
|
||||||
} else {
|
|
||||||
val := iter.readUint64(c)
|
|
||||||
if val > math.MaxInt64 {
|
|
||||||
iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return int64(val)
|
|
||||||
}
|
}
|
||||||
|
val := iter.readUint64(c)
|
||||||
|
if val > math.MaxInt64 {
|
||||||
|
iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return int64(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadUint64 read uint64
|
||||||
func (iter *Iterator) ReadUint64() uint64 {
|
func (iter *Iterator) ReadUint64() uint64 {
|
||||||
return iter.readUint64(iter.nextToken())
|
return iter.readUint64(iter.nextToken())
|
||||||
}
|
}
|
||||||
@ -240,10 +245,9 @@ func (iter *Iterator) readUint64(c byte) (ret uint64) {
|
|||||||
if value2 < value {
|
if value2 < value {
|
||||||
iter.ReportError("readUint64", "overflow")
|
iter.ReportError("readUint64", "overflow")
|
||||||
return
|
return
|
||||||
} else {
|
|
||||||
value = value2
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
value = value2
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
value = (value << 3) + (value << 1) + uint64(ind)
|
value = (value << 3) + (value << 1) + uint64(ind)
|
||||||
}
|
}
|
||||||
|
@ -6,11 +6,14 @@ import (
|
|||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ReadObject read one field from object.
|
||||||
|
// If object ended, returns empty string.
|
||||||
|
// Otherwise, returns the field name.
|
||||||
func (iter *Iterator) ReadObject() (ret string) {
|
func (iter *Iterator) ReadObject() (ret string) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
switch c {
|
switch c {
|
||||||
case 'n':
|
case 'n':
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return "" // null
|
return "" // null
|
||||||
case '{':
|
case '{':
|
||||||
c = iter.nextToken()
|
c = iter.nextToken()
|
||||||
@ -74,6 +77,7 @@ func calcHash(str string) int32 {
|
|||||||
return int32(hash)
|
return int32(hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadObjectCB read object with callback, the key is ascii only and field name not copied
|
||||||
func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool {
|
func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '{' {
|
if c == '{' {
|
||||||
@ -84,11 +88,17 @@ func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool {
|
|||||||
if !callback(iter, *(*string)(unsafe.Pointer(&field))) {
|
if !callback(iter, *(*string)(unsafe.Pointer(&field))) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for iter.nextToken() == ',' {
|
c = iter.nextToken()
|
||||||
|
for c == ',' {
|
||||||
field = iter.readObjectFieldAsBytes()
|
field = iter.readObjectFieldAsBytes()
|
||||||
if !callback(iter, *(*string)(unsafe.Pointer(&field))) {
|
if !callback(iter, *(*string)(unsafe.Pointer(&field))) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
c = iter.nextToken()
|
||||||
|
}
|
||||||
|
if c != '}' {
|
||||||
|
iter.ReportError("ReadObjectCB", `object not ended with }`)
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -99,13 +109,14 @@ func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if c == 'n' {
|
if c == 'n' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return true // null
|
return true // null
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadObjectCB", `expect { or n`)
|
iter.ReportError("ReadObjectCB", `expect { or n`)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadMapCB read map with callback, the key can be any string
|
||||||
func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
|
func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '{' {
|
if c == '{' {
|
||||||
@ -120,7 +131,8 @@ func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
|
|||||||
if !callback(iter, field) {
|
if !callback(iter, field) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for iter.nextToken() == ',' {
|
c = iter.nextToken()
|
||||||
|
for c == ',' {
|
||||||
field = iter.ReadString()
|
field = iter.ReadString()
|
||||||
if iter.nextToken() != ':' {
|
if iter.nextToken() != ':' {
|
||||||
iter.ReportError("ReadMapCB", "expect : after object field")
|
iter.ReportError("ReadMapCB", "expect : after object field")
|
||||||
@ -129,6 +141,11 @@ func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
|
|||||||
if !callback(iter, field) {
|
if !callback(iter, field) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
c = iter.nextToken()
|
||||||
|
}
|
||||||
|
if c != '}' {
|
||||||
|
iter.ReportError("ReadMapCB", `object not ended with }`)
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -139,7 +156,7 @@ func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if c == 'n' {
|
if c == 'n' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return true // null
|
return true // null
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadMapCB", `expect { or n`)
|
iter.ReportError("ReadMapCB", `expect { or n`)
|
||||||
@ -156,7 +173,7 @@ func (iter *Iterator) readObjectStart() bool {
|
|||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
return true
|
return true
|
||||||
} else if c == 'n' {
|
} else if c == 'n' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
iter.ReportError("readObjectStart", "expect { or n")
|
iter.ReportError("readObjectStart", "expect { or n")
|
||||||
|
@ -7,28 +7,30 @@ import "fmt"
|
|||||||
func (iter *Iterator) ReadNil() (ret bool) {
|
func (iter *Iterator) ReadNil() (ret bool) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == 'n' {
|
if c == 'n' {
|
||||||
iter.skipFixedBytes(3) // null
|
iter.skipThreeBytes('u', 'l', 'l') // null
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadBool reads a json object as Bool
|
// ReadBool reads a json object as BoolValue
|
||||||
func (iter *Iterator) ReadBool() (ret bool) {
|
func (iter *Iterator) ReadBool() (ret bool) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == 't' {
|
if c == 't' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('r', 'u', 'e')
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if c == 'f' {
|
if c == 'f' {
|
||||||
iter.skipFixedBytes(4)
|
iter.skipFourBytes('a', 'l', 's', 'e')
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadBool", "expect t or f")
|
iter.ReportError("ReadBool", "expect t or f")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SkipAndReturnBytes skip next JSON element, and return its content as []byte.
|
||||||
|
// The []byte can be kept, it is a copy of data.
|
||||||
func (iter *Iterator) SkipAndReturnBytes() []byte {
|
func (iter *Iterator) SkipAndReturnBytes() []byte {
|
||||||
iter.startCapture(iter.head)
|
iter.startCapture(iter.head)
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
@ -58,10 +60,9 @@ func (iter *Iterator) stopCapture() []byte {
|
|||||||
iter.captured = nil
|
iter.captured = nil
|
||||||
if len(captured) == 0 {
|
if len(captured) == 0 {
|
||||||
return remaining
|
return remaining
|
||||||
} else {
|
|
||||||
captured = append(captured, remaining...)
|
|
||||||
return captured
|
|
||||||
}
|
}
|
||||||
|
captured = append(captured, remaining...)
|
||||||
|
return captured
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip skips a json object and positions to relatively the next json object
|
// Skip skips a json object and positions to relatively the next json object
|
||||||
@ -70,11 +71,16 @@ func (iter *Iterator) Skip() {
|
|||||||
switch c {
|
switch c {
|
||||||
case '"':
|
case '"':
|
||||||
iter.skipString()
|
iter.skipString()
|
||||||
case 'n', 't':
|
case 'n':
|
||||||
iter.skipFixedBytes(3) // null or true
|
iter.skipThreeBytes('u', 'l', 'l') // null
|
||||||
|
case 't':
|
||||||
|
iter.skipThreeBytes('r', 'u', 'e') // true
|
||||||
case 'f':
|
case 'f':
|
||||||
iter.skipFixedBytes(4) // false
|
iter.skipFourBytes('a', 'l', 's', 'e') // false
|
||||||
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
case '0':
|
||||||
|
iter.unreadByte()
|
||||||
|
iter.ReadFloat32()
|
||||||
|
case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
iter.skipNumber()
|
iter.skipNumber()
|
||||||
case '[':
|
case '[':
|
||||||
iter.skipArray()
|
iter.skipArray()
|
||||||
@ -86,155 +92,36 @@ func (iter *Iterator) Skip() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (iter *Iterator) skipString() {
|
func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) {
|
||||||
for {
|
if iter.readByte() != b1 {
|
||||||
end, escaped := iter.findStringEnd()
|
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
|
||||||
if end == -1 {
|
return
|
||||||
if !iter.loadMore() {
|
}
|
||||||
iter.ReportError("skipString", "incomplete string")
|
if iter.readByte() != b2 {
|
||||||
return
|
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
|
||||||
}
|
return
|
||||||
if escaped {
|
}
|
||||||
iter.head = 1 // skip the first char as last char read is \
|
if iter.readByte() != b3 {
|
||||||
}
|
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
|
||||||
} else {
|
return
|
||||||
iter.head = end
|
}
|
||||||
return
|
if iter.readByte() != b4 {
|
||||||
}
|
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go
|
func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) {
|
||||||
// Tries to find the end of string
|
if iter.readByte() != b1 {
|
||||||
// Support if string contains escaped quote symbols.
|
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
|
||||||
func (iter *Iterator) findStringEnd() (int, bool) {
|
return
|
||||||
escaped := false
|
|
||||||
for i := iter.head; i < iter.tail; i++ {
|
|
||||||
c := iter.buf[i]
|
|
||||||
if c == '"' {
|
|
||||||
if !escaped {
|
|
||||||
return i + 1, false
|
|
||||||
}
|
|
||||||
j := i - 1
|
|
||||||
for {
|
|
||||||
if j < iter.head || iter.buf[j] != '\\' {
|
|
||||||
// even number of backslashes
|
|
||||||
// either end of buffer, or " found
|
|
||||||
return i + 1, true
|
|
||||||
}
|
|
||||||
j--
|
|
||||||
if j < iter.head || iter.buf[j] != '\\' {
|
|
||||||
// odd number of backslashes
|
|
||||||
// it is \" or \\\"
|
|
||||||
break
|
|
||||||
}
|
|
||||||
j--
|
|
||||||
}
|
|
||||||
} else if c == '\\' {
|
|
||||||
escaped = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
j := iter.tail - 1
|
if iter.readByte() != b2 {
|
||||||
for {
|
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
|
||||||
if j < iter.head || iter.buf[j] != '\\' {
|
return
|
||||||
// even number of backslashes
|
|
||||||
// either end of buffer, or " found
|
|
||||||
return -1, false // do not end with \
|
|
||||||
}
|
|
||||||
j--
|
|
||||||
if j < iter.head || iter.buf[j] != '\\' {
|
|
||||||
// odd number of backslashes
|
|
||||||
// it is \" or \\\"
|
|
||||||
break
|
|
||||||
}
|
|
||||||
j--
|
|
||||||
|
|
||||||
}
|
}
|
||||||
return -1, true // end with \
|
if iter.readByte() != b3 {
|
||||||
}
|
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
|
||||||
|
return
|
||||||
func (iter *Iterator) skipArray() {
|
|
||||||
level := 1
|
|
||||||
for {
|
|
||||||
for i := iter.head; i < iter.tail; i++ {
|
|
||||||
switch iter.buf[i] {
|
|
||||||
case '"': // If inside string, skip it
|
|
||||||
iter.head = i + 1
|
|
||||||
iter.skipString()
|
|
||||||
i = iter.head - 1 // it will be i++ soon
|
|
||||||
case '[': // If open symbol, increase level
|
|
||||||
level++
|
|
||||||
case ']': // If close symbol, increase level
|
|
||||||
level--
|
|
||||||
|
|
||||||
// If we have returned to the original level, we're done
|
|
||||||
if level == 0 {
|
|
||||||
iter.head = i + 1
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !iter.loadMore() {
|
|
||||||
iter.ReportError("skipObject", "incomplete array")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iter *Iterator) skipObject() {
|
|
||||||
level := 1
|
|
||||||
for {
|
|
||||||
for i := iter.head; i < iter.tail; i++ {
|
|
||||||
switch iter.buf[i] {
|
|
||||||
case '"': // If inside string, skip it
|
|
||||||
iter.head = i + 1
|
|
||||||
iter.skipString()
|
|
||||||
i = iter.head - 1 // it will be i++ soon
|
|
||||||
case '{': // If open symbol, increase level
|
|
||||||
level++
|
|
||||||
case '}': // If close symbol, increase level
|
|
||||||
level--
|
|
||||||
|
|
||||||
// If we have returned to the original level, we're done
|
|
||||||
if level == 0 {
|
|
||||||
iter.head = i + 1
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !iter.loadMore() {
|
|
||||||
iter.ReportError("skipObject", "incomplete object")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iter *Iterator) skipNumber() {
|
|
||||||
for {
|
|
||||||
for i := iter.head; i < iter.tail; i++ {
|
|
||||||
c := iter.buf[i]
|
|
||||||
switch c {
|
|
||||||
case ' ', '\n', '\r', '\t', ',', '}', ']':
|
|
||||||
iter.head = i
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !iter.loadMore() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iter *Iterator) skipFixedBytes(n int) {
|
|
||||||
iter.head += n
|
|
||||||
if iter.head >= iter.tail {
|
|
||||||
more := iter.head - iter.tail
|
|
||||||
if !iter.loadMore() {
|
|
||||||
if more > 0 {
|
|
||||||
iter.ReportError("skipFixedBytes", "unexpected end")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
iter.head += more
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
144
feature_iter_skip_sloppy.go
Normal file
144
feature_iter_skip_sloppy.go
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
//+build jsoniter-sloppy
|
||||||
|
|
||||||
|
package jsoniter
|
||||||
|
|
||||||
|
// sloppy but faster implementation, do not validate the input json
|
||||||
|
|
||||||
|
func (iter *Iterator) skipNumber() {
|
||||||
|
for {
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
c := iter.buf[i]
|
||||||
|
switch c {
|
||||||
|
case ' ', '\n', '\r', '\t', ',', '}', ']':
|
||||||
|
iter.head = i
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !iter.loadMore() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipArray() {
|
||||||
|
level := 1
|
||||||
|
for {
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
switch iter.buf[i] {
|
||||||
|
case '"': // If inside string, skip it
|
||||||
|
iter.head = i + 1
|
||||||
|
iter.skipString()
|
||||||
|
i = iter.head - 1 // it will be i++ soon
|
||||||
|
case '[': // If open symbol, increase level
|
||||||
|
level++
|
||||||
|
case ']': // If close symbol, increase level
|
||||||
|
level--
|
||||||
|
|
||||||
|
// If we have returned to the original level, we're done
|
||||||
|
if level == 0 {
|
||||||
|
iter.head = i + 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !iter.loadMore() {
|
||||||
|
iter.ReportError("skipObject", "incomplete array")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipObject() {
|
||||||
|
level := 1
|
||||||
|
for {
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
switch iter.buf[i] {
|
||||||
|
case '"': // If inside string, skip it
|
||||||
|
iter.head = i + 1
|
||||||
|
iter.skipString()
|
||||||
|
i = iter.head - 1 // it will be i++ soon
|
||||||
|
case '{': // If open symbol, increase level
|
||||||
|
level++
|
||||||
|
case '}': // If close symbol, increase level
|
||||||
|
level--
|
||||||
|
|
||||||
|
// If we have returned to the original level, we're done
|
||||||
|
if level == 0 {
|
||||||
|
iter.head = i + 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !iter.loadMore() {
|
||||||
|
iter.ReportError("skipObject", "incomplete object")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipString() {
|
||||||
|
for {
|
||||||
|
end, escaped := iter.findStringEnd()
|
||||||
|
if end == -1 {
|
||||||
|
if !iter.loadMore() {
|
||||||
|
iter.ReportError("skipString", "incomplete string")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if escaped {
|
||||||
|
iter.head = 1 // skip the first char as last char read is \
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
iter.head = end
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go
|
||||||
|
// Tries to find the end of string
|
||||||
|
// Support if string contains escaped quote symbols.
|
||||||
|
func (iter *Iterator) findStringEnd() (int, bool) {
|
||||||
|
escaped := false
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
c := iter.buf[i]
|
||||||
|
if c == '"' {
|
||||||
|
if !escaped {
|
||||||
|
return i + 1, false
|
||||||
|
}
|
||||||
|
j := i - 1
|
||||||
|
for {
|
||||||
|
if j < iter.head || iter.buf[j] != '\\' {
|
||||||
|
// even number of backslashes
|
||||||
|
// either end of buffer, or " found
|
||||||
|
return i + 1, true
|
||||||
|
}
|
||||||
|
j--
|
||||||
|
if j < iter.head || iter.buf[j] != '\\' {
|
||||||
|
// odd number of backslashes
|
||||||
|
// it is \" or \\\"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
} else if c == '\\' {
|
||||||
|
escaped = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
j := iter.tail - 1
|
||||||
|
for {
|
||||||
|
if j < iter.head || iter.buf[j] != '\\' {
|
||||||
|
// even number of backslashes
|
||||||
|
// either end of buffer, or " found
|
||||||
|
return -1, false // do not end with \
|
||||||
|
}
|
||||||
|
j--
|
||||||
|
if j < iter.head || iter.buf[j] != '\\' {
|
||||||
|
// odd number of backslashes
|
||||||
|
// it is \" or \\\"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
j--
|
||||||
|
|
||||||
|
}
|
||||||
|
return -1, true // end with \
|
||||||
|
}
|
89
feature_iter_skip_strict.go
Normal file
89
feature_iter_skip_strict.go
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
//+build !jsoniter-sloppy
|
||||||
|
|
||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func (iter *Iterator) skipNumber() {
|
||||||
|
if !iter.trySkipNumber() {
|
||||||
|
iter.unreadByte()
|
||||||
|
iter.ReadFloat32()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) trySkipNumber() bool {
|
||||||
|
dotFound := false
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
c := iter.buf[i]
|
||||||
|
switch c {
|
||||||
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
case '.':
|
||||||
|
if dotFound {
|
||||||
|
iter.ReportError("validateNumber", `more than one dot found in number`)
|
||||||
|
return true // already failed
|
||||||
|
}
|
||||||
|
if i+1 == iter.tail {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
c = iter.buf[i+1]
|
||||||
|
switch c {
|
||||||
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
default:
|
||||||
|
iter.ReportError("validateNumber", `missing digit after dot`)
|
||||||
|
return true // already failed
|
||||||
|
}
|
||||||
|
dotFound = true
|
||||||
|
default:
|
||||||
|
switch c {
|
||||||
|
case ',', ']', '}', ' ', '\t', '\n', '\r':
|
||||||
|
if iter.head == i {
|
||||||
|
return false // if - without following digits
|
||||||
|
}
|
||||||
|
iter.head = i
|
||||||
|
return true // must be valid
|
||||||
|
}
|
||||||
|
return false // may be invalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipString() {
|
||||||
|
if !iter.trySkipString() {
|
||||||
|
iter.unreadByte()
|
||||||
|
iter.ReadString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) trySkipString() bool {
|
||||||
|
for i := iter.head; i < iter.tail; i++ {
|
||||||
|
c := iter.buf[i]
|
||||||
|
if c == '"' {
|
||||||
|
iter.head = i + 1
|
||||||
|
return true // valid
|
||||||
|
} else if c == '\\' {
|
||||||
|
return false
|
||||||
|
} else if c < ' ' {
|
||||||
|
iter.ReportError("trySkipString",
|
||||||
|
fmt.Sprintf(`invalid control character found: %d`, c))
|
||||||
|
return true // already failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipObject() {
|
||||||
|
iter.unreadByte()
|
||||||
|
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
||||||
|
iter.Skip()
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) skipArray() {
|
||||||
|
iter.unreadByte()
|
||||||
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
|
iter.Skip()
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
@ -1,9 +1,11 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"unicode/utf16"
|
"unicode/utf16"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ReadString read string from iterator
|
||||||
func (iter *Iterator) ReadString() (ret string) {
|
func (iter *Iterator) ReadString() (ret string) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '"' {
|
if c == '"' {
|
||||||
@ -15,11 +17,15 @@ func (iter *Iterator) ReadString() (ret string) {
|
|||||||
return ret
|
return ret
|
||||||
} else if c == '\\' {
|
} else if c == '\\' {
|
||||||
break
|
break
|
||||||
|
} else if c < ' ' {
|
||||||
|
iter.ReportError("ReadString",
|
||||||
|
fmt.Sprintf(`invalid control character found: %d`, c))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return iter.readStringSlowPath()
|
return iter.readStringSlowPath()
|
||||||
} else if c == 'n' {
|
} else if c == 'n' {
|
||||||
iter.skipFixedBytes(3)
|
iter.skipThreeBytes('u', 'l', 'l')
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadString", `expects " or n`)
|
iter.ReportError("ReadString", `expects " or n`)
|
||||||
@ -36,66 +42,77 @@ func (iter *Iterator) readStringSlowPath() (ret string) {
|
|||||||
}
|
}
|
||||||
if c == '\\' {
|
if c == '\\' {
|
||||||
c = iter.readByte()
|
c = iter.readByte()
|
||||||
switch c {
|
str = iter.readEscapedChar(c, str)
|
||||||
case 'u', 'U':
|
|
||||||
r := iter.readU4()
|
|
||||||
if utf16.IsSurrogate(r) {
|
|
||||||
c = iter.readByte()
|
|
||||||
if iter.Error != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if c != '\\' {
|
|
||||||
iter.ReportError("ReadString",
|
|
||||||
`expects \u after utf16 surrogate, but \ not found`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c = iter.readByte()
|
|
||||||
if iter.Error != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if c != 'u' && c != 'U' {
|
|
||||||
iter.ReportError("ReadString",
|
|
||||||
`expects \u after utf16 surrogate, but \u not found`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
r2 := iter.readU4()
|
|
||||||
if iter.Error != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
combined := utf16.DecodeRune(r, r2)
|
|
||||||
str = appendRune(str, combined)
|
|
||||||
} else {
|
|
||||||
str = appendRune(str, r)
|
|
||||||
}
|
|
||||||
case '"':
|
|
||||||
str = append(str, '"')
|
|
||||||
case '\\':
|
|
||||||
str = append(str, '\\')
|
|
||||||
case '/':
|
|
||||||
str = append(str, '/')
|
|
||||||
case 'b':
|
|
||||||
str = append(str, '\b')
|
|
||||||
case 'f':
|
|
||||||
str = append(str, '\f')
|
|
||||||
case 'n':
|
|
||||||
str = append(str, '\n')
|
|
||||||
case 'r':
|
|
||||||
str = append(str, '\r')
|
|
||||||
case 't':
|
|
||||||
str = append(str, '\t')
|
|
||||||
default:
|
|
||||||
iter.ReportError("ReadString",
|
|
||||||
`invalid escape char after \`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
str = append(str, c)
|
str = append(str, c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadString", "unexpected end of input")
|
iter.ReportError("readStringSlowPath", "unexpected end of input")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte {
|
||||||
|
switch c {
|
||||||
|
case 'u':
|
||||||
|
r := iter.readU4()
|
||||||
|
if utf16.IsSurrogate(r) {
|
||||||
|
c = iter.readByte()
|
||||||
|
if iter.Error != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if c != '\\' {
|
||||||
|
iter.unreadByte()
|
||||||
|
str = appendRune(str, r)
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
c = iter.readByte()
|
||||||
|
if iter.Error != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if c != 'u' {
|
||||||
|
str = appendRune(str, r)
|
||||||
|
return iter.readEscapedChar(c, str)
|
||||||
|
}
|
||||||
|
r2 := iter.readU4()
|
||||||
|
if iter.Error != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
combined := utf16.DecodeRune(r, r2)
|
||||||
|
if combined == '\uFFFD' {
|
||||||
|
str = appendRune(str, r)
|
||||||
|
str = appendRune(str, r2)
|
||||||
|
} else {
|
||||||
|
str = appendRune(str, combined)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
str = appendRune(str, r)
|
||||||
|
}
|
||||||
|
case '"':
|
||||||
|
str = append(str, '"')
|
||||||
|
case '\\':
|
||||||
|
str = append(str, '\\')
|
||||||
|
case '/':
|
||||||
|
str = append(str, '/')
|
||||||
|
case 'b':
|
||||||
|
str = append(str, '\b')
|
||||||
|
case 'f':
|
||||||
|
str = append(str, '\f')
|
||||||
|
case 'n':
|
||||||
|
str = append(str, '\n')
|
||||||
|
case 'r':
|
||||||
|
str = append(str, '\r')
|
||||||
|
case 't':
|
||||||
|
str = append(str, '\t')
|
||||||
|
default:
|
||||||
|
iter.ReportError("readEscapedChar",
|
||||||
|
`invalid escape char after \`)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadStringAsSlice read string from iterator without copying into string form.
|
||||||
|
// The []byte can not be kept, as it will change after next iterator call.
|
||||||
func (iter *Iterator) ReadStringAsSlice() (ret []byte) {
|
func (iter *Iterator) ReadStringAsSlice() (ret []byte) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c == '"' {
|
if c == '"' {
|
||||||
@ -122,7 +139,7 @@ func (iter *Iterator) ReadStringAsSlice() (ret []byte) {
|
|||||||
}
|
}
|
||||||
return copied
|
return copied
|
||||||
}
|
}
|
||||||
iter.ReportError("ReadString", `expects " or n`)
|
iter.ReportError("ReadStringAsSlice", `expects " or n`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
15
feature_json_number.go
Normal file
15
feature_json_number.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
type Number string
|
||||||
|
|
||||||
|
func CastJsonNumber(val interface{}) (string, bool) {
|
||||||
|
switch typedVal := val.(type) {
|
||||||
|
case json.Number:
|
||||||
|
return string(typedVal), true
|
||||||
|
case Number:
|
||||||
|
return string(typedVal), true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
@ -4,6 +4,18 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// IteratorPool a thread safe pool of iterators with same configuration
|
||||||
|
type IteratorPool interface {
|
||||||
|
BorrowIterator(data []byte) *Iterator
|
||||||
|
ReturnIterator(iter *Iterator)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamPool a thread safe pool of streams with same configuration
|
||||||
|
type StreamPool interface {
|
||||||
|
BorrowStream(writer io.Writer) *Stream
|
||||||
|
ReturnStream(stream *Stream)
|
||||||
|
}
|
||||||
|
|
||||||
func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream {
|
func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream {
|
||||||
select {
|
select {
|
||||||
case stream := <-cfg.streamPool:
|
case stream := <-cfg.streamPool:
|
||||||
|
@ -32,6 +32,11 @@ type ValEncoder interface {
|
|||||||
EncodeInterface(val interface{}, stream *Stream)
|
EncodeInterface(val interface{}, stream *Stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type checkIsEmpty interface {
|
||||||
|
IsEmpty(ptr unsafe.Pointer) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteToStream the default implementation for TypeEncoder method EncodeInterface
|
||||||
func WriteToStream(val interface{}, stream *Stream, encoder ValEncoder) {
|
func WriteToStream(val interface{}, stream *Stream, encoder ValEncoder) {
|
||||||
e := (*emptyInterface)(unsafe.Pointer(&val))
|
e := (*emptyInterface)(unsafe.Pointer(&val))
|
||||||
if e.word == nil {
|
if e.word == nil {
|
||||||
@ -45,24 +50,25 @@ func WriteToStream(val interface{}, stream *Stream, encoder ValEncoder) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator)
|
|
||||||
type EncoderFunc func(ptr unsafe.Pointer, stream *Stream)
|
|
||||||
|
|
||||||
var jsonNumberType reflect.Type
|
var jsonNumberType reflect.Type
|
||||||
|
var jsoniterNumberType reflect.Type
|
||||||
var jsonRawMessageType reflect.Type
|
var jsonRawMessageType reflect.Type
|
||||||
var jsoniterRawMessageType reflect.Type
|
var jsoniterRawMessageType reflect.Type
|
||||||
var anyType reflect.Type
|
var anyType reflect.Type
|
||||||
var marshalerType reflect.Type
|
var marshalerType reflect.Type
|
||||||
var unmarshalerType reflect.Type
|
var unmarshalerType reflect.Type
|
||||||
|
var textMarshalerType reflect.Type
|
||||||
var textUnmarshalerType reflect.Type
|
var textUnmarshalerType reflect.Type
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
jsonNumberType = reflect.TypeOf((*json.Number)(nil)).Elem()
|
jsonNumberType = reflect.TypeOf((*json.Number)(nil)).Elem()
|
||||||
|
jsoniterNumberType = reflect.TypeOf((*Number)(nil)).Elem()
|
||||||
jsonRawMessageType = reflect.TypeOf((*json.RawMessage)(nil)).Elem()
|
jsonRawMessageType = reflect.TypeOf((*json.RawMessage)(nil)).Elem()
|
||||||
jsoniterRawMessageType = reflect.TypeOf((*RawMessage)(nil)).Elem()
|
jsoniterRawMessageType = reflect.TypeOf((*RawMessage)(nil)).Elem()
|
||||||
anyType = reflect.TypeOf((*Any)(nil)).Elem()
|
anyType = reflect.TypeOf((*Any)(nil)).Elem()
|
||||||
marshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
|
marshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
|
||||||
unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
|
unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
|
||||||
|
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
|
||||||
textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
|
textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,17 +82,37 @@ func (decoder *optionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
*((*unsafe.Pointer)(ptr)) = nil
|
*((*unsafe.Pointer)(ptr)) = nil
|
||||||
} else {
|
} else {
|
||||||
if *((*unsafe.Pointer)(ptr)) == nil {
|
if *((*unsafe.Pointer)(ptr)) == nil {
|
||||||
// pointer to null, we have to allocate memory to hold the value
|
//pointer to null, we have to allocate memory to hold the value
|
||||||
value := reflect.New(decoder.valueType)
|
value := reflect.New(decoder.valueType)
|
||||||
decoder.valueDecoder.Decode(unsafe.Pointer(value.Pointer()), iter)
|
newPtr := extractInterface(value.Interface()).word
|
||||||
*((*uintptr)(ptr)) = value.Pointer()
|
decoder.valueDecoder.Decode(newPtr, iter)
|
||||||
|
*((*uintptr)(ptr)) = uintptr(newPtr)
|
||||||
} else {
|
} else {
|
||||||
// reuse existing instance
|
//reuse existing instance
|
||||||
decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter)
|
decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type deferenceDecoder struct {
|
||||||
|
// only to deference a pointer
|
||||||
|
valueType reflect.Type
|
||||||
|
valueDecoder ValDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *deferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if *((*unsafe.Pointer)(ptr)) == nil {
|
||||||
|
//pointer to null, we have to allocate memory to hold the value
|
||||||
|
value := reflect.New(decoder.valueType)
|
||||||
|
newPtr := extractInterface(value.Interface()).word
|
||||||
|
decoder.valueDecoder.Decode(newPtr, iter)
|
||||||
|
*((*uintptr)(ptr)) = uintptr(newPtr)
|
||||||
|
} else {
|
||||||
|
//reuse existing instance
|
||||||
|
decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type optionalEncoder struct {
|
type optionalEncoder struct {
|
||||||
valueEncoder ValEncoder
|
valueEncoder ValEncoder
|
||||||
}
|
}
|
||||||
@ -106,9 +132,8 @@ func (encoder *optionalEncoder) EncodeInterface(val interface{}, stream *Stream)
|
|||||||
func (encoder *optionalEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
func (encoder *optionalEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
if *((*unsafe.Pointer)(ptr)) == nil {
|
if *((*unsafe.Pointer)(ptr)) == nil {
|
||||||
return true
|
return true
|
||||||
} else {
|
|
||||||
return encoder.valueEncoder.IsEmpty(*((*unsafe.Pointer)(ptr)))
|
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
type placeholderEncoder struct {
|
type placeholderEncoder struct {
|
||||||
@ -129,11 +154,11 @@ func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *placeholderEncoder) getRealEncoder() ValEncoder {
|
func (encoder *placeholderEncoder) getRealEncoder() ValEncoder {
|
||||||
for i := 0; i < 30; i++ {
|
for i := 0; i < 500; i++ {
|
||||||
realDecoder := encoder.cfg.getEncoderFromCache(encoder.cacheKey)
|
realDecoder := encoder.cfg.getEncoderFromCache(encoder.cacheKey)
|
||||||
_, isPlaceholder := realDecoder.(*placeholderEncoder)
|
_, isPlaceholder := realDecoder.(*placeholderEncoder)
|
||||||
if isPlaceholder {
|
if isPlaceholder {
|
||||||
time.Sleep(time.Second)
|
time.Sleep(10 * time.Millisecond)
|
||||||
} else {
|
} else {
|
||||||
return realDecoder
|
return realDecoder
|
||||||
}
|
}
|
||||||
@ -147,11 +172,11 @@ type placeholderDecoder struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
for i := 0; i < 30; i++ {
|
for i := 0; i < 500; i++ {
|
||||||
realDecoder := decoder.cfg.getDecoderFromCache(decoder.cacheKey)
|
realDecoder := decoder.cfg.getDecoderFromCache(decoder.cacheKey)
|
||||||
_, isPlaceholder := realDecoder.(*placeholderDecoder)
|
_, isPlaceholder := realDecoder.(*placeholderDecoder)
|
||||||
if isPlaceholder {
|
if isPlaceholder {
|
||||||
time.Sleep(time.Second)
|
time.Sleep(10 * time.Millisecond)
|
||||||
} else {
|
} else {
|
||||||
realDecoder.Decode(ptr, iter)
|
realDecoder.Decode(ptr, iter)
|
||||||
return
|
return
|
||||||
@ -180,7 +205,7 @@ type nonEmptyInterface struct {
|
|||||||
word unsafe.Pointer
|
word unsafe.Pointer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read converts an Iterator instance into go interface, same as json.Unmarshal
|
// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal
|
||||||
func (iter *Iterator) ReadVal(obj interface{}) {
|
func (iter *Iterator) ReadVal(obj interface{}) {
|
||||||
typ := reflect.TypeOf(obj)
|
typ := reflect.TypeOf(obj)
|
||||||
cacheKey := typ.Elem()
|
cacheKey := typ.Elem()
|
||||||
@ -193,6 +218,7 @@ func (iter *Iterator) ReadVal(obj interface{}) {
|
|||||||
decoder.Decode(e.word, iter)
|
decoder.Decode(e.word, iter)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteVal copy the go interface into underlying JSON, same as json.Marshal
|
||||||
func (stream *Stream) WriteVal(val interface{}) {
|
func (stream *Stream) WriteVal(val interface{}) {
|
||||||
if nil == val {
|
if nil == val {
|
||||||
stream.WriteNil()
|
stream.WriteNil()
|
||||||
@ -246,66 +272,138 @@ func decoderOfType(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func createDecoderOfType(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) {
|
func createDecoderOfType(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) {
|
||||||
if typ.String() == "[]uint8" {
|
typeName := typ.String()
|
||||||
return &base64Codec{}, nil
|
if typ == jsonRawMessageType {
|
||||||
}
|
|
||||||
if typ.AssignableTo(jsonRawMessageType) {
|
|
||||||
return &jsonRawMessageCodec{}, nil
|
return &jsonRawMessageCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.AssignableTo(jsoniterRawMessageType) {
|
if typ == jsoniterRawMessageType {
|
||||||
return &jsoniterRawMessageCodec{}, nil
|
return &jsoniterRawMessageCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.AssignableTo(jsonNumberType) {
|
if typ.AssignableTo(jsonNumberType) {
|
||||||
return &jsonNumberCodec{}, nil
|
return &jsonNumberCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.ConvertibleTo(unmarshalerType) {
|
if typ.AssignableTo(jsoniterNumberType) {
|
||||||
|
return &jsoniterNumberCodec{}, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(unmarshalerType) {
|
||||||
templateInterface := reflect.New(typ).Elem().Interface()
|
templateInterface := reflect.New(typ).Elem().Interface()
|
||||||
var decoder ValDecoder = &unmarshalerDecoder{extractInterface(templateInterface)}
|
var decoder ValDecoder = &unmarshalerDecoder{extractInterface(templateInterface)}
|
||||||
if typ.Kind() != reflect.Struct {
|
if typ.Kind() == reflect.Ptr {
|
||||||
decoder = &optionalDecoder{typ, decoder}
|
decoder = &optionalDecoder{typ.Elem(), decoder}
|
||||||
}
|
}
|
||||||
return decoder, nil
|
return decoder, nil
|
||||||
}
|
}
|
||||||
if typ.ConvertibleTo(anyType) {
|
if reflect.PtrTo(typ).Implements(unmarshalerType) {
|
||||||
|
templateInterface := reflect.New(typ).Interface()
|
||||||
|
var decoder ValDecoder = &unmarshalerDecoder{extractInterface(templateInterface)}
|
||||||
|
return decoder, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(textUnmarshalerType) {
|
||||||
|
templateInterface := reflect.New(typ).Elem().Interface()
|
||||||
|
var decoder ValDecoder = &textUnmarshalerDecoder{extractInterface(templateInterface)}
|
||||||
|
if typ.Kind() == reflect.Ptr {
|
||||||
|
decoder = &optionalDecoder{typ.Elem(), decoder}
|
||||||
|
}
|
||||||
|
return decoder, nil
|
||||||
|
}
|
||||||
|
if reflect.PtrTo(typ).Implements(textUnmarshalerType) {
|
||||||
|
templateInterface := reflect.New(typ).Interface()
|
||||||
|
var decoder ValDecoder = &textUnmarshalerDecoder{extractInterface(templateInterface)}
|
||||||
|
return decoder, nil
|
||||||
|
}
|
||||||
|
if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 {
|
||||||
|
sliceDecoder, err := prefix("[slice]").addToDecoder(decoderOfSlice(cfg, typ))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &base64Codec{sliceDecoder: sliceDecoder}, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(anyType) {
|
||||||
return &anyCodec{}, nil
|
return &anyCodec{}, nil
|
||||||
}
|
}
|
||||||
switch typ.Kind() {
|
switch typ.Kind() {
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
|
if typeName != "string" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*string)(nil)).Elem())
|
||||||
|
}
|
||||||
return &stringCodec{}, nil
|
return &stringCodec{}, nil
|
||||||
case reflect.Int:
|
case reflect.Int:
|
||||||
|
if typeName != "int" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*int)(nil)).Elem())
|
||||||
|
}
|
||||||
return &intCodec{}, nil
|
return &intCodec{}, nil
|
||||||
case reflect.Int8:
|
case reflect.Int8:
|
||||||
|
if typeName != "int8" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*int8)(nil)).Elem())
|
||||||
|
}
|
||||||
return &int8Codec{}, nil
|
return &int8Codec{}, nil
|
||||||
case reflect.Int16:
|
case reflect.Int16:
|
||||||
|
if typeName != "int16" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*int16)(nil)).Elem())
|
||||||
|
}
|
||||||
return &int16Codec{}, nil
|
return &int16Codec{}, nil
|
||||||
case reflect.Int32:
|
case reflect.Int32:
|
||||||
|
if typeName != "int32" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*int32)(nil)).Elem())
|
||||||
|
}
|
||||||
return &int32Codec{}, nil
|
return &int32Codec{}, nil
|
||||||
case reflect.Int64:
|
case reflect.Int64:
|
||||||
|
if typeName != "int64" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*int64)(nil)).Elem())
|
||||||
|
}
|
||||||
return &int64Codec{}, nil
|
return &int64Codec{}, nil
|
||||||
case reflect.Uint:
|
case reflect.Uint:
|
||||||
|
if typeName != "uint" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uint)(nil)).Elem())
|
||||||
|
}
|
||||||
return &uintCodec{}, nil
|
return &uintCodec{}, nil
|
||||||
case reflect.Uint8:
|
case reflect.Uint8:
|
||||||
|
if typeName != "uint8" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uint8)(nil)).Elem())
|
||||||
|
}
|
||||||
return &uint8Codec{}, nil
|
return &uint8Codec{}, nil
|
||||||
case reflect.Uint16:
|
case reflect.Uint16:
|
||||||
|
if typeName != "uint16" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uint16)(nil)).Elem())
|
||||||
|
}
|
||||||
return &uint16Codec{}, nil
|
return &uint16Codec{}, nil
|
||||||
case reflect.Uint32:
|
case reflect.Uint32:
|
||||||
|
if typeName != "uint32" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uint32)(nil)).Elem())
|
||||||
|
}
|
||||||
return &uint32Codec{}, nil
|
return &uint32Codec{}, nil
|
||||||
|
case reflect.Uintptr:
|
||||||
|
if typeName != "uintptr" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uintptr)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uintptrCodec{}, nil
|
||||||
case reflect.Uint64:
|
case reflect.Uint64:
|
||||||
|
if typeName != "uint64" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*uint64)(nil)).Elem())
|
||||||
|
}
|
||||||
return &uint64Codec{}, nil
|
return &uint64Codec{}, nil
|
||||||
case reflect.Float32:
|
case reflect.Float32:
|
||||||
|
if typeName != "float32" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*float32)(nil)).Elem())
|
||||||
|
}
|
||||||
return &float32Codec{}, nil
|
return &float32Codec{}, nil
|
||||||
case reflect.Float64:
|
case reflect.Float64:
|
||||||
|
if typeName != "float64" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*float64)(nil)).Elem())
|
||||||
|
}
|
||||||
return &float64Codec{}, nil
|
return &float64Codec{}, nil
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
|
if typeName != "bool" {
|
||||||
|
return decoderOfType(cfg, reflect.TypeOf((*bool)(nil)).Elem())
|
||||||
|
}
|
||||||
return &boolCodec{}, nil
|
return &boolCodec{}, nil
|
||||||
case reflect.Interface:
|
case reflect.Interface:
|
||||||
if typ.NumMethod() == 0 {
|
if typ.NumMethod() == 0 {
|
||||||
return &emptyInterfaceCodec{}, nil
|
return &emptyInterfaceCodec{}, nil
|
||||||
} else {
|
|
||||||
return &nonEmptyInterfaceCodec{}, nil
|
|
||||||
}
|
}
|
||||||
|
return &nonEmptyInterfaceCodec{}, nil
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
return prefix(fmt.Sprintf("[%s]", typ.String())).addToDecoder(decoderOfStruct(cfg, typ))
|
return prefix(fmt.Sprintf("[%s]", typeName)).addToDecoder(decoderOfStruct(cfg, typ))
|
||||||
case reflect.Array:
|
case reflect.Array:
|
||||||
return prefix("[array]").addToDecoder(decoderOfArray(cfg, typ))
|
return prefix("[array]").addToDecoder(decoderOfArray(cfg, typ))
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
@ -341,29 +439,70 @@ func encoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) {
|
func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) {
|
||||||
if typ.String() == "[]uint8" {
|
if typ == jsonRawMessageType {
|
||||||
return &base64Codec{}, nil
|
|
||||||
}
|
|
||||||
if typ.AssignableTo(jsonRawMessageType) {
|
|
||||||
return &jsonRawMessageCodec{}, nil
|
return &jsonRawMessageCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.AssignableTo(jsoniterRawMessageType) {
|
if typ == jsoniterRawMessageType {
|
||||||
return &jsoniterRawMessageCodec{}, nil
|
return &jsoniterRawMessageCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.AssignableTo(jsonNumberType) {
|
if typ.AssignableTo(jsonNumberType) {
|
||||||
return &jsonNumberCodec{}, nil
|
return &jsonNumberCodec{}, nil
|
||||||
}
|
}
|
||||||
if typ.ConvertibleTo(marshalerType) {
|
if typ.AssignableTo(jsoniterNumberType) {
|
||||||
|
return &jsoniterNumberCodec{}, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(marshalerType) {
|
||||||
|
checkIsEmpty, err := createCheckIsEmpty(typ)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
templateInterface := reflect.New(typ).Elem().Interface()
|
templateInterface := reflect.New(typ).Elem().Interface()
|
||||||
var encoder ValEncoder = &marshalerEncoder{extractInterface(templateInterface)}
|
var encoder ValEncoder = &marshalerEncoder{
|
||||||
if typ.Kind() != reflect.Struct {
|
templateInterface: extractInterface(templateInterface),
|
||||||
|
checkIsEmpty: checkIsEmpty,
|
||||||
|
}
|
||||||
|
if typ.Kind() == reflect.Ptr {
|
||||||
encoder = &optionalEncoder{encoder}
|
encoder = &optionalEncoder{encoder}
|
||||||
}
|
}
|
||||||
return encoder, nil
|
return encoder, nil
|
||||||
}
|
}
|
||||||
if typ.ConvertibleTo(anyType) {
|
if reflect.PtrTo(typ).Implements(marshalerType) {
|
||||||
|
checkIsEmpty, err := createCheckIsEmpty(reflect.PtrTo(typ))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
templateInterface := reflect.New(typ).Interface()
|
||||||
|
var encoder ValEncoder = &marshalerEncoder{
|
||||||
|
templateInterface: extractInterface(templateInterface),
|
||||||
|
checkIsEmpty: checkIsEmpty,
|
||||||
|
}
|
||||||
|
return encoder, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(textMarshalerType) {
|
||||||
|
checkIsEmpty, err := createCheckIsEmpty(typ)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
templateInterface := reflect.New(typ).Elem().Interface()
|
||||||
|
var encoder ValEncoder = &textMarshalerEncoder{
|
||||||
|
templateInterface: extractInterface(templateInterface),
|
||||||
|
checkIsEmpty: checkIsEmpty,
|
||||||
|
}
|
||||||
|
if typ.Kind() == reflect.Ptr {
|
||||||
|
encoder = &optionalEncoder{encoder}
|
||||||
|
}
|
||||||
|
return encoder, nil
|
||||||
|
}
|
||||||
|
if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 {
|
||||||
|
return &base64Codec{}, nil
|
||||||
|
}
|
||||||
|
if typ.Implements(anyType) {
|
||||||
return &anyCodec{}, nil
|
return &anyCodec{}, nil
|
||||||
}
|
}
|
||||||
|
return createEncoderOfSimpleType(cfg, typ)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createCheckIsEmpty(typ reflect.Type) (checkIsEmpty, error) {
|
||||||
kind := typ.Kind()
|
kind := typ.Kind()
|
||||||
switch kind {
|
switch kind {
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
@ -386,6 +525,8 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
|
|||||||
return &uint16Codec{}, nil
|
return &uint16Codec{}, nil
|
||||||
case reflect.Uint32:
|
case reflect.Uint32:
|
||||||
return &uint32Codec{}, nil
|
return &uint32Codec{}, nil
|
||||||
|
case reflect.Uintptr:
|
||||||
|
return &uintptrCodec{}, nil
|
||||||
case reflect.Uint64:
|
case reflect.Uint64:
|
||||||
return &uint64Codec{}, nil
|
return &uint64Codec{}, nil
|
||||||
case reflect.Float32:
|
case reflect.Float32:
|
||||||
@ -397,11 +538,109 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
|
|||||||
case reflect.Interface:
|
case reflect.Interface:
|
||||||
if typ.NumMethod() == 0 {
|
if typ.NumMethod() == 0 {
|
||||||
return &emptyInterfaceCodec{}, nil
|
return &emptyInterfaceCodec{}, nil
|
||||||
} else {
|
|
||||||
return &nonEmptyInterfaceCodec{}, nil
|
|
||||||
}
|
}
|
||||||
|
return &nonEmptyInterfaceCodec{}, nil
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
return prefix(fmt.Sprintf("[%s]", typ.String())).addToEncoder(encoderOfStruct(cfg, typ))
|
return &structEncoder{}, nil
|
||||||
|
case reflect.Array:
|
||||||
|
return &arrayEncoder{}, nil
|
||||||
|
case reflect.Slice:
|
||||||
|
return &sliceEncoder{}, nil
|
||||||
|
case reflect.Map:
|
||||||
|
return &mapEncoder{}, nil
|
||||||
|
case reflect.Ptr:
|
||||||
|
return &optionalEncoder{}, nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported type: %v", typ)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createEncoderOfSimpleType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) {
|
||||||
|
typeName := typ.String()
|
||||||
|
kind := typ.Kind()
|
||||||
|
switch kind {
|
||||||
|
case reflect.String:
|
||||||
|
if typeName != "string" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*string)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &stringCodec{}, nil
|
||||||
|
case reflect.Int:
|
||||||
|
if typeName != "int" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*int)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &intCodec{}, nil
|
||||||
|
case reflect.Int8:
|
||||||
|
if typeName != "int8" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*int8)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &int8Codec{}, nil
|
||||||
|
case reflect.Int16:
|
||||||
|
if typeName != "int16" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*int16)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &int16Codec{}, nil
|
||||||
|
case reflect.Int32:
|
||||||
|
if typeName != "int32" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*int32)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &int32Codec{}, nil
|
||||||
|
case reflect.Int64:
|
||||||
|
if typeName != "int64" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*int64)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &int64Codec{}, nil
|
||||||
|
case reflect.Uint:
|
||||||
|
if typeName != "uint" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uint)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uintCodec{}, nil
|
||||||
|
case reflect.Uint8:
|
||||||
|
if typeName != "uint8" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uint8)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uint8Codec{}, nil
|
||||||
|
case reflect.Uint16:
|
||||||
|
if typeName != "uint16" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uint16)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uint16Codec{}, nil
|
||||||
|
case reflect.Uint32:
|
||||||
|
if typeName != "uint32" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uint32)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uint32Codec{}, nil
|
||||||
|
case reflect.Uintptr:
|
||||||
|
if typeName != "uintptr" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uintptr)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uintptrCodec{}, nil
|
||||||
|
case reflect.Uint64:
|
||||||
|
if typeName != "uint64" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*uint64)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &uint64Codec{}, nil
|
||||||
|
case reflect.Float32:
|
||||||
|
if typeName != "float32" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*float32)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &float32Codec{}, nil
|
||||||
|
case reflect.Float64:
|
||||||
|
if typeName != "float64" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*float64)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &float64Codec{}, nil
|
||||||
|
case reflect.Bool:
|
||||||
|
if typeName != "bool" {
|
||||||
|
return encoderOfType(cfg, reflect.TypeOf((*bool)(nil)).Elem())
|
||||||
|
}
|
||||||
|
return &boolCodec{}, nil
|
||||||
|
case reflect.Interface:
|
||||||
|
if typ.NumMethod() == 0 {
|
||||||
|
return &emptyInterfaceCodec{}, nil
|
||||||
|
}
|
||||||
|
return &nonEmptyInterfaceCodec{}, nil
|
||||||
|
case reflect.Struct:
|
||||||
|
return prefix(fmt.Sprintf("[%s]", typeName)).addToEncoder(encoderOfStruct(cfg, typ))
|
||||||
case reflect.Array:
|
case reflect.Array:
|
||||||
return prefix("[array]").addToEncoder(encoderOfArray(cfg, typ))
|
return prefix("[array]").addToEncoder(encoderOfArray(cfg, typ))
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
@ -459,7 +698,6 @@ func encoderOfMap(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) {
|
|||||||
mapInterface := reflect.New(typ).Elem().Interface()
|
mapInterface := reflect.New(typ).Elem().Interface()
|
||||||
if cfg.sortMapKeys {
|
if cfg.sortMapKeys {
|
||||||
return &sortKeysMapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil
|
return &sortKeysMapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil
|
||||||
} else {
|
|
||||||
return &mapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil
|
|
||||||
}
|
}
|
||||||
|
return &mapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil
|
||||||
}
|
}
|
||||||
|
@ -33,16 +33,12 @@ type arrayEncoder struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
if ptr == nil {
|
|
||||||
stream.WriteNil()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
stream.WriteArrayStart()
|
stream.WriteArrayStart()
|
||||||
elemPtr := uintptr(ptr)
|
elemPtr := unsafe.Pointer(ptr)
|
||||||
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
encoder.elemEncoder.Encode(elemPtr, stream)
|
||||||
for i := 1; i < encoder.arrayType.Len(); i++ {
|
for i := 1; i < encoder.arrayType.Len(); i++ {
|
||||||
stream.WriteMore()
|
stream.WriteMore()
|
||||||
elemPtr += encoder.elemType.Size()
|
elemPtr = unsafe.Pointer(uintptr(elemPtr) + encoder.elemType.Size())
|
||||||
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
||||||
}
|
}
|
||||||
stream.WriteArrayEnd()
|
stream.WriteArrayEnd()
|
||||||
@ -52,7 +48,24 @@ func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *arrayEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
func (encoder *arrayEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
// special optimization for interface{}
|
||||||
|
e := (*emptyInterface)(unsafe.Pointer(&val))
|
||||||
|
if e.word == nil {
|
||||||
|
stream.WriteArrayStart()
|
||||||
|
stream.WriteNil()
|
||||||
|
stream.WriteArrayEnd()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
elemType := encoder.arrayType.Elem()
|
||||||
|
if encoder.arrayType.Len() == 1 && (elemType.Kind() == reflect.Ptr || elemType.Kind() == reflect.Map) {
|
||||||
|
ptr := uintptr(e.word)
|
||||||
|
e.word = unsafe.Pointer(&ptr)
|
||||||
|
}
|
||||||
|
if reflect.TypeOf(val).Kind() == reflect.Ptr {
|
||||||
|
encoder.Encode(unsafe.Pointer(&e.word), stream)
|
||||||
|
} else {
|
||||||
|
encoder.Encode(e.word, stream)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -74,11 +87,13 @@ func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
|
|
||||||
func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) {
|
func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
offset := uintptr(0)
|
offset := uintptr(0)
|
||||||
for ; iter.ReadArray(); offset += decoder.elemType.Size() {
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
if offset < decoder.arrayType.Size() {
|
if offset < decoder.arrayType.Size() {
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(ptr)+offset), iter)
|
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(ptr)+offset), iter)
|
||||||
|
offset += decoder.elemType.Size()
|
||||||
} else {
|
} else {
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
}
|
}
|
||||||
}
|
return true
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
@ -14,11 +15,16 @@ var typeEncoders = map[string]ValEncoder{}
|
|||||||
var fieldEncoders = map[string]ValEncoder{}
|
var fieldEncoders = map[string]ValEncoder{}
|
||||||
var extensions = []Extension{}
|
var extensions = []Extension{}
|
||||||
|
|
||||||
|
// StructDescriptor describe how should we encode/decode the struct
|
||||||
type StructDescriptor struct {
|
type StructDescriptor struct {
|
||||||
Type reflect.Type
|
onePtrEmbedded bool
|
||||||
Fields []*Binding
|
onePtrOptimization bool
|
||||||
|
Type reflect.Type
|
||||||
|
Fields []*Binding
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetField get one field from the descriptor by its name.
|
||||||
|
// Can not use map here to keep field orders.
|
||||||
func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding {
|
func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding {
|
||||||
for _, binding := range structDescriptor.Fields {
|
for _, binding := range structDescriptor.Fields {
|
||||||
if binding.Field.Name == fieldName {
|
if binding.Field.Name == fieldName {
|
||||||
@ -28,7 +34,9 @@ func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Binding describe how should we encode/decode the struct field
|
||||||
type Binding struct {
|
type Binding struct {
|
||||||
|
levels []int
|
||||||
Field *reflect.StructField
|
Field *reflect.StructField
|
||||||
FromNames []string
|
FromNames []string
|
||||||
ToNames []string
|
ToNames []string
|
||||||
@ -36,6 +44,8 @@ type Binding struct {
|
|||||||
Decoder ValDecoder
|
Decoder ValDecoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder.
|
||||||
|
// Can also rename fields by UpdateStructDescriptor.
|
||||||
type Extension interface {
|
type Extension interface {
|
||||||
UpdateStructDescriptor(structDescriptor *StructDescriptor)
|
UpdateStructDescriptor(structDescriptor *StructDescriptor)
|
||||||
CreateDecoder(typ reflect.Type) ValDecoder
|
CreateDecoder(typ reflect.Type) ValDecoder
|
||||||
@ -44,24 +54,30 @@ type Extension interface {
|
|||||||
DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder
|
DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DummyExtension embed this type get dummy implementation for all methods of Extension
|
||||||
type DummyExtension struct {
|
type DummyExtension struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateStructDescriptor No-op
|
||||||
func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
|
func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateDecoder No-op
|
||||||
func (extension *DummyExtension) CreateDecoder(typ reflect.Type) ValDecoder {
|
func (extension *DummyExtension) CreateDecoder(typ reflect.Type) ValDecoder {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateEncoder No-op
|
||||||
func (extension *DummyExtension) CreateEncoder(typ reflect.Type) ValEncoder {
|
func (extension *DummyExtension) CreateEncoder(typ reflect.Type) ValEncoder {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecorateDecoder No-op
|
||||||
func (extension *DummyExtension) DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder {
|
func (extension *DummyExtension) DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder {
|
||||||
return decoder
|
return decoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecorateEncoder No-op
|
||||||
func (extension *DummyExtension) DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder {
|
func (extension *DummyExtension) DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder {
|
||||||
return encoder
|
return encoder
|
||||||
}
|
}
|
||||||
@ -94,38 +110,53 @@ func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
|||||||
return encoder.isEmptyFunc(ptr)
|
return encoder.isEmptyFunc(ptr)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecoderFunc the function form of TypeDecoder
|
||||||
|
type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator)
|
||||||
|
|
||||||
|
// EncoderFunc the function form of TypeEncoder
|
||||||
|
type EncoderFunc func(ptr unsafe.Pointer, stream *Stream)
|
||||||
|
|
||||||
|
// RegisterTypeDecoderFunc register TypeDecoder for a type with function
|
||||||
func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) {
|
func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) {
|
||||||
typeDecoders[typ] = &funcDecoder{fun}
|
typeDecoders[typ] = &funcDecoder{fun}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterTypeDecoder register TypeDecoder for a typ
|
||||||
func RegisterTypeDecoder(typ string, decoder ValDecoder) {
|
func RegisterTypeDecoder(typ string, decoder ValDecoder) {
|
||||||
typeDecoders[typ] = decoder
|
typeDecoders[typ] = decoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function
|
||||||
func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) {
|
func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) {
|
||||||
RegisterFieldDecoder(typ, field, &funcDecoder{fun})
|
RegisterFieldDecoder(typ, field, &funcDecoder{fun})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterFieldDecoder register TypeDecoder for a struct field
|
||||||
func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) {
|
func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) {
|
||||||
fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder
|
fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function
|
||||||
func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
|
func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
|
||||||
typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc}
|
typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterTypeEncoder register TypeEncoder for a type
|
||||||
func RegisterTypeEncoder(typ string, encoder ValEncoder) {
|
func RegisterTypeEncoder(typ string, encoder ValEncoder) {
|
||||||
typeEncoders[typ] = encoder
|
typeEncoders[typ] = encoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function
|
||||||
func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
|
func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
|
||||||
RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc})
|
RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterFieldEncoder register TypeEncoder for a struct field
|
||||||
func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
|
func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
|
||||||
fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder
|
fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterExtension register extension
|
||||||
func RegisterExtension(extension Extension) {
|
func RegisterExtension(extension Extension) {
|
||||||
extensions = append(extensions, extension)
|
extensions = append(extensions, extension)
|
||||||
}
|
}
|
||||||
@ -192,108 +223,191 @@ func _getTypeEncoderFromExtension(typ reflect.Type) ValEncoder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, error) {
|
func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, error) {
|
||||||
anonymousBindings := []*Binding{}
|
embeddedBindings := []*Binding{}
|
||||||
bindings := []*Binding{}
|
bindings := []*Binding{}
|
||||||
for i := 0; i < typ.NumField(); i++ {
|
for i := 0; i < typ.NumField(); i++ {
|
||||||
field := typ.Field(i)
|
field := typ.Field(i)
|
||||||
if field.Anonymous {
|
tag := field.Tag.Get(cfg.getTagKey())
|
||||||
|
tagParts := strings.Split(tag, ",")
|
||||||
|
if tag == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if field.Anonymous && (tag == "" || tagParts[0] == "") {
|
||||||
if field.Type.Kind() == reflect.Struct {
|
if field.Type.Kind() == reflect.Struct {
|
||||||
structDescriptor, err := describeStruct(cfg, field.Type)
|
structDescriptor, err := describeStruct(cfg, field.Type)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, binding := range structDescriptor.Fields {
|
for _, binding := range structDescriptor.Fields {
|
||||||
anonymousBindings = append(anonymousBindings, binding)
|
binding.levels = append([]int{i}, binding.levels...)
|
||||||
|
omitempty := binding.Encoder.(*structFieldEncoder).omitempty
|
||||||
|
binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty}
|
||||||
|
binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
|
||||||
|
embeddedBindings = append(embeddedBindings, binding)
|
||||||
}
|
}
|
||||||
|
continue
|
||||||
} else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
|
} else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
|
||||||
structDescriptor, err := describeStruct(cfg, field.Type.Elem())
|
structDescriptor, err := describeStruct(cfg, field.Type.Elem())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, binding := range structDescriptor.Fields {
|
for _, binding := range structDescriptor.Fields {
|
||||||
|
binding.levels = append([]int{i}, binding.levels...)
|
||||||
|
omitempty := binding.Encoder.(*structFieldEncoder).omitempty
|
||||||
binding.Encoder = &optionalEncoder{binding.Encoder}
|
binding.Encoder = &optionalEncoder{binding.Encoder}
|
||||||
binding.Encoder = &structFieldEncoder{&field, binding.Encoder, false}
|
binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty}
|
||||||
binding.Decoder = &optionalDecoder{field.Type, binding.Decoder}
|
binding.Decoder = &deferenceDecoder{field.Type.Elem(), binding.Decoder}
|
||||||
binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
|
binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
|
||||||
anonymousBindings = append(anonymousBindings, binding)
|
embeddedBindings = append(embeddedBindings, binding)
|
||||||
}
|
}
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
tagParts := strings.Split(field.Tag.Get("json"), ",")
|
fieldNames := calcFieldNames(field.Name, tagParts[0], tag)
|
||||||
fieldNames := calcFieldNames(field.Name, tagParts[0])
|
fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name)
|
||||||
fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name)
|
decoder := fieldDecoders[fieldCacheKey]
|
||||||
decoder := fieldDecoders[fieldCacheKey]
|
if decoder == nil {
|
||||||
if decoder == nil {
|
var err error
|
||||||
var err error
|
decoder, err = decoderOfType(cfg, field.Type)
|
||||||
decoder, err = decoderOfType(cfg, field.Type)
|
if err != nil {
|
||||||
if err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
encoder := fieldEncoders[fieldCacheKey]
|
}
|
||||||
if encoder == nil {
|
encoder := fieldEncoders[fieldCacheKey]
|
||||||
var err error
|
if encoder == nil {
|
||||||
encoder, err = encoderOfType(cfg, field.Type)
|
var err error
|
||||||
if err != nil {
|
encoder, err = encoderOfType(cfg, field.Type)
|
||||||
return nil, err
|
if err != nil {
|
||||||
}
|
return nil, err
|
||||||
// map is stored as pointer in the struct
|
|
||||||
if field.Type.Kind() == reflect.Map {
|
|
||||||
encoder = &optionalEncoder{encoder}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
binding := &Binding{
|
// map is stored as pointer in the struct
|
||||||
Field: &field,
|
if field.Type.Kind() == reflect.Map {
|
||||||
FromNames: fieldNames,
|
encoder = &optionalEncoder{encoder}
|
||||||
ToNames: fieldNames,
|
|
||||||
Decoder: decoder,
|
|
||||||
Encoder: encoder,
|
|
||||||
}
|
}
|
||||||
bindings = append(bindings, binding)
|
}
|
||||||
|
binding := &Binding{
|
||||||
|
Field: &field,
|
||||||
|
FromNames: fieldNames,
|
||||||
|
ToNames: fieldNames,
|
||||||
|
Decoder: decoder,
|
||||||
|
Encoder: encoder,
|
||||||
|
}
|
||||||
|
binding.levels = []int{i}
|
||||||
|
bindings = append(bindings, binding)
|
||||||
|
}
|
||||||
|
return createStructDescriptor(cfg, typ, bindings, embeddedBindings), nil
|
||||||
|
}
|
||||||
|
func createStructDescriptor(cfg *frozenConfig, typ reflect.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor {
|
||||||
|
onePtrEmbedded := false
|
||||||
|
onePtrOptimization := false
|
||||||
|
if typ.NumField() == 1 {
|
||||||
|
firstField := typ.Field(0)
|
||||||
|
switch firstField.Type.Kind() {
|
||||||
|
case reflect.Ptr:
|
||||||
|
if firstField.Anonymous && firstField.Type.Elem().Kind() == reflect.Struct {
|
||||||
|
onePtrEmbedded = true
|
||||||
|
}
|
||||||
|
fallthrough
|
||||||
|
case reflect.Map:
|
||||||
|
onePtrOptimization = true
|
||||||
|
case reflect.Struct:
|
||||||
|
onePtrOptimization = isStructOnePtr(firstField.Type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
structDescriptor := &StructDescriptor{
|
structDescriptor := &StructDescriptor{
|
||||||
Type: typ,
|
onePtrEmbedded: onePtrEmbedded,
|
||||||
Fields: bindings,
|
onePtrOptimization: onePtrOptimization,
|
||||||
|
Type: typ,
|
||||||
|
Fields: bindings,
|
||||||
}
|
}
|
||||||
for _, extension := range extensions {
|
for _, extension := range extensions {
|
||||||
extension.UpdateStructDescriptor(structDescriptor)
|
extension.UpdateStructDescriptor(structDescriptor)
|
||||||
}
|
}
|
||||||
|
processTags(structDescriptor, cfg)
|
||||||
|
// merge normal & embedded bindings & sort with original order
|
||||||
|
allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...))
|
||||||
|
sort.Sort(allBindings)
|
||||||
|
structDescriptor.Fields = allBindings
|
||||||
|
return structDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
func isStructOnePtr(typ reflect.Type) bool {
|
||||||
|
if typ.NumField() == 1 {
|
||||||
|
firstField := typ.Field(0)
|
||||||
|
switch firstField.Type.Kind() {
|
||||||
|
case reflect.Ptr:
|
||||||
|
return true
|
||||||
|
case reflect.Map:
|
||||||
|
return true
|
||||||
|
case reflect.Struct:
|
||||||
|
return isStructOnePtr(firstField.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type sortableBindings []*Binding
|
||||||
|
|
||||||
|
func (bindings sortableBindings) Len() int {
|
||||||
|
return len(bindings)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bindings sortableBindings) Less(i, j int) bool {
|
||||||
|
left := bindings[i].levels
|
||||||
|
right := bindings[j].levels
|
||||||
|
k := 0
|
||||||
|
for {
|
||||||
|
if left[k] < right[k] {
|
||||||
|
return true
|
||||||
|
} else if left[k] > right[k] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
k++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bindings sortableBindings) Swap(i, j int) {
|
||||||
|
bindings[i], bindings[j] = bindings[j], bindings[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) {
|
||||||
for _, binding := range structDescriptor.Fields {
|
for _, binding := range structDescriptor.Fields {
|
||||||
shouldOmitEmpty := false
|
shouldOmitEmpty := false
|
||||||
tagParts := strings.Split(binding.Field.Tag.Get("json"), ",")
|
tagParts := strings.Split(binding.Field.Tag.Get(cfg.getTagKey()), ",")
|
||||||
for _, tagPart := range tagParts[1:] {
|
for _, tagPart := range tagParts[1:] {
|
||||||
if tagPart == "omitempty" {
|
if tagPart == "omitempty" {
|
||||||
shouldOmitEmpty = true
|
shouldOmitEmpty = true
|
||||||
} else if tagPart == "string" {
|
} else if tagPart == "string" {
|
||||||
binding.Decoder = &stringModeDecoder{binding.Decoder}
|
if binding.Field.Type.Kind() == reflect.String {
|
||||||
binding.Encoder = &stringModeEncoder{binding.Encoder}
|
binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg}
|
||||||
|
binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg}
|
||||||
|
} else {
|
||||||
|
binding.Decoder = &stringModeNumberDecoder{binding.Decoder}
|
||||||
|
binding.Encoder = &stringModeNumberEncoder{binding.Encoder}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder}
|
binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder}
|
||||||
binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty}
|
binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty}
|
||||||
}
|
}
|
||||||
// insert anonymous bindings to the head
|
|
||||||
structDescriptor.Fields = append(anonymousBindings, structDescriptor.Fields...)
|
|
||||||
return structDescriptor, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func calcFieldNames(originalFieldName string, tagProvidedFieldName string) []string {
|
func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
|
||||||
// tag => exported? => original
|
// ignore?
|
||||||
isNotExported := unicode.IsLower(rune(originalFieldName[0]))
|
if wholeTag == "-" {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
// rename?
|
||||||
var fieldNames []string
|
var fieldNames []string
|
||||||
/// tagParts[0] always present, even if no tags
|
if tagProvidedFieldName == "" {
|
||||||
switch tagProvidedFieldName {
|
fieldNames = []string{originalFieldName}
|
||||||
case "":
|
} else {
|
||||||
if isNotExported {
|
|
||||||
fieldNames = []string{}
|
|
||||||
} else {
|
|
||||||
fieldNames = []string{originalFieldName}
|
|
||||||
}
|
|
||||||
case "-":
|
|
||||||
fieldNames = []string{}
|
|
||||||
default:
|
|
||||||
fieldNames = []string{tagProvidedFieldName}
|
fieldNames = []string{tagProvidedFieldName}
|
||||||
}
|
}
|
||||||
|
// private?
|
||||||
|
isNotExported := unicode.IsLower(rune(originalFieldName[0]))
|
||||||
|
if isNotExported {
|
||||||
|
fieldNames = []string{}
|
||||||
|
}
|
||||||
return fieldNames
|
return fieldNames
|
||||||
}
|
}
|
||||||
|
@ -23,6 +23,10 @@ func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
mapInterface.word = ptr
|
mapInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&mapInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&mapInterface))
|
||||||
realVal := reflect.ValueOf(*realInterface).Elem()
|
realVal := reflect.ValueOf(*realInterface).Elem()
|
||||||
|
if iter.ReadNil() {
|
||||||
|
realVal.Set(reflect.Zero(decoder.mapType))
|
||||||
|
return
|
||||||
|
}
|
||||||
if realVal.IsNil() {
|
if realVal.IsNil() {
|
||||||
realVal.Set(reflect.MakeMap(realVal.Type()))
|
realVal.Set(reflect.MakeMap(realVal.Type()))
|
||||||
}
|
}
|
||||||
@ -31,9 +35,10 @@ func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
decoder.elemDecoder.Decode(unsafe.Pointer(elem.Pointer()), iter)
|
decoder.elemDecoder.Decode(unsafe.Pointer(elem.Pointer()), iter)
|
||||||
// to put into map, we have to use reflection
|
// to put into map, we have to use reflection
|
||||||
keyType := decoder.keyType
|
keyType := decoder.keyType
|
||||||
|
// TODO: remove this from loop
|
||||||
switch {
|
switch {
|
||||||
case keyType.Kind() == reflect.String:
|
case keyType.Kind() == reflect.String:
|
||||||
realVal.SetMapIndex(reflect.ValueOf(keyStr), elem.Elem())
|
realVal.SetMapIndex(reflect.ValueOf(keyStr).Convert(keyType), elem.Elem())
|
||||||
return true
|
return true
|
||||||
case keyType.Implements(textUnmarshalerType):
|
case keyType.Implements(textUnmarshalerType):
|
||||||
textUnmarshaler := reflect.New(keyType.Elem()).Interface().(encoding.TextUnmarshaler)
|
textUnmarshaler := reflect.New(keyType.Elem()).Interface().(encoding.TextUnmarshaler)
|
||||||
@ -44,6 +49,15 @@ func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
}
|
}
|
||||||
realVal.SetMapIndex(reflect.ValueOf(textUnmarshaler), elem.Elem())
|
realVal.SetMapIndex(reflect.ValueOf(textUnmarshaler), elem.Elem())
|
||||||
return true
|
return true
|
||||||
|
case reflect.PtrTo(keyType).Implements(textUnmarshalerType):
|
||||||
|
textUnmarshaler := reflect.New(keyType).Interface().(encoding.TextUnmarshaler)
|
||||||
|
err := textUnmarshaler.UnmarshalText([]byte(keyStr))
|
||||||
|
if err != nil {
|
||||||
|
iter.ReportError("read map key as TextUnmarshaler", err.Error())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
realVal.SetMapIndex(reflect.ValueOf(textUnmarshaler).Elem(), elem.Elem())
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
switch keyType.Kind() {
|
switch keyType.Kind() {
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
@ -81,14 +95,17 @@ func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
mapInterface.word = ptr
|
mapInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&mapInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&mapInterface))
|
||||||
realVal := reflect.ValueOf(*realInterface)
|
realVal := reflect.ValueOf(*realInterface)
|
||||||
|
|
||||||
stream.WriteObjectStart()
|
stream.WriteObjectStart()
|
||||||
for i, key := range realVal.MapKeys() {
|
for i, key := range realVal.MapKeys() {
|
||||||
if i != 0 {
|
if i != 0 {
|
||||||
stream.WriteMore()
|
stream.WriteMore()
|
||||||
}
|
}
|
||||||
encodeMapKey(key, stream)
|
encodeMapKey(key, stream)
|
||||||
stream.writeByte(':')
|
if stream.indention > 0 {
|
||||||
|
stream.writeTwoBytes(byte(':'), byte(' '))
|
||||||
|
} else {
|
||||||
|
stream.writeByte(':')
|
||||||
|
}
|
||||||
val := realVal.MapIndex(key).Interface()
|
val := realVal.MapIndex(key).Interface()
|
||||||
encoder.elemEncoder.EncodeInterface(val, stream)
|
encoder.elemEncoder.EncodeInterface(val, stream)
|
||||||
}
|
}
|
||||||
@ -123,7 +140,7 @@ func encodeMapKey(key reflect.Value, stream *Stream) {
|
|||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
stream.Error = &json.UnsupportedTypeError{key.Type()}
|
stream.Error = &json.UnsupportedTypeError{Type: key.Type()}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *mapEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
func (encoder *mapEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
@ -152,7 +169,15 @@ func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
realVal := reflect.ValueOf(*realInterface)
|
realVal := reflect.ValueOf(*realInterface)
|
||||||
|
|
||||||
// Extract and sort the keys.
|
// Extract and sort the keys.
|
||||||
var sv stringValues = realVal.MapKeys()
|
keys := realVal.MapKeys()
|
||||||
|
sv := stringValues(make([]reflectWithString, len(keys)))
|
||||||
|
for i, v := range keys {
|
||||||
|
sv[i].v = v
|
||||||
|
if err := sv[i].resolve(); err != nil {
|
||||||
|
stream.Error = err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
sort.Sort(sv)
|
sort.Sort(sv)
|
||||||
|
|
||||||
stream.WriteObjectStart()
|
stream.WriteObjectStart()
|
||||||
@ -160,9 +185,13 @@ func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
if i != 0 {
|
if i != 0 {
|
||||||
stream.WriteMore()
|
stream.WriteMore()
|
||||||
}
|
}
|
||||||
encodeMapKey(key, stream)
|
stream.WriteVal(key.s) // might need html escape, so can not WriteString directly
|
||||||
stream.writeByte(':')
|
if stream.indention > 0 {
|
||||||
val := realVal.MapIndex(key).Interface()
|
stream.writeTwoBytes(byte(':'), byte(' '))
|
||||||
|
} else {
|
||||||
|
stream.writeByte(':')
|
||||||
|
}
|
||||||
|
val := realVal.MapIndex(key.v).Interface()
|
||||||
encoder.elemEncoder.EncodeInterface(val, stream)
|
encoder.elemEncoder.EncodeInterface(val, stream)
|
||||||
}
|
}
|
||||||
stream.WriteObjectEnd()
|
stream.WriteObjectEnd()
|
||||||
@ -170,12 +199,37 @@ func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
|
|
||||||
// stringValues is a slice of reflect.Value holding *reflect.StringValue.
|
// stringValues is a slice of reflect.Value holding *reflect.StringValue.
|
||||||
// It implements the methods to sort by string.
|
// It implements the methods to sort by string.
|
||||||
type stringValues []reflect.Value
|
type stringValues []reflectWithString
|
||||||
|
|
||||||
|
type reflectWithString struct {
|
||||||
|
v reflect.Value
|
||||||
|
s string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *reflectWithString) resolve() error {
|
||||||
|
if w.v.Kind() == reflect.String {
|
||||||
|
w.s = w.v.String()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
|
||||||
|
buf, err := tm.MarshalText()
|
||||||
|
w.s = string(buf)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch w.v.Kind() {
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
w.s = strconv.FormatInt(w.v.Int(), 10)
|
||||||
|
return nil
|
||||||
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||||
|
w.s = strconv.FormatUint(w.v.Uint(), 10)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &json.UnsupportedTypeError{Type: w.v.Type()}
|
||||||
|
}
|
||||||
|
|
||||||
func (sv stringValues) Len() int { return len(sv) }
|
func (sv stringValues) Len() int { return len(sv) }
|
||||||
func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
|
func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
|
||||||
func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
|
func (sv stringValues) Less(i, j int) bool { return sv[i].s < sv[j].s }
|
||||||
func (sv stringValues) get(i int) string { return sv[i].String() }
|
|
||||||
|
|
||||||
func (encoder *sortKeysMapEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
func (encoder *sortKeysMapEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, encoder)
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -30,6 +32,10 @@ type intCodec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *intCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *intCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*int)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*int)(ptr)) = iter.ReadInt()
|
*((*int)(ptr)) = iter.ReadInt()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,18 +43,45 @@ func (codec *intCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteInt(*((*int)(ptr)))
|
stream.WriteInt(*((*int)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *intCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *intCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *intCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *intCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return *((*int)(ptr)) == 0
|
return *((*int)(ptr)) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type uintptrCodec struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *uintptrCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uintptr)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*((*uintptr)(ptr)) = uintptr(iter.ReadUint64())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *uintptrCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
|
stream.WriteUint64(uint64(*((*uintptr)(ptr))))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *uintptrCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
|
WriteToStream(val, stream, codec)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *uintptrCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
|
return *((*uintptr)(ptr)) == 0
|
||||||
|
}
|
||||||
|
|
||||||
type int8Codec struct {
|
type int8Codec struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint8)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*int8)(ptr)) = iter.ReadInt8()
|
*((*int8)(ptr)) = iter.ReadInt8()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -56,8 +89,8 @@ func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteInt8(*((*int8)(ptr)))
|
stream.WriteInt8(*((*int8)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *int8Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *int8Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -68,6 +101,10 @@ type int16Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*int16)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*int16)(ptr)) = iter.ReadInt16()
|
*((*int16)(ptr)) = iter.ReadInt16()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,8 +112,8 @@ func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteInt16(*((*int16)(ptr)))
|
stream.WriteInt16(*((*int16)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *int16Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *int16Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -87,6 +124,10 @@ type int32Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*int32)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*int32)(ptr)) = iter.ReadInt32()
|
*((*int32)(ptr)) = iter.ReadInt32()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,8 +135,8 @@ func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteInt32(*((*int32)(ptr)))
|
stream.WriteInt32(*((*int32)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *int32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *int32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -106,6 +147,10 @@ type int64Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*int64)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*int64)(ptr)) = iter.ReadInt64()
|
*((*int64)(ptr)) = iter.ReadInt64()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -113,8 +158,8 @@ func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteInt64(*((*int64)(ptr)))
|
stream.WriteInt64(*((*int64)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *int64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *int64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -125,6 +170,10 @@ type uintCodec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uintCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *uintCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*uint)(ptr)) = iter.ReadUint()
|
*((*uint)(ptr)) = iter.ReadUint()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -132,8 +181,8 @@ func (codec *uintCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteUint(*((*uint)(ptr)))
|
stream.WriteUint(*((*uint)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *uintCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *uintCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uintCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *uintCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -144,6 +193,10 @@ type uint8Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint8)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*uint8)(ptr)) = iter.ReadUint8()
|
*((*uint8)(ptr)) = iter.ReadUint8()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -151,8 +204,8 @@ func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteUint8(*((*uint8)(ptr)))
|
stream.WriteUint8(*((*uint8)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *uint8Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *uint8Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -162,7 +215,11 @@ func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
|||||||
type uint16Codec struct {
|
type uint16Codec struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint16)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*uint16)(ptr)) = iter.ReadUint16()
|
*((*uint16)(ptr)) = iter.ReadUint16()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,8 +227,8 @@ func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteUint16(*((*uint16)(ptr)))
|
stream.WriteUint16(*((*uint16)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *uint16Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *uint16Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -182,6 +239,10 @@ type uint32Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint32)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*uint32)(ptr)) = iter.ReadUint32()
|
*((*uint32)(ptr)) = iter.ReadUint32()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -189,8 +250,8 @@ func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteUint32(*((*uint32)(ptr)))
|
stream.WriteUint32(*((*uint32)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *uint32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *uint32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -201,6 +262,10 @@ type uint64Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*uint64)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*uint64)(ptr)) = iter.ReadUint64()
|
*((*uint64)(ptr)) = iter.ReadUint64()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -208,8 +273,8 @@ func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteUint64(*((*uint64)(ptr)))
|
stream.WriteUint64(*((*uint64)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *uint64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *uint64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -220,6 +285,10 @@ type float32Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*float32)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*float32)(ptr)) = iter.ReadFloat32()
|
*((*float32)(ptr)) = iter.ReadFloat32()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -227,8 +296,8 @@ func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteFloat32(*((*float32)(ptr)))
|
stream.WriteFloat32(*((*float32)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *float32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *float32Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -239,6 +308,10 @@ type float64Codec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if iter.ReadNil() {
|
||||||
|
*((*float64)(ptr)) = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
*((*float64)(ptr)) = iter.ReadFloat64()
|
*((*float64)(ptr)) = iter.ReadFloat64()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -246,8 +319,8 @@ func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteFloat64(*((*float64)(ptr)))
|
stream.WriteFloat64(*((*float64)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *float64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *float64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -258,15 +331,17 @@ type boolCodec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
*((*bool)(ptr)) = iter.ReadBool()
|
if !iter.ReadNil() {
|
||||||
|
*((*bool)(ptr)) = iter.ReadBool()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
stream.WriteBool(*((*bool)(ptr)))
|
stream.WriteBool(*((*bool)(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *boolCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *boolCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -277,19 +352,29 @@ type emptyInterfaceCodec struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (codec *emptyInterfaceCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *emptyInterfaceCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
*((*interface{})(ptr)) = iter.Read()
|
if iter.ReadNil() {
|
||||||
|
*((*interface{})(ptr)) = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
existing := *((*interface{})(ptr))
|
||||||
|
if existing != nil && reflect.TypeOf(existing).Kind() == reflect.Ptr {
|
||||||
|
iter.ReadVal(existing)
|
||||||
|
} else {
|
||||||
|
*((*interface{})(ptr)) = iter.Read()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *emptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (codec *emptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
stream.WriteVal(*((*interface{})(ptr)))
|
stream.WriteVal(*((*interface{})(ptr)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *emptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *emptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
stream.WriteVal(val)
|
stream.WriteVal(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *emptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *emptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return ptr == nil
|
emptyInterface := (*emptyInterface)(ptr)
|
||||||
|
return emptyInterface.typ == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type nonEmptyInterfaceCodec struct {
|
type nonEmptyInterfaceCodec struct {
|
||||||
@ -318,7 +403,7 @@ func (codec *nonEmptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream)
|
|||||||
stream.WriteVal(i)
|
stream.WriteVal(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *nonEmptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *nonEmptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
stream.WriteVal(val)
|
stream.WriteVal(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -338,11 +423,11 @@ func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
(*((*Any)(ptr))).WriteTo(stream)
|
(*((*Any)(ptr))).WriteTo(stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *anyCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *anyCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
(val.(Any)).WriteTo(stream)
|
(val.(Any)).WriteTo(stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return (*((*Any)(ptr))).Size() == 0
|
return (*((*Any)(ptr))).Size() == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -357,14 +442,33 @@ func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteRaw(string(*((*json.Number)(ptr))))
|
stream.WriteRaw(string(*((*json.Number)(ptr))))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsonNumberCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *jsonNumberCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
stream.WriteRaw(string(val.(json.Number)))
|
stream.WriteRaw(string(val.(json.Number)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return len(*((*json.Number)(ptr))) == 0
|
return len(*((*json.Number)(ptr))) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type jsoniterNumberCodec struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
*((*Number)(ptr)) = Number([]byte(iter.readNumberAsString()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
|
stream.WriteRaw(string(*((*Number)(ptr))))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *jsoniterNumberCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
|
stream.WriteRaw(string(val.(Number)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
|
return len(*((*Number)(ptr))) == 0
|
||||||
|
}
|
||||||
|
|
||||||
type jsonRawMessageCodec struct {
|
type jsonRawMessageCodec struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -376,11 +480,11 @@ func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
stream.WriteRaw(string(*((*json.RawMessage)(ptr))))
|
stream.WriteRaw(string(*((*json.RawMessage)(ptr))))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsonRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *jsonRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
stream.WriteRaw(string(val.(json.RawMessage)))
|
stream.WriteRaw(string(val.(json.RawMessage)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return len(*((*json.RawMessage)(ptr))) == 0
|
return len(*((*json.RawMessage)(ptr))) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -395,46 +499,59 @@ func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream)
|
|||||||
stream.WriteRaw(string(*((*RawMessage)(ptr))))
|
stream.WriteRaw(string(*((*RawMessage)(ptr))))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsoniterRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) {
|
func (codec *jsoniterRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
stream.WriteRaw(string(val.(RawMessage)))
|
stream.WriteRaw(string(val.(RawMessage)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return len(*((*RawMessage)(ptr))) == 0
|
return len(*((*RawMessage)(ptr))) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
type base64Codec struct {
|
type base64Codec struct {
|
||||||
|
sliceDecoder ValDecoder
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
encoding := base64.StdEncoding
|
if iter.ReadNil() {
|
||||||
src := iter.SkipAndReturnBytes()
|
ptrSlice := (*sliceHeader)(ptr)
|
||||||
src = src[1 : len(src)-1]
|
ptrSlice.Len = 0
|
||||||
decodedLen := encoding.DecodedLen(len(src))
|
ptrSlice.Cap = 0
|
||||||
dst := make([]byte, decodedLen)
|
ptrSlice.Data = nil
|
||||||
_, err := encoding.Decode(dst, src)
|
return
|
||||||
if err != nil {
|
}
|
||||||
iter.ReportError("decode base64", err.Error())
|
switch iter.WhatIsNext() {
|
||||||
} else {
|
case StringValue:
|
||||||
*((*[]byte)(ptr)) = dst
|
encoding := base64.StdEncoding
|
||||||
|
src := iter.SkipAndReturnBytes()
|
||||||
|
src = src[1 : len(src)-1]
|
||||||
|
decodedLen := encoding.DecodedLen(len(src))
|
||||||
|
dst := make([]byte, decodedLen)
|
||||||
|
len, err := encoding.Decode(dst, src)
|
||||||
|
if err != nil {
|
||||||
|
iter.ReportError("decode base64", err.Error())
|
||||||
|
} else {
|
||||||
|
dst = dst[:len]
|
||||||
|
dstSlice := (*sliceHeader)(unsafe.Pointer(&dst))
|
||||||
|
ptrSlice := (*sliceHeader)(ptr)
|
||||||
|
ptrSlice.Data = dstSlice.Data
|
||||||
|
ptrSlice.Cap = dstSlice.Cap
|
||||||
|
ptrSlice.Len = dstSlice.Len
|
||||||
|
}
|
||||||
|
case ArrayValue:
|
||||||
|
codec.sliceDecoder.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.ReportError("base64Codec", "invalid input")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
encoding := base64.StdEncoding
|
|
||||||
stream.writeByte('"')
|
|
||||||
src := *((*[]byte)(ptr))
|
src := *((*[]byte)(ptr))
|
||||||
toGrow := encoding.EncodedLen(len(src))
|
if len(src) == 0 {
|
||||||
stream.ensure(toGrow)
|
stream.WriteNil()
|
||||||
encoding.Encode(stream.buf[stream.n:], src)
|
return
|
||||||
stream.n += toGrow
|
}
|
||||||
stream.writeByte('"')
|
|
||||||
}
|
|
||||||
|
|
||||||
func (encoder *base64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
|
||||||
encoding := base64.StdEncoding
|
encoding := base64.StdEncoding
|
||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
src := val.([]byte)
|
|
||||||
toGrow := encoding.EncodedLen(len(src))
|
toGrow := encoding.EncodedLen(len(src))
|
||||||
stream.ensure(toGrow)
|
stream.ensure(toGrow)
|
||||||
encoding.Encode(stream.buf[stream.n:], src)
|
encoding.Encode(stream.buf[stream.n:], src)
|
||||||
@ -442,18 +559,34 @@ func (encoder *base64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
|||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *base64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *base64Codec) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
|
ptr := extractInterface(val).word
|
||||||
|
src := *((*[]byte)(ptr))
|
||||||
|
if len(src) == 0 {
|
||||||
|
stream.WriteNil()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
encoding := base64.StdEncoding
|
||||||
|
stream.writeByte('"')
|
||||||
|
toGrow := encoding.EncodedLen(len(src))
|
||||||
|
stream.ensure(toGrow)
|
||||||
|
encoding.Encode(stream.buf[stream.n:], src)
|
||||||
|
stream.n += toGrow
|
||||||
|
stream.writeByte('"')
|
||||||
|
}
|
||||||
|
|
||||||
|
func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return len(*((*[]byte)(ptr))) == 0
|
return len(*((*[]byte)(ptr))) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
type stringModeDecoder struct {
|
type stringModeNumberDecoder struct {
|
||||||
elemDecoder ValDecoder
|
elemDecoder ValDecoder
|
||||||
}
|
}
|
||||||
|
|
||||||
func (decoder *stringModeDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
c := iter.nextToken()
|
c := iter.nextToken()
|
||||||
if c != '"' {
|
if c != '"' {
|
||||||
iter.ReportError("stringModeDecoder", `expect "`)
|
iter.ReportError("stringModeNumberDecoder", `expect "`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
decoder.elemDecoder.Decode(ptr, iter)
|
decoder.elemDecoder.Decode(ptr, iter)
|
||||||
@ -462,31 +595,65 @@ func (decoder *stringModeDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
}
|
}
|
||||||
c = iter.readByte()
|
c = iter.readByte()
|
||||||
if c != '"' {
|
if c != '"' {
|
||||||
iter.ReportError("stringModeDecoder", `expect "`)
|
iter.ReportError("stringModeNumberDecoder", `expect "`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type stringModeEncoder struct {
|
type stringModeStringDecoder struct {
|
||||||
|
elemDecoder ValDecoder
|
||||||
|
cfg *frozenConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
decoder.elemDecoder.Decode(ptr, iter)
|
||||||
|
str := *((*string)(ptr))
|
||||||
|
tempIter := decoder.cfg.BorrowIterator([]byte(str))
|
||||||
|
defer decoder.cfg.ReturnIterator(tempIter)
|
||||||
|
*((*string)(ptr)) = tempIter.ReadString()
|
||||||
|
}
|
||||||
|
|
||||||
|
type stringModeNumberEncoder struct {
|
||||||
elemEncoder ValEncoder
|
elemEncoder ValEncoder
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *stringModeEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
encoder.elemEncoder.Encode(ptr, stream)
|
encoder.elemEncoder.Encode(ptr, stream)
|
||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *stringModeEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
func (encoder *stringModeNumberEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
WriteToStream(val, stream, encoder)
|
WriteToStream(val, stream, encoder)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *stringModeEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
|
return encoder.elemEncoder.IsEmpty(ptr)
|
||||||
|
}
|
||||||
|
|
||||||
|
type stringModeStringEncoder struct {
|
||||||
|
elemEncoder ValEncoder
|
||||||
|
cfg *frozenConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
|
tempStream := encoder.cfg.BorrowStream(nil)
|
||||||
|
defer encoder.cfg.ReturnStream(tempStream)
|
||||||
|
encoder.elemEncoder.Encode(ptr, tempStream)
|
||||||
|
stream.WriteString(string(tempStream.Buffer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (encoder *stringModeStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
|
WriteToStream(val, stream, encoder)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
return encoder.elemEncoder.IsEmpty(ptr)
|
return encoder.elemEncoder.IsEmpty(ptr)
|
||||||
}
|
}
|
||||||
|
|
||||||
type marshalerEncoder struct {
|
type marshalerEncoder struct {
|
||||||
templateInterface emptyInterface
|
templateInterface emptyInterface
|
||||||
|
checkIsEmpty checkIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
@ -494,6 +661,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
templateInterface.word = ptr
|
templateInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
||||||
marshaler := (*realInterface).(json.Marshaler)
|
marshaler := (*realInterface).(json.Marshaler)
|
||||||
|
|
||||||
bytes, err := marshaler.MarshalJSON()
|
bytes, err := marshaler.MarshalJSON()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
stream.Error = err
|
stream.Error = err
|
||||||
@ -506,18 +674,35 @@ func (encoder *marshalerEncoder) EncodeInterface(val interface{}, stream *Stream
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
|
return encoder.checkIsEmpty.IsEmpty(ptr)
|
||||||
|
}
|
||||||
|
|
||||||
|
type textMarshalerEncoder struct {
|
||||||
|
templateInterface emptyInterface
|
||||||
|
checkIsEmpty checkIsEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
||||||
templateInterface := encoder.templateInterface
|
templateInterface := encoder.templateInterface
|
||||||
templateInterface.word = ptr
|
templateInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
||||||
marshaler := (*realInterface).(json.Marshaler)
|
marshaler := (*realInterface).(encoding.TextMarshaler)
|
||||||
bytes, err := marshaler.MarshalJSON()
|
bytes, err := marshaler.MarshalText()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return true
|
stream.Error = err
|
||||||
} else {
|
} else {
|
||||||
return len(bytes) > 0
|
stream.WriteString(string(bytes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (encoder *textMarshalerEncoder) EncodeInterface(val interface{}, stream *Stream) {
|
||||||
|
WriteToStream(val, stream, encoder)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
|
return encoder.checkIsEmpty.IsEmpty(ptr)
|
||||||
|
}
|
||||||
|
|
||||||
type unmarshalerDecoder struct {
|
type unmarshalerDecoder struct {
|
||||||
templateInterface emptyInterface
|
templateInterface emptyInterface
|
||||||
}
|
}
|
||||||
@ -527,9 +712,27 @@ func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
templateInterface.word = ptr
|
templateInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
||||||
unmarshaler := (*realInterface).(json.Unmarshaler)
|
unmarshaler := (*realInterface).(json.Unmarshaler)
|
||||||
|
iter.nextToken()
|
||||||
|
iter.unreadByte() // skip spaces
|
||||||
bytes := iter.SkipAndReturnBytes()
|
bytes := iter.SkipAndReturnBytes()
|
||||||
err := unmarshaler.UnmarshalJSON(bytes)
|
err := unmarshaler.UnmarshalJSON(bytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
iter.ReportError("unmarshaler", err.Error())
|
iter.ReportError("unmarshalerDecoder", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type textUnmarshalerDecoder struct {
|
||||||
|
templateInterface emptyInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
templateInterface := decoder.templateInterface
|
||||||
|
templateInterface.word = ptr
|
||||||
|
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
||||||
|
unmarshaler := (*realInterface).(encoding.TextUnmarshaler)
|
||||||
|
str := iter.ReadString()
|
||||||
|
err := unmarshaler.UnmarshalText([]byte(str))
|
||||||
|
if err != nil {
|
||||||
|
iter.ReportError("textUnmarshalerDecoder", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -43,11 +43,11 @@ func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
stream.WriteArrayStart()
|
stream.WriteArrayStart()
|
||||||
elemPtr := uintptr(slice.Data)
|
elemPtr := unsafe.Pointer(slice.Data)
|
||||||
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
||||||
for i := 1; i < slice.Len; i++ {
|
for i := 1; i < slice.Len; i++ {
|
||||||
stream.WriteMore()
|
stream.WriteMore()
|
||||||
elemPtr += encoder.elemType.Size()
|
elemPtr = unsafe.Pointer(uintptr(elemPtr) + encoder.elemType.Size())
|
||||||
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream)
|
||||||
}
|
}
|
||||||
stream.WriteArrayEnd()
|
stream.WriteArrayEnd()
|
||||||
@ -87,36 +87,21 @@ func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
|||||||
|
|
||||||
func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) {
|
func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
slice := (*sliceHeader)(ptr)
|
slice := (*sliceHeader)(ptr)
|
||||||
|
if iter.ReadNil() {
|
||||||
|
slice.Len = 0
|
||||||
|
slice.Cap = 0
|
||||||
|
slice.Data = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
reuseSlice(slice, decoder.sliceType, 4)
|
reuseSlice(slice, decoder.sliceType, 4)
|
||||||
if !iter.ReadArray() {
|
slice.Len = 0
|
||||||
return
|
|
||||||
}
|
|
||||||
offset := uintptr(0)
|
offset := uintptr(0)
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
if !iter.ReadArray() {
|
|
||||||
slice.Len = 1
|
|
||||||
return
|
|
||||||
}
|
|
||||||
offset += decoder.elemType.Size()
|
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
|
||||||
if !iter.ReadArray() {
|
|
||||||
slice.Len = 2
|
|
||||||
return
|
|
||||||
}
|
|
||||||
offset += decoder.elemType.Size()
|
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
|
||||||
if !iter.ReadArray() {
|
|
||||||
slice.Len = 3
|
|
||||||
return
|
|
||||||
}
|
|
||||||
offset += decoder.elemType.Size()
|
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
|
||||||
slice.Len = 4
|
|
||||||
for iter.ReadArray() {
|
|
||||||
growOne(slice, decoder.sliceType, decoder.elemType)
|
growOne(slice, decoder.sliceType, decoder.elemType)
|
||||||
offset += decoder.elemType.Size()
|
|
||||||
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter)
|
||||||
}
|
offset += decoder.elemType.Size()
|
||||||
|
return true
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// grow grows the slice s so that it can hold extra more values, allocating
|
// grow grows the slice s so that it can hold extra more values, allocating
|
||||||
@ -139,7 +124,8 @@ func growOne(slice *sliceHeader, sliceType reflect.Type, elementType reflect.Typ
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
dst := unsafe.Pointer(reflect.MakeSlice(sliceType, newLen, newCap).Pointer())
|
newVal := reflect.MakeSlice(sliceType, newLen, newCap)
|
||||||
|
dst := unsafe.Pointer(newVal.Pointer())
|
||||||
// copy old array into new array
|
// copy old array into new array
|
||||||
originalBytesCount := uintptr(slice.Len) * elementType.Size()
|
originalBytesCount := uintptr(slice.Len) * elementType.Size()
|
||||||
srcPtr := (*[1 << 30]byte)(slice.Data)
|
srcPtr := (*[1 << 30]byte)(slice.Data)
|
||||||
@ -147,16 +133,17 @@ func growOne(slice *sliceHeader, sliceType reflect.Type, elementType reflect.Typ
|
|||||||
for i := uintptr(0); i < originalBytesCount; i++ {
|
for i := uintptr(0); i < originalBytesCount; i++ {
|
||||||
dstPtr[i] = srcPtr[i]
|
dstPtr[i] = srcPtr[i]
|
||||||
}
|
}
|
||||||
|
slice.Data = dst
|
||||||
slice.Len = newLen
|
slice.Len = newLen
|
||||||
slice.Cap = newCap
|
slice.Cap = newCap
|
||||||
slice.Data = dst
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func reuseSlice(slice *sliceHeader, sliceType reflect.Type, expectedCap int) {
|
func reuseSlice(slice *sliceHeader, sliceType reflect.Type, expectedCap int) {
|
||||||
if expectedCap <= slice.Cap {
|
if expectedCap <= slice.Cap {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
dst := unsafe.Pointer(reflect.MakeSlice(sliceType, 0, expectedCap).Pointer())
|
newVal := reflect.MakeSlice(sliceType, 0, expectedCap)
|
||||||
slice.Cap = expectedCap
|
dst := unsafe.Pointer(newVal.Pointer())
|
||||||
slice.Data = dst
|
slice.Data = dst
|
||||||
|
slice.Cap = expectedCap
|
||||||
}
|
}
|
||||||
|
916
feature_reflect_struct_decoder.go
Normal file
916
feature_reflect_struct_decoder.go
Normal file
@ -0,0 +1,916 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder) (ValDecoder, error) {
|
||||||
|
knownHash := map[int32]struct{}{
|
||||||
|
0: {},
|
||||||
|
}
|
||||||
|
switch len(fields) {
|
||||||
|
case 0:
|
||||||
|
return &skipObjectDecoder{typ}, nil
|
||||||
|
case 1:
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder}, nil
|
||||||
|
}
|
||||||
|
case 2:
|
||||||
|
var fieldHash1 int32
|
||||||
|
var fieldHash2 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldHash1 == 0 {
|
||||||
|
fieldHash1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldHash2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2}, nil
|
||||||
|
case 3:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &threeFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3}, nil
|
||||||
|
case 4:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &fourFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4}, nil
|
||||||
|
case 5:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &fiveFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5}, nil
|
||||||
|
case 6:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldName6 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
var fieldDecoder6 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else if fieldName5 == 0 {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName6 = fieldHash
|
||||||
|
fieldDecoder6 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &sixFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6}, nil
|
||||||
|
case 7:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldName6 int32
|
||||||
|
var fieldName7 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
var fieldDecoder6 *structFieldDecoder
|
||||||
|
var fieldDecoder7 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else if fieldName5 == 0 {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
} else if fieldName6 == 0 {
|
||||||
|
fieldName6 = fieldHash
|
||||||
|
fieldDecoder6 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName7 = fieldHash
|
||||||
|
fieldDecoder7 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &sevenFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6,
|
||||||
|
fieldName7, fieldDecoder7}, nil
|
||||||
|
case 8:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldName6 int32
|
||||||
|
var fieldName7 int32
|
||||||
|
var fieldName8 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
var fieldDecoder6 *structFieldDecoder
|
||||||
|
var fieldDecoder7 *structFieldDecoder
|
||||||
|
var fieldDecoder8 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else if fieldName5 == 0 {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
} else if fieldName6 == 0 {
|
||||||
|
fieldName6 = fieldHash
|
||||||
|
fieldDecoder6 = fieldDecoder
|
||||||
|
} else if fieldName7 == 0 {
|
||||||
|
fieldName7 = fieldHash
|
||||||
|
fieldDecoder7 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName8 = fieldHash
|
||||||
|
fieldDecoder8 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &eightFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6,
|
||||||
|
fieldName7, fieldDecoder7, fieldName8, fieldDecoder8}, nil
|
||||||
|
case 9:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldName6 int32
|
||||||
|
var fieldName7 int32
|
||||||
|
var fieldName8 int32
|
||||||
|
var fieldName9 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
var fieldDecoder6 *structFieldDecoder
|
||||||
|
var fieldDecoder7 *structFieldDecoder
|
||||||
|
var fieldDecoder8 *structFieldDecoder
|
||||||
|
var fieldDecoder9 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else if fieldName5 == 0 {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
} else if fieldName6 == 0 {
|
||||||
|
fieldName6 = fieldHash
|
||||||
|
fieldDecoder6 = fieldDecoder
|
||||||
|
} else if fieldName7 == 0 {
|
||||||
|
fieldName7 = fieldHash
|
||||||
|
fieldDecoder7 = fieldDecoder
|
||||||
|
} else if fieldName8 == 0 {
|
||||||
|
fieldName8 = fieldHash
|
||||||
|
fieldDecoder8 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName9 = fieldHash
|
||||||
|
fieldDecoder9 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &nineFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6,
|
||||||
|
fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, fieldName9, fieldDecoder9}, nil
|
||||||
|
case 10:
|
||||||
|
var fieldName1 int32
|
||||||
|
var fieldName2 int32
|
||||||
|
var fieldName3 int32
|
||||||
|
var fieldName4 int32
|
||||||
|
var fieldName5 int32
|
||||||
|
var fieldName6 int32
|
||||||
|
var fieldName7 int32
|
||||||
|
var fieldName8 int32
|
||||||
|
var fieldName9 int32
|
||||||
|
var fieldName10 int32
|
||||||
|
var fieldDecoder1 *structFieldDecoder
|
||||||
|
var fieldDecoder2 *structFieldDecoder
|
||||||
|
var fieldDecoder3 *structFieldDecoder
|
||||||
|
var fieldDecoder4 *structFieldDecoder
|
||||||
|
var fieldDecoder5 *structFieldDecoder
|
||||||
|
var fieldDecoder6 *structFieldDecoder
|
||||||
|
var fieldDecoder7 *structFieldDecoder
|
||||||
|
var fieldDecoder8 *structFieldDecoder
|
||||||
|
var fieldDecoder9 *structFieldDecoder
|
||||||
|
var fieldDecoder10 *structFieldDecoder
|
||||||
|
for fieldName, fieldDecoder := range fields {
|
||||||
|
fieldHash := calcHash(fieldName)
|
||||||
|
_, known := knownHash[fieldHash]
|
||||||
|
if known {
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
knownHash[fieldHash] = struct{}{}
|
||||||
|
if fieldName1 == 0 {
|
||||||
|
fieldName1 = fieldHash
|
||||||
|
fieldDecoder1 = fieldDecoder
|
||||||
|
} else if fieldName2 == 0 {
|
||||||
|
fieldName2 = fieldHash
|
||||||
|
fieldDecoder2 = fieldDecoder
|
||||||
|
} else if fieldName3 == 0 {
|
||||||
|
fieldName3 = fieldHash
|
||||||
|
fieldDecoder3 = fieldDecoder
|
||||||
|
} else if fieldName4 == 0 {
|
||||||
|
fieldName4 = fieldHash
|
||||||
|
fieldDecoder4 = fieldDecoder
|
||||||
|
} else if fieldName5 == 0 {
|
||||||
|
fieldName5 = fieldHash
|
||||||
|
fieldDecoder5 = fieldDecoder
|
||||||
|
} else if fieldName6 == 0 {
|
||||||
|
fieldName6 = fieldHash
|
||||||
|
fieldDecoder6 = fieldDecoder
|
||||||
|
} else if fieldName7 == 0 {
|
||||||
|
fieldName7 = fieldHash
|
||||||
|
fieldDecoder7 = fieldDecoder
|
||||||
|
} else if fieldName8 == 0 {
|
||||||
|
fieldName8 = fieldHash
|
||||||
|
fieldDecoder8 = fieldDecoder
|
||||||
|
} else if fieldName9 == 0 {
|
||||||
|
fieldName9 = fieldHash
|
||||||
|
fieldDecoder9 = fieldDecoder
|
||||||
|
} else {
|
||||||
|
fieldName10 = fieldHash
|
||||||
|
fieldDecoder10 = fieldDecoder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &tenFieldsStructDecoder{typ,
|
||||||
|
fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3,
|
||||||
|
fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6,
|
||||||
|
fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, fieldName9, fieldDecoder9,
|
||||||
|
fieldName10, fieldDecoder10}, nil
|
||||||
|
}
|
||||||
|
return &generalStructDecoder{typ, fields}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type generalStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fields map[string]*structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fieldBytes := iter.readObjectFieldAsBytes()
|
||||||
|
field := *(*string)(unsafe.Pointer(&fieldBytes))
|
||||||
|
fieldDecoder := decoder.fields[strings.ToLower(field)]
|
||||||
|
if fieldDecoder == nil {
|
||||||
|
iter.Skip()
|
||||||
|
} else {
|
||||||
|
fieldDecoder.Decode(ptr, iter)
|
||||||
|
}
|
||||||
|
for iter.nextToken() == ',' {
|
||||||
|
fieldBytes = iter.readObjectFieldAsBytes()
|
||||||
|
field = *(*string)(unsafe.Pointer(&fieldBytes))
|
||||||
|
fieldDecoder = decoder.fields[strings.ToLower(field)]
|
||||||
|
if fieldDecoder == nil {
|
||||||
|
iter.Skip()
|
||||||
|
} else {
|
||||||
|
fieldDecoder.Decode(ptr, iter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type skipObjectDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
valueType := iter.WhatIsNext()
|
||||||
|
if valueType != ObjectValue && valueType != NilValue {
|
||||||
|
iter.ReportError("skipObjectDecoder", "expect object or null")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
|
||||||
|
type oneFieldStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash int32
|
||||||
|
fieldDecoder *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
if iter.readFieldHash() == decoder.fieldHash {
|
||||||
|
decoder.fieldDecoder.Decode(ptr, iter)
|
||||||
|
} else {
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type twoFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type threeFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fourFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fiveFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sixFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
fieldHash6 int32
|
||||||
|
fieldDecoder6 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash6:
|
||||||
|
decoder.fieldDecoder6.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sevenFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
fieldHash6 int32
|
||||||
|
fieldDecoder6 *structFieldDecoder
|
||||||
|
fieldHash7 int32
|
||||||
|
fieldDecoder7 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash6:
|
||||||
|
decoder.fieldDecoder6.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash7:
|
||||||
|
decoder.fieldDecoder7.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type eightFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
fieldHash6 int32
|
||||||
|
fieldDecoder6 *structFieldDecoder
|
||||||
|
fieldHash7 int32
|
||||||
|
fieldDecoder7 *structFieldDecoder
|
||||||
|
fieldHash8 int32
|
||||||
|
fieldDecoder8 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash6:
|
||||||
|
decoder.fieldDecoder6.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash7:
|
||||||
|
decoder.fieldDecoder7.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash8:
|
||||||
|
decoder.fieldDecoder8.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type nineFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
fieldHash6 int32
|
||||||
|
fieldDecoder6 *structFieldDecoder
|
||||||
|
fieldHash7 int32
|
||||||
|
fieldDecoder7 *structFieldDecoder
|
||||||
|
fieldHash8 int32
|
||||||
|
fieldDecoder8 *structFieldDecoder
|
||||||
|
fieldHash9 int32
|
||||||
|
fieldDecoder9 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash6:
|
||||||
|
decoder.fieldDecoder6.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash7:
|
||||||
|
decoder.fieldDecoder7.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash8:
|
||||||
|
decoder.fieldDecoder8.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash9:
|
||||||
|
decoder.fieldDecoder9.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type tenFieldsStructDecoder struct {
|
||||||
|
typ reflect.Type
|
||||||
|
fieldHash1 int32
|
||||||
|
fieldDecoder1 *structFieldDecoder
|
||||||
|
fieldHash2 int32
|
||||||
|
fieldDecoder2 *structFieldDecoder
|
||||||
|
fieldHash3 int32
|
||||||
|
fieldDecoder3 *structFieldDecoder
|
||||||
|
fieldHash4 int32
|
||||||
|
fieldDecoder4 *structFieldDecoder
|
||||||
|
fieldHash5 int32
|
||||||
|
fieldDecoder5 *structFieldDecoder
|
||||||
|
fieldHash6 int32
|
||||||
|
fieldDecoder6 *structFieldDecoder
|
||||||
|
fieldHash7 int32
|
||||||
|
fieldDecoder7 *structFieldDecoder
|
||||||
|
fieldHash8 int32
|
||||||
|
fieldDecoder8 *structFieldDecoder
|
||||||
|
fieldHash9 int32
|
||||||
|
fieldDecoder9 *structFieldDecoder
|
||||||
|
fieldHash10 int32
|
||||||
|
fieldDecoder10 *structFieldDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
if !iter.readObjectStart() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
switch iter.readFieldHash() {
|
||||||
|
case decoder.fieldHash1:
|
||||||
|
decoder.fieldDecoder1.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash2:
|
||||||
|
decoder.fieldDecoder2.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash3:
|
||||||
|
decoder.fieldDecoder3.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash4:
|
||||||
|
decoder.fieldDecoder4.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash5:
|
||||||
|
decoder.fieldDecoder5.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash6:
|
||||||
|
decoder.fieldDecoder6.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash7:
|
||||||
|
decoder.fieldDecoder7.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash8:
|
||||||
|
decoder.fieldDecoder8.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash9:
|
||||||
|
decoder.fieldDecoder9.Decode(ptr, iter)
|
||||||
|
case decoder.fieldHash10:
|
||||||
|
decoder.fieldDecoder10.Decode(ptr, iter)
|
||||||
|
default:
|
||||||
|
iter.Skip()
|
||||||
|
}
|
||||||
|
if iter.isObjectEnd() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type structFieldDecoder struct {
|
||||||
|
field *reflect.StructField
|
||||||
|
fieldDecoder ValDecoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
fieldPtr := unsafe.Pointer(uintptr(ptr) + decoder.field.Offset)
|
||||||
|
decoder.fieldDecoder.Decode(fieldPtr, iter)
|
||||||
|
if iter.Error != nil && iter.Error != io.EOF {
|
||||||
|
iter.Error = fmt.Errorf("%s: %s", decoder.field.Name, iter.Error.Error())
|
||||||
|
}
|
||||||
|
}
|
@ -4,6 +4,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Stream is a io.Writer like object, with JSON specific write functions.
|
||||||
|
// Error is not returned as return value, but stored as Error member on this stream instance.
|
||||||
type Stream struct {
|
type Stream struct {
|
||||||
cfg *frozenConfig
|
cfg *frozenConfig
|
||||||
out io.Writer
|
out io.Writer
|
||||||
@ -13,9 +15,13 @@ type Stream struct {
|
|||||||
indention int
|
indention int
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewStream(cfg *frozenConfig, out io.Writer, bufSize int) *Stream {
|
// NewStream create new stream instance.
|
||||||
|
// cfg can be jsoniter.ConfigDefault.
|
||||||
|
// out can be nil if write to internal buffer.
|
||||||
|
// bufSize is the initial size for the internal buffer in bytes.
|
||||||
|
func NewStream(cfg API, out io.Writer, bufSize int) *Stream {
|
||||||
return &Stream{
|
return &Stream{
|
||||||
cfg: cfg,
|
cfg: cfg.(*frozenConfig),
|
||||||
out: out,
|
out: out,
|
||||||
buf: make([]byte, bufSize),
|
buf: make([]byte, bufSize),
|
||||||
n: 0,
|
n: 0,
|
||||||
@ -24,191 +30,203 @@ func NewStream(cfg *frozenConfig, out io.Writer, bufSize int) *Stream {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) Reset(out io.Writer) {
|
// Pool returns a pool can provide more stream with same configuration
|
||||||
b.out = out
|
func (stream *Stream) Pool() StreamPool {
|
||||||
b.n = 0
|
return stream.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset reuse this stream instance by assign a new writer
|
||||||
|
func (stream *Stream) Reset(out io.Writer) {
|
||||||
|
stream.out = out
|
||||||
|
stream.n = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Available returns how many bytes are unused in the buffer.
|
// Available returns how many bytes are unused in the buffer.
|
||||||
func (b *Stream) Available() int {
|
func (stream *Stream) Available() int {
|
||||||
return len(b.buf) - b.n
|
return len(stream.buf) - stream.n
|
||||||
}
|
}
|
||||||
|
|
||||||
// Buffered returns the number of bytes that have been written into the current buffer.
|
// Buffered returns the number of bytes that have been written into the current buffer.
|
||||||
func (b *Stream) Buffered() int {
|
func (stream *Stream) Buffered() int {
|
||||||
return b.n
|
return stream.n
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) Buffer() []byte {
|
// Buffer if writer is nil, use this method to take the result
|
||||||
return b.buf[:b.n]
|
func (stream *Stream) Buffer() []byte {
|
||||||
|
return stream.buf[:stream.n]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write writes the contents of p into the buffer.
|
// Write writes the contents of p into the buffer.
|
||||||
// It returns the number of bytes written.
|
// It returns the number of bytes written.
|
||||||
// If nn < len(p), it also returns an error explaining
|
// If nn < len(p), it also returns an error explaining
|
||||||
// why the write is short.
|
// why the write is short.
|
||||||
func (b *Stream) Write(p []byte) (nn int, err error) {
|
func (stream *Stream) Write(p []byte) (nn int, err error) {
|
||||||
for len(p) > b.Available() && b.Error == nil {
|
for len(p) > stream.Available() && stream.Error == nil {
|
||||||
if b.out == nil {
|
if stream.out == nil {
|
||||||
b.growAtLeast(len(p))
|
stream.growAtLeast(len(p))
|
||||||
} else {
|
} else {
|
||||||
var n int
|
var n int
|
||||||
if b.Buffered() == 0 {
|
if stream.Buffered() == 0 {
|
||||||
// Large write, empty buffer.
|
// Large write, empty buffer.
|
||||||
// Write directly from p to avoid copy.
|
// Write directly from p to avoid copy.
|
||||||
n, b.Error = b.out.Write(p)
|
n, stream.Error = stream.out.Write(p)
|
||||||
} else {
|
} else {
|
||||||
n = copy(b.buf[b.n:], p)
|
n = copy(stream.buf[stream.n:], p)
|
||||||
b.n += n
|
stream.n += n
|
||||||
b.Flush()
|
stream.Flush()
|
||||||
}
|
}
|
||||||
nn += n
|
nn += n
|
||||||
p = p[n:]
|
p = p[n:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return nn, b.Error
|
return nn, stream.Error
|
||||||
}
|
}
|
||||||
n := copy(b.buf[b.n:], p)
|
n := copy(stream.buf[stream.n:], p)
|
||||||
b.n += n
|
stream.n += n
|
||||||
nn += n
|
nn += n
|
||||||
return nn, nil
|
return nn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteByte writes a single byte.
|
// WriteByte writes a single byte.
|
||||||
func (b *Stream) writeByte(c byte) {
|
func (stream *Stream) writeByte(c byte) {
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b.Available() < 1 {
|
if stream.Available() < 1 {
|
||||||
b.growAtLeast(1)
|
stream.growAtLeast(1)
|
||||||
}
|
}
|
||||||
b.buf[b.n] = c
|
stream.buf[stream.n] = c
|
||||||
b.n++
|
stream.n++
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) writeTwoBytes(c1 byte, c2 byte) {
|
func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) {
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b.Available() < 2 {
|
if stream.Available() < 2 {
|
||||||
b.growAtLeast(2)
|
stream.growAtLeast(2)
|
||||||
}
|
}
|
||||||
b.buf[b.n] = c1
|
stream.buf[stream.n] = c1
|
||||||
b.buf[b.n+1] = c2
|
stream.buf[stream.n+1] = c2
|
||||||
b.n += 2
|
stream.n += 2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) {
|
func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) {
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b.Available() < 3 {
|
if stream.Available() < 3 {
|
||||||
b.growAtLeast(3)
|
stream.growAtLeast(3)
|
||||||
}
|
}
|
||||||
b.buf[b.n] = c1
|
stream.buf[stream.n] = c1
|
||||||
b.buf[b.n+1] = c2
|
stream.buf[stream.n+1] = c2
|
||||||
b.buf[b.n+2] = c3
|
stream.buf[stream.n+2] = c3
|
||||||
b.n += 3
|
stream.n += 3
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) {
|
func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) {
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b.Available() < 4 {
|
if stream.Available() < 4 {
|
||||||
b.growAtLeast(4)
|
stream.growAtLeast(4)
|
||||||
}
|
}
|
||||||
b.buf[b.n] = c1
|
stream.buf[stream.n] = c1
|
||||||
b.buf[b.n+1] = c2
|
stream.buf[stream.n+1] = c2
|
||||||
b.buf[b.n+2] = c3
|
stream.buf[stream.n+2] = c3
|
||||||
b.buf[b.n+3] = c4
|
stream.buf[stream.n+3] = c4
|
||||||
b.n += 4
|
stream.n += 4
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) {
|
func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) {
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b.Available() < 5 {
|
if stream.Available() < 5 {
|
||||||
b.growAtLeast(5)
|
stream.growAtLeast(5)
|
||||||
}
|
}
|
||||||
b.buf[b.n] = c1
|
stream.buf[stream.n] = c1
|
||||||
b.buf[b.n+1] = c2
|
stream.buf[stream.n+1] = c2
|
||||||
b.buf[b.n+2] = c3
|
stream.buf[stream.n+2] = c3
|
||||||
b.buf[b.n+3] = c4
|
stream.buf[stream.n+3] = c4
|
||||||
b.buf[b.n+4] = c5
|
stream.buf[stream.n+4] = c5
|
||||||
b.n += 5
|
stream.n += 5
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flush writes any buffered data to the underlying io.Writer.
|
// Flush writes any buffered data to the underlying io.Writer.
|
||||||
func (b *Stream) Flush() error {
|
func (stream *Stream) Flush() error {
|
||||||
if b.out == nil {
|
if stream.out == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if b.Error != nil {
|
if stream.Error != nil {
|
||||||
return b.Error
|
return stream.Error
|
||||||
}
|
}
|
||||||
if b.n == 0 {
|
if stream.n == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
n, err := b.out.Write(b.buf[0:b.n])
|
n, err := stream.out.Write(stream.buf[0:stream.n])
|
||||||
if n < b.n && err == nil {
|
if n < stream.n && err == nil {
|
||||||
err = io.ErrShortWrite
|
err = io.ErrShortWrite
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if n > 0 && n < b.n {
|
if n > 0 && n < stream.n {
|
||||||
copy(b.buf[0:b.n-n], b.buf[n:b.n])
|
copy(stream.buf[0:stream.n-n], stream.buf[n:stream.n])
|
||||||
}
|
}
|
||||||
b.n -= n
|
stream.n -= n
|
||||||
b.Error = err
|
stream.Error = err
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
b.n = 0
|
stream.n = 0
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) ensure(minimal int) {
|
func (stream *Stream) ensure(minimal int) {
|
||||||
available := b.Available()
|
available := stream.Available()
|
||||||
if available < minimal {
|
if available < minimal {
|
||||||
if b.n > 1024 {
|
stream.growAtLeast(minimal)
|
||||||
b.Flush()
|
|
||||||
}
|
|
||||||
b.growAtLeast(minimal)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) growAtLeast(minimal int) {
|
func (stream *Stream) growAtLeast(minimal int) {
|
||||||
toGrow := len(b.buf)
|
if stream.out != nil {
|
||||||
|
stream.Flush()
|
||||||
|
}
|
||||||
|
toGrow := len(stream.buf)
|
||||||
if toGrow < minimal {
|
if toGrow < minimal {
|
||||||
toGrow = minimal
|
toGrow = minimal
|
||||||
}
|
}
|
||||||
newBuf := make([]byte, len(b.buf)+toGrow)
|
newBuf := make([]byte, len(stream.buf)+toGrow)
|
||||||
copy(newBuf, b.Buffer())
|
copy(newBuf, stream.Buffer())
|
||||||
b.buf = newBuf
|
stream.buf = newBuf
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Stream) WriteRaw(s string) {
|
// WriteRaw write string out without quotes, just like []byte
|
||||||
b.ensure(len(s))
|
func (stream *Stream) WriteRaw(s string) {
|
||||||
if b.Error != nil {
|
stream.ensure(len(s))
|
||||||
|
if stream.Error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
n := copy(b.buf[b.n:], s)
|
n := copy(stream.buf[stream.n:], s)
|
||||||
b.n += n
|
stream.n += n
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteNil write null to stream
|
||||||
func (stream *Stream) WriteNil() {
|
func (stream *Stream) WriteNil() {
|
||||||
stream.writeFourBytes('n', 'u', 'l', 'l')
|
stream.writeFourBytes('n', 'u', 'l', 'l')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteTrue write true to stream
|
||||||
func (stream *Stream) WriteTrue() {
|
func (stream *Stream) WriteTrue() {
|
||||||
stream.writeFourBytes('t', 'r', 'u', 'e')
|
stream.writeFourBytes('t', 'r', 'u', 'e')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteFalse write false to stream
|
||||||
func (stream *Stream) WriteFalse() {
|
func (stream *Stream) WriteFalse() {
|
||||||
stream.writeFiveBytes('f', 'a', 'l', 's', 'e')
|
stream.writeFiveBytes('f', 'a', 'l', 's', 'e')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteBool write true or false into stream
|
||||||
func (stream *Stream) WriteBool(val bool) {
|
func (stream *Stream) WriteBool(val bool) {
|
||||||
if val {
|
if val {
|
||||||
stream.WriteTrue()
|
stream.WriteTrue()
|
||||||
@ -217,44 +235,56 @@ func (stream *Stream) WriteBool(val bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteObjectStart write { with possible indention
|
||||||
func (stream *Stream) WriteObjectStart() {
|
func (stream *Stream) WriteObjectStart() {
|
||||||
stream.indention += stream.cfg.indentionStep
|
stream.indention += stream.cfg.indentionStep
|
||||||
stream.writeByte('{')
|
stream.writeByte('{')
|
||||||
stream.writeIndention(0)
|
stream.writeIndention(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteObjectField write "field": with possible indention
|
||||||
func (stream *Stream) WriteObjectField(field string) {
|
func (stream *Stream) WriteObjectField(field string) {
|
||||||
stream.WriteString(field)
|
stream.WriteString(field)
|
||||||
stream.writeByte(':')
|
if stream.indention > 0 {
|
||||||
|
stream.writeTwoBytes(':', ' ')
|
||||||
|
} else {
|
||||||
|
stream.writeByte(':')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteObjectEnd write } with possible indention
|
||||||
func (stream *Stream) WriteObjectEnd() {
|
func (stream *Stream) WriteObjectEnd() {
|
||||||
stream.writeIndention(stream.cfg.indentionStep)
|
stream.writeIndention(stream.cfg.indentionStep)
|
||||||
stream.indention -= stream.cfg.indentionStep
|
stream.indention -= stream.cfg.indentionStep
|
||||||
stream.writeByte('}')
|
stream.writeByte('}')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteEmptyObject write {}
|
||||||
func (stream *Stream) WriteEmptyObject() {
|
func (stream *Stream) WriteEmptyObject() {
|
||||||
stream.writeByte('{')
|
stream.writeByte('{')
|
||||||
stream.writeByte('}')
|
stream.writeByte('}')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteMore write , with possible indention
|
||||||
func (stream *Stream) WriteMore() {
|
func (stream *Stream) WriteMore() {
|
||||||
stream.writeByte(',')
|
stream.writeByte(',')
|
||||||
stream.writeIndention(0)
|
stream.writeIndention(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteArrayStart write [ with possible indention
|
||||||
func (stream *Stream) WriteArrayStart() {
|
func (stream *Stream) WriteArrayStart() {
|
||||||
stream.indention += stream.cfg.indentionStep
|
stream.indention += stream.cfg.indentionStep
|
||||||
stream.writeByte('[')
|
stream.writeByte('[')
|
||||||
stream.writeIndention(0)
|
stream.writeIndention(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteEmptyArray write []
|
||||||
func (stream *Stream) WriteEmptyArray() {
|
func (stream *Stream) WriteEmptyArray() {
|
||||||
stream.writeByte('[')
|
stream.writeByte('[')
|
||||||
stream.writeByte(']')
|
stream.writeByte(']')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteArrayEnd write ] with possible indention
|
||||||
func (stream *Stream) WriteArrayEnd() {
|
func (stream *Stream) WriteArrayEnd() {
|
||||||
stream.writeIndention(stream.cfg.indentionStep)
|
stream.writeIndention(stream.cfg.indentionStep)
|
||||||
stream.indention -= stream.cfg.indentionStep
|
stream.indention -= stream.cfg.indentionStep
|
||||||
|
@ -1,26 +1,37 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _POW10 []uint64
|
var pow10 []uint64
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
_POW10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000}
|
pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteFloat32 write float32 to stream
|
||||||
func (stream *Stream) WriteFloat32(val float32) {
|
func (stream *Stream) WriteFloat32(val float32) {
|
||||||
stream.WriteRaw(strconv.FormatFloat(float64(val), 'f', -1, 32))
|
abs := math.Abs(float64(val))
|
||||||
|
fmt := byte('f')
|
||||||
|
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
|
||||||
|
if abs != 0 {
|
||||||
|
if float32(abs) < 1e-6 || float32(abs) >= 1e21 {
|
||||||
|
fmt = 'e'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 32))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster
|
||||||
func (stream *Stream) WriteFloat32Lossy(val float32) {
|
func (stream *Stream) WriteFloat32Lossy(val float32) {
|
||||||
if val < 0 {
|
if val < 0 {
|
||||||
stream.writeByte('-')
|
stream.writeByte('-')
|
||||||
val = -val
|
val = -val
|
||||||
}
|
}
|
||||||
if val > 0x4ffffff {
|
if val > 0x4ffffff {
|
||||||
stream.WriteRaw(strconv.FormatFloat(float64(val), 'f', -1, 32))
|
stream.WriteFloat32(val)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
precision := 6
|
precision := 6
|
||||||
@ -33,7 +44,7 @@ func (stream *Stream) WriteFloat32Lossy(val float32) {
|
|||||||
}
|
}
|
||||||
stream.writeByte('.')
|
stream.writeByte('.')
|
||||||
stream.ensure(10)
|
stream.ensure(10)
|
||||||
for p := precision - 1; p > 0 && fval < _POW10[p]; p-- {
|
for p := precision - 1; p > 0 && fval < pow10[p]; p-- {
|
||||||
stream.writeByte('0')
|
stream.writeByte('0')
|
||||||
}
|
}
|
||||||
stream.WriteUint64(fval)
|
stream.WriteUint64(fval)
|
||||||
@ -42,17 +53,27 @@ func (stream *Stream) WriteFloat32Lossy(val float32) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteFloat64 write float64 to stream
|
||||||
func (stream *Stream) WriteFloat64(val float64) {
|
func (stream *Stream) WriteFloat64(val float64) {
|
||||||
stream.WriteRaw(strconv.FormatFloat(float64(val), 'f', -1, 64))
|
abs := math.Abs(val)
|
||||||
|
fmt := byte('f')
|
||||||
|
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
|
||||||
|
if abs != 0 {
|
||||||
|
if abs < 1e-6 || abs >= 1e21 {
|
||||||
|
fmt = 'e'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 64))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster
|
||||||
func (stream *Stream) WriteFloat64Lossy(val float64) {
|
func (stream *Stream) WriteFloat64Lossy(val float64) {
|
||||||
if val < 0 {
|
if val < 0 {
|
||||||
stream.writeByte('-')
|
stream.writeByte('-')
|
||||||
val = -val
|
val = -val
|
||||||
}
|
}
|
||||||
if val > 0x4ffffff {
|
if val > 0x4ffffff {
|
||||||
stream.WriteRaw(strconv.FormatFloat(val, 'f', -1, 64))
|
stream.WriteFloat64(val)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
precision := 6
|
precision := 6
|
||||||
@ -65,7 +86,7 @@ func (stream *Stream) WriteFloat64Lossy(val float64) {
|
|||||||
}
|
}
|
||||||
stream.writeByte('.')
|
stream.writeByte('.')
|
||||||
stream.ensure(10)
|
stream.ensure(10)
|
||||||
for p := precision - 1; p > 0 && fval < _POW10[p]; p-- {
|
for p := precision - 1; p > 0 && fval < pow10[p]; p-- {
|
||||||
stream.writeByte('0')
|
stream.writeByte('0')
|
||||||
}
|
}
|
||||||
stream.WriteUint64(fval)
|
stream.WriteUint64(fval)
|
||||||
|
@ -1,15 +1,15 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
var _DIGITS []uint32
|
var digits []uint32
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
_DIGITS = make([]uint32, 1000)
|
digits = make([]uint32, 1000)
|
||||||
for i := uint32(0); i < 1000; i++ {
|
for i := uint32(0); i < 1000; i++ {
|
||||||
_DIGITS[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0'
|
digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0'
|
||||||
if i < 10 {
|
if i < 10 {
|
||||||
_DIGITS[i] += 2 << 24
|
digits[i] += 2 << 24
|
||||||
} else if i < 100 {
|
} else if i < 100 {
|
||||||
_DIGITS[i] += 1 << 24
|
digits[i] += 1 << 24
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -36,11 +36,13 @@ func writeBuf(buf []byte, v uint32, n int) {
|
|||||||
buf[n+2] = byte(v)
|
buf[n+2] = byte(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteUint8 write uint8 to stream
|
||||||
func (stream *Stream) WriteUint8(val uint8) {
|
func (stream *Stream) WriteUint8(val uint8) {
|
||||||
stream.ensure(3)
|
stream.ensure(3)
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], stream.n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], stream.n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteInt8 write int8 to stream
|
||||||
func (stream *Stream) WriteInt8(nval int8) {
|
func (stream *Stream) WriteInt8(nval int8) {
|
||||||
stream.ensure(4)
|
stream.ensure(4)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
@ -52,23 +54,25 @@ func (stream *Stream) WriteInt8(nval int8) {
|
|||||||
} else {
|
} else {
|
||||||
val = uint8(nval)
|
val = uint8(nval)
|
||||||
}
|
}
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteUint16 write uint16 to stream
|
||||||
func (stream *Stream) WriteUint16(val uint16) {
|
func (stream *Stream) WriteUint16(val uint16) {
|
||||||
stream.ensure(5)
|
stream.ensure(5)
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], stream.n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], stream.n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
n := writeFirstBuf(stream.buf, _DIGITS[q1], stream.n)
|
n := writeFirstBuf(stream.buf, digits[q1], stream.n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteInt16 write int16 to stream
|
||||||
func (stream *Stream) WriteInt16(nval int16) {
|
func (stream *Stream) WriteInt16(nval int16) {
|
||||||
stream.ensure(6)
|
stream.ensure(6)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
@ -82,48 +86,50 @@ func (stream *Stream) WriteInt16(nval int16) {
|
|||||||
}
|
}
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q1], n)
|
n = writeFirstBuf(stream.buf, digits[q1], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteUint32 write uint32 to stream
|
||||||
func (stream *Stream) WriteUint32(val uint32) {
|
func (stream *Stream) WriteUint32(val uint32) {
|
||||||
stream.ensure(10)
|
stream.ensure(10)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
q2 := q1 / 1000
|
q2 := q1 / 1000
|
||||||
if q2 == 0 {
|
if q2 == 0 {
|
||||||
n := writeFirstBuf(stream.buf, _DIGITS[q1], n)
|
n := writeFirstBuf(stream.buf, digits[q1], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r2 := q1 - q2*1000
|
r2 := q1 - q2*1000
|
||||||
q3 := q2 / 1000
|
q3 := q2 / 1000
|
||||||
if q3 == 0 {
|
if q3 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q2], n)
|
n = writeFirstBuf(stream.buf, digits[q2], n)
|
||||||
} else {
|
} else {
|
||||||
r3 := q2 - q3*1000
|
r3 := q2 - q3*1000
|
||||||
stream.buf[n] = byte(q3 + '0')
|
stream.buf[n] = byte(q3 + '0')
|
||||||
n++
|
n++
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n)
|
writeBuf(stream.buf, digits[r3], n)
|
||||||
n += 3
|
n += 3
|
||||||
}
|
}
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n)
|
writeBuf(stream.buf, digits[r2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+3)
|
writeBuf(stream.buf, digits[r1], n+3)
|
||||||
stream.n = n + 6
|
stream.n = n + 6
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteInt32 write int32 to stream
|
||||||
func (stream *Stream) WriteInt32(nval int32) {
|
func (stream *Stream) WriteInt32(nval int32) {
|
||||||
stream.ensure(11)
|
stream.ensure(11)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
@ -137,97 +143,99 @@ func (stream *Stream) WriteInt32(nval int32) {
|
|||||||
}
|
}
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
q2 := q1 / 1000
|
q2 := q1 / 1000
|
||||||
if q2 == 0 {
|
if q2 == 0 {
|
||||||
n := writeFirstBuf(stream.buf, _DIGITS[q1], n)
|
n := writeFirstBuf(stream.buf, digits[q1], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r2 := q1 - q2*1000
|
r2 := q1 - q2*1000
|
||||||
q3 := q2 / 1000
|
q3 := q2 / 1000
|
||||||
if q3 == 0 {
|
if q3 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q2], n)
|
n = writeFirstBuf(stream.buf, digits[q2], n)
|
||||||
} else {
|
} else {
|
||||||
r3 := q2 - q3*1000
|
r3 := q2 - q3*1000
|
||||||
stream.buf[n] = byte(q3 + '0')
|
stream.buf[n] = byte(q3 + '0')
|
||||||
n++
|
n++
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n)
|
writeBuf(stream.buf, digits[r3], n)
|
||||||
n += 3
|
n += 3
|
||||||
}
|
}
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n)
|
writeBuf(stream.buf, digits[r2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+3)
|
writeBuf(stream.buf, digits[r1], n+3)
|
||||||
stream.n = n + 6
|
stream.n = n + 6
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteUint64 write uint64 to stream
|
||||||
func (stream *Stream) WriteUint64(val uint64) {
|
func (stream *Stream) WriteUint64(val uint64) {
|
||||||
stream.ensure(20)
|
stream.ensure(20)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
q2 := q1 / 1000
|
q2 := q1 / 1000
|
||||||
if q2 == 0 {
|
if q2 == 0 {
|
||||||
n := writeFirstBuf(stream.buf, _DIGITS[q1], n)
|
n := writeFirstBuf(stream.buf, digits[q1], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r2 := q1 - q2*1000
|
r2 := q1 - q2*1000
|
||||||
q3 := q2 / 1000
|
q3 := q2 / 1000
|
||||||
if q3 == 0 {
|
if q3 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q2], n)
|
n = writeFirstBuf(stream.buf, digits[q2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n)
|
writeBuf(stream.buf, digits[r2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+3)
|
writeBuf(stream.buf, digits[r1], n+3)
|
||||||
stream.n = n + 6
|
stream.n = n + 6
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r3 := q2 - q3*1000
|
r3 := q2 - q3*1000
|
||||||
q4 := q3 / 1000
|
q4 := q3 / 1000
|
||||||
if q4 == 0 {
|
if q4 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q3], n)
|
n = writeFirstBuf(stream.buf, digits[q3], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n)
|
writeBuf(stream.buf, digits[r3], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+3)
|
writeBuf(stream.buf, digits[r2], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+6)
|
writeBuf(stream.buf, digits[r1], n+6)
|
||||||
stream.n = n + 9
|
stream.n = n + 9
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r4 := q3 - q4*1000
|
r4 := q3 - q4*1000
|
||||||
q5 := q4 / 1000
|
q5 := q4 / 1000
|
||||||
if q5 == 0 {
|
if q5 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q4], n)
|
n = writeFirstBuf(stream.buf, digits[q4], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r4], n)
|
writeBuf(stream.buf, digits[r4], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n+3)
|
writeBuf(stream.buf, digits[r3], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+6)
|
writeBuf(stream.buf, digits[r2], n+6)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+9)
|
writeBuf(stream.buf, digits[r1], n+9)
|
||||||
stream.n = n + 12
|
stream.n = n + 12
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r5 := q4 - q5*1000
|
r5 := q4 - q5*1000
|
||||||
q6 := q5 / 1000
|
q6 := q5 / 1000
|
||||||
if q6 == 0 {
|
if q6 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q5], n)
|
n = writeFirstBuf(stream.buf, digits[q5], n)
|
||||||
} else {
|
} else {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q6], n)
|
n = writeFirstBuf(stream.buf, digits[q6], n)
|
||||||
r6 := q5 - q6*1000
|
r6 := q5 - q6*1000
|
||||||
writeBuf(stream.buf, _DIGITS[r6], n)
|
writeBuf(stream.buf, digits[r6], n)
|
||||||
n += 3
|
n += 3
|
||||||
}
|
}
|
||||||
writeBuf(stream.buf, _DIGITS[r5], n)
|
writeBuf(stream.buf, digits[r5], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r4], n+3)
|
writeBuf(stream.buf, digits[r4], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n+6)
|
writeBuf(stream.buf, digits[r3], n+6)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+9)
|
writeBuf(stream.buf, digits[r2], n+9)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+12)
|
writeBuf(stream.buf, digits[r1], n+12)
|
||||||
stream.n = n + 15
|
stream.n = n + 15
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteInt64 write int64 to stream
|
||||||
func (stream *Stream) WriteInt64(nval int64) {
|
func (stream *Stream) WriteInt64(nval int64) {
|
||||||
stream.ensure(20)
|
stream.ensure(20)
|
||||||
n := stream.n
|
n := stream.n
|
||||||
@ -241,70 +249,72 @@ func (stream *Stream) WriteInt64(nval int64) {
|
|||||||
}
|
}
|
||||||
q1 := val / 1000
|
q1 := val / 1000
|
||||||
if q1 == 0 {
|
if q1 == 0 {
|
||||||
stream.n = writeFirstBuf(stream.buf, _DIGITS[val], n)
|
stream.n = writeFirstBuf(stream.buf, digits[val], n)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r1 := val - q1*1000
|
r1 := val - q1*1000
|
||||||
q2 := q1 / 1000
|
q2 := q1 / 1000
|
||||||
if q2 == 0 {
|
if q2 == 0 {
|
||||||
n := writeFirstBuf(stream.buf, _DIGITS[q1], n)
|
n := writeFirstBuf(stream.buf, digits[q1], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n)
|
writeBuf(stream.buf, digits[r1], n)
|
||||||
stream.n = n + 3
|
stream.n = n + 3
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r2 := q1 - q2*1000
|
r2 := q1 - q2*1000
|
||||||
q3 := q2 / 1000
|
q3 := q2 / 1000
|
||||||
if q3 == 0 {
|
if q3 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q2], n)
|
n = writeFirstBuf(stream.buf, digits[q2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n)
|
writeBuf(stream.buf, digits[r2], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+3)
|
writeBuf(stream.buf, digits[r1], n+3)
|
||||||
stream.n = n + 6
|
stream.n = n + 6
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r3 := q2 - q3*1000
|
r3 := q2 - q3*1000
|
||||||
q4 := q3 / 1000
|
q4 := q3 / 1000
|
||||||
if q4 == 0 {
|
if q4 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q3], n)
|
n = writeFirstBuf(stream.buf, digits[q3], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n)
|
writeBuf(stream.buf, digits[r3], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+3)
|
writeBuf(stream.buf, digits[r2], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+6)
|
writeBuf(stream.buf, digits[r1], n+6)
|
||||||
stream.n = n + 9
|
stream.n = n + 9
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r4 := q3 - q4*1000
|
r4 := q3 - q4*1000
|
||||||
q5 := q4 / 1000
|
q5 := q4 / 1000
|
||||||
if q5 == 0 {
|
if q5 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q4], n)
|
n = writeFirstBuf(stream.buf, digits[q4], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r4], n)
|
writeBuf(stream.buf, digits[r4], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n+3)
|
writeBuf(stream.buf, digits[r3], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+6)
|
writeBuf(stream.buf, digits[r2], n+6)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+9)
|
writeBuf(stream.buf, digits[r1], n+9)
|
||||||
stream.n = n + 12
|
stream.n = n + 12
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r5 := q4 - q5*1000
|
r5 := q4 - q5*1000
|
||||||
q6 := q5 / 1000
|
q6 := q5 / 1000
|
||||||
if q6 == 0 {
|
if q6 == 0 {
|
||||||
n = writeFirstBuf(stream.buf, _DIGITS[q5], n)
|
n = writeFirstBuf(stream.buf, digits[q5], n)
|
||||||
} else {
|
} else {
|
||||||
stream.buf[n] = byte(q6 + '0')
|
stream.buf[n] = byte(q6 + '0')
|
||||||
n++
|
n++
|
||||||
r6 := q5 - q6*1000
|
r6 := q5 - q6*1000
|
||||||
writeBuf(stream.buf, _DIGITS[r6], n)
|
writeBuf(stream.buf, digits[r6], n)
|
||||||
n += 3
|
n += 3
|
||||||
}
|
}
|
||||||
writeBuf(stream.buf, _DIGITS[r5], n)
|
writeBuf(stream.buf, digits[r5], n)
|
||||||
writeBuf(stream.buf, _DIGITS[r4], n+3)
|
writeBuf(stream.buf, digits[r4], n+3)
|
||||||
writeBuf(stream.buf, _DIGITS[r3], n+6)
|
writeBuf(stream.buf, digits[r3], n+6)
|
||||||
writeBuf(stream.buf, _DIGITS[r2], n+9)
|
writeBuf(stream.buf, digits[r2], n+9)
|
||||||
writeBuf(stream.buf, _DIGITS[r1], n+12)
|
writeBuf(stream.buf, digits[r1], n+12)
|
||||||
stream.n = n + 15
|
stream.n = n + 15
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteInt write int to stream
|
||||||
func (stream *Stream) WriteInt(val int) {
|
func (stream *Stream) WriteInt(val int) {
|
||||||
stream.WriteInt64(int64(val))
|
stream.WriteInt64(int64(val))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteUint write uint to stream
|
||||||
func (stream *Stream) WriteUint(val uint) {
|
func (stream *Stream) WriteUint(val uint) {
|
||||||
stream.WriteUint64(uint64(val))
|
stream.WriteUint64(uint64(val))
|
||||||
}
|
}
|
||||||
|
@ -217,7 +217,8 @@ var safeSet = [utf8.RuneSelf]bool{
|
|||||||
|
|
||||||
var hex = "0123456789abcdef"
|
var hex = "0123456789abcdef"
|
||||||
|
|
||||||
func (stream *Stream) WriteStringWithHtmlEscaped(s string) {
|
// WriteStringWithHTMLEscaped write string to stream with html special characters escaped
|
||||||
|
func (stream *Stream) WriteStringWithHTMLEscaped(s string) {
|
||||||
stream.ensure(32)
|
stream.ensure(32)
|
||||||
valLen := len(s)
|
valLen := len(s)
|
||||||
toWriteLen := valLen
|
toWriteLen := valLen
|
||||||
@ -232,7 +233,7 @@ func (stream *Stream) WriteStringWithHtmlEscaped(s string) {
|
|||||||
i := 0
|
i := 0
|
||||||
for ; i < toWriteLen; i++ {
|
for ; i < toWriteLen; i++ {
|
||||||
c := s[i]
|
c := s[i]
|
||||||
if c <= utf8.RuneSelf && htmlSafeSet[c] {
|
if c < utf8.RuneSelf && htmlSafeSet[c] {
|
||||||
stream.buf[n] = c
|
stream.buf[n] = c
|
||||||
n++
|
n++
|
||||||
} else {
|
} else {
|
||||||
@ -246,47 +247,15 @@ func (stream *Stream) WriteStringWithHtmlEscaped(s string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
stream.n = n
|
stream.n = n
|
||||||
writeStringSlowPath(stream, htmlSafeSet, i, s, valLen)
|
writeStringSlowPathWithHTMLEscaped(stream, i, s, valLen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (stream *Stream) WriteString(s string) {
|
func writeStringSlowPathWithHTMLEscaped(stream *Stream, i int, s string, valLen int) {
|
||||||
stream.ensure(32)
|
|
||||||
valLen := len(s)
|
|
||||||
toWriteLen := valLen
|
|
||||||
bufLengthMinusTwo := len(stream.buf) - 2 // make room for the quotes
|
|
||||||
if stream.n+toWriteLen > bufLengthMinusTwo {
|
|
||||||
toWriteLen = bufLengthMinusTwo - stream.n
|
|
||||||
}
|
|
||||||
n := stream.n
|
|
||||||
stream.buf[n] = '"'
|
|
||||||
n++
|
|
||||||
// write string, the fast path, without utf8 and escape support
|
|
||||||
i := 0
|
|
||||||
for ; i < toWriteLen; i++ {
|
|
||||||
c := s[i]
|
|
||||||
if c > 31 && c != '"' && c != '\\' {
|
|
||||||
stream.buf[n] = c
|
|
||||||
n++
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if i == valLen {
|
|
||||||
stream.buf[n] = '"'
|
|
||||||
n++
|
|
||||||
stream.n = n
|
|
||||||
return
|
|
||||||
}
|
|
||||||
stream.n = n
|
|
||||||
writeStringSlowPath(stream, safeSet, i, s, valLen)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeStringSlowPath(stream *Stream, safeSet [utf8.RuneSelf]bool, i int, s string, valLen int) {
|
|
||||||
start := i
|
start := i
|
||||||
// for the remaining parts, we process them char by char
|
// for the remaining parts, we process them char by char
|
||||||
for ; i < valLen; i++ {
|
for i < valLen {
|
||||||
if b := s[i]; b < utf8.RuneSelf {
|
if b := s[i]; b < utf8.RuneSelf {
|
||||||
if safeSet[b] {
|
if htmlSafeSet[b] {
|
||||||
i++
|
i++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -321,7 +290,7 @@ func writeStringSlowPath(stream *Stream, safeSet [utf8.RuneSelf]bool, i int, s s
|
|||||||
stream.WriteRaw(s[start:i])
|
stream.WriteRaw(s[start:i])
|
||||||
}
|
}
|
||||||
stream.WriteRaw(`\ufffd`)
|
stream.WriteRaw(`\ufffd`)
|
||||||
i += size
|
i++
|
||||||
start = i
|
start = i
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -349,3 +318,79 @@ func writeStringSlowPath(stream *Stream, safeSet [utf8.RuneSelf]bool, i int, s s
|
|||||||
}
|
}
|
||||||
stream.writeByte('"')
|
stream.writeByte('"')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteString write string to stream without html escape
|
||||||
|
func (stream *Stream) WriteString(s string) {
|
||||||
|
stream.ensure(32)
|
||||||
|
valLen := len(s)
|
||||||
|
toWriteLen := valLen
|
||||||
|
bufLengthMinusTwo := len(stream.buf) - 2 // make room for the quotes
|
||||||
|
if stream.n+toWriteLen > bufLengthMinusTwo {
|
||||||
|
toWriteLen = bufLengthMinusTwo - stream.n
|
||||||
|
}
|
||||||
|
n := stream.n
|
||||||
|
stream.buf[n] = '"'
|
||||||
|
n++
|
||||||
|
// write string, the fast path, without utf8 and escape support
|
||||||
|
i := 0
|
||||||
|
for ; i < toWriteLen; i++ {
|
||||||
|
c := s[i]
|
||||||
|
if c > 31 && c != '"' && c != '\\' {
|
||||||
|
stream.buf[n] = c
|
||||||
|
n++
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i == valLen {
|
||||||
|
stream.buf[n] = '"'
|
||||||
|
n++
|
||||||
|
stream.n = n
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stream.n = n
|
||||||
|
writeStringSlowPath(stream, i, s, valLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeStringSlowPath(stream *Stream, i int, s string, valLen int) {
|
||||||
|
start := i
|
||||||
|
// for the remaining parts, we process them char by char
|
||||||
|
for i < valLen {
|
||||||
|
if b := s[i]; b < utf8.RuneSelf {
|
||||||
|
if safeSet[b] {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if start < i {
|
||||||
|
stream.WriteRaw(s[start:i])
|
||||||
|
}
|
||||||
|
switch b {
|
||||||
|
case '\\', '"':
|
||||||
|
stream.writeTwoBytes('\\', b)
|
||||||
|
case '\n':
|
||||||
|
stream.writeTwoBytes('\\', 'n')
|
||||||
|
case '\r':
|
||||||
|
stream.writeTwoBytes('\\', 'r')
|
||||||
|
case '\t':
|
||||||
|
stream.writeTwoBytes('\\', 't')
|
||||||
|
default:
|
||||||
|
// This encodes bytes < 0x20 except for \t, \n and \r.
|
||||||
|
// If escapeHTML is set, it also escapes <, >, and &
|
||||||
|
// because they can lead to security holes when
|
||||||
|
// user-controlled strings are rendered into JSON
|
||||||
|
// and served to some browsers.
|
||||||
|
stream.WriteRaw(`\u00`)
|
||||||
|
stream.writeTwoBytes(hex[b>>4], hex[b&0xF])
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
start = i
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if start < len(s) {
|
||||||
|
stream.WriteRaw(s[start:])
|
||||||
|
}
|
||||||
|
stream.writeByte('"')
|
||||||
|
}
|
||||||
|
7
fuzzy_mode_convert_table.md
Normal file
7
fuzzy_mode_convert_table.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
| json type \ dest type | bool | int | uint | float |string|
|
||||||
|
| --- | --- | --- | --- |--|--|
|
||||||
|
| number | positive => true <br/> negative => true <br/> zero => false| 23.2 => 23 <br/> -32.1 => -32| 12.1 => 12 <br/> -12.1 => 0|as normal|same as origin|
|
||||||
|
| string | empty string => false <br/> string "0" => false <br/> other strings => true | "123.32" => 123 <br/> "-123.4" => -123 <br/> "123.23xxxw" => 123 <br/> "abcde12" => 0 <br/> "-32.1" => -32| 13.2 => 13 <br/> -1.1 => 0 |12.1 => 12.1 <br/> -12.3 => -12.3<br/> 12.4xxa => 12.4 <br/> +1.1e2 =>110 |same as origin|
|
||||||
|
| bool | true => true <br/> false => false| true => 1 <br/> false => 0 | true => 1 <br/> false => 0 |true => 1 <br/>false => 0|true => "true" <br/> false => "false"|
|
||||||
|
| object | true | 0 | 0 |0|originnal json|
|
||||||
|
| array | empty array => false <br/> nonempty array => true| [] => 0 <br/> [1,2] => 1 | [] => 0 <br/> [1,2] => 1 |[] => 0<br/>[1,2] => 1|original json|
|
18
jsoniter.go
Normal file
18
jsoniter.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
// Package jsoniter implements encoding and decoding of JSON as defined in
|
||||||
|
// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json.
|
||||||
|
// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter
|
||||||
|
// and variable type declarations (if any).
|
||||||
|
// jsoniter interfaces gives 100% compatibility with code using standard lib.
|
||||||
|
//
|
||||||
|
// "JSON and Go"
|
||||||
|
// (https://golang.org/doc/articles/json_and_go.html)
|
||||||
|
// gives a description of how Marshal/Unmarshal operate
|
||||||
|
// between arbitrary or predefined json objects and bytes,
|
||||||
|
// and it applies to jsoniter.Marshal/Unmarshal as well.
|
||||||
|
//
|
||||||
|
// Besides, jsoniter.Iterator provides a different set of interfaces
|
||||||
|
// iterating given bytes/string/reader
|
||||||
|
// and yielding parsed elements one by one.
|
||||||
|
// This set of interfaces reads input as required and gives
|
||||||
|
// better performance.
|
||||||
|
package jsoniter
|
45
jsoniter_1dot8_only_test.go
Normal file
45
jsoniter_1dot8_only_test.go
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_new_encoder(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
buf1 := &bytes.Buffer{}
|
||||||
|
encoder1 := json.NewEncoder(buf1)
|
||||||
|
encoder1.SetEscapeHTML(false)
|
||||||
|
encoder1.Encode([]int{1})
|
||||||
|
should.Equal("[1]\n", buf1.String())
|
||||||
|
buf2 := &bytes.Buffer{}
|
||||||
|
encoder2 := NewEncoder(buf2)
|
||||||
|
encoder2.SetEscapeHTML(false)
|
||||||
|
encoder2.Encode([]int{1})
|
||||||
|
should.Equal("[1]", buf2.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_string_encode_with_std_without_html_escape(t *testing.T) {
|
||||||
|
api := Config{EscapeHTML: false}.Froze()
|
||||||
|
should := require.New(t)
|
||||||
|
for i := 0; i < utf8.RuneSelf; i++ {
|
||||||
|
input := string([]byte{byte(i)})
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
encoder := json.NewEncoder(buf)
|
||||||
|
encoder.SetEscapeHTML(false)
|
||||||
|
err := encoder.Encode(input)
|
||||||
|
should.Nil(err)
|
||||||
|
stdOutput := buf.String()
|
||||||
|
stdOutput = stdOutput[:len(stdOutput)-1]
|
||||||
|
jsoniterOutputBytes, err := api.Marshal(input)
|
||||||
|
should.Nil(err)
|
||||||
|
jsoniterOutput := string(jsoniterOutputBytes)
|
||||||
|
should.Equal(stdOutput, jsoniterOutput)
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,7 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@ -33,20 +33,6 @@ func Test_new_decoder(t *testing.T) {
|
|||||||
should.False(decoder2.More())
|
should.False(decoder2.More())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_new_encoder(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
buf1 := &bytes.Buffer{}
|
|
||||||
encoder1 := json.NewEncoder(buf1)
|
|
||||||
encoder1.SetEscapeHTML(false)
|
|
||||||
encoder1.Encode([]int{1})
|
|
||||||
should.Equal("[1]\n", buf1.String())
|
|
||||||
buf2 := &bytes.Buffer{}
|
|
||||||
encoder2 := NewEncoder(buf2)
|
|
||||||
encoder2.SetEscapeHTML(false)
|
|
||||||
encoder2.Encode([]int{1})
|
|
||||||
should.Equal("[1]", buf2.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_use_number(t *testing.T) {
|
func Test_use_number(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
decoder1 := json.NewDecoder(bytes.NewBufferString(`123`))
|
decoder1 := json.NewDecoder(bytes.NewBufferString(`123`))
|
||||||
@ -68,3 +54,31 @@ func Test_use_number_for_unmarshal(t *testing.T) {
|
|||||||
should.Nil(api.UnmarshalFromString("123", &obj))
|
should.Nil(api.UnmarshalFromString("123", &obj))
|
||||||
should.Equal(json.Number("123"), obj)
|
should.Equal(json.Number("123"), obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_marshal_indent(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
obj := struct {
|
||||||
|
F1 int
|
||||||
|
F2 []int
|
||||||
|
}{1, []int{2, 3, 4}}
|
||||||
|
output, err := json.MarshalIndent(obj, "", " ")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output))
|
||||||
|
output, err = MarshalIndent(obj, "", " ")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_marshal_indent_map(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
obj := map[int]int{1: 2}
|
||||||
|
output, err := json.MarshalIndent(obj, "", " ")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{\n \"1\": 2\n}", string(output))
|
||||||
|
output, err = MarshalIndent(obj, "", " ")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{\n \"1\": 2\n}", string(output))
|
||||||
|
output, err = ConfigCompatibleWithStandardLibrary.MarshalIndent(obj, "", " ")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{\n \"1\": 2\n}", string(output))
|
||||||
|
}
|
||||||
|
62
jsoniter_alias_test.go
Normal file
62
jsoniter_alias_test.go
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_alias(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type myint int
|
||||||
|
type myint8 int8
|
||||||
|
type myint16 int16
|
||||||
|
type myint32 int32
|
||||||
|
type myint64 int64
|
||||||
|
type myuint uint
|
||||||
|
type myuint8 uint8
|
||||||
|
type myuint16 uint16
|
||||||
|
type myuint32 uint32
|
||||||
|
type myuint64 uint64
|
||||||
|
type myfloat32 float32
|
||||||
|
type myfloat64 float64
|
||||||
|
type mystring string
|
||||||
|
type mybool bool
|
||||||
|
type myuintptr uintptr
|
||||||
|
var a struct {
|
||||||
|
A myint8 `json:"a"`
|
||||||
|
B myint16 `json:"stream"`
|
||||||
|
C myint32 `json:"c"`
|
||||||
|
D myint64 `json:"d"`
|
||||||
|
E myuint8 `json:"e"`
|
||||||
|
F myuint16 `json:"f"`
|
||||||
|
G myuint32 `json:"g"`
|
||||||
|
H myuint64 `json:"h"`
|
||||||
|
I myfloat32 `json:"i"`
|
||||||
|
J myfloat64 `json:"j"`
|
||||||
|
K mystring `json:"k"`
|
||||||
|
L myint `json:"l"`
|
||||||
|
M myuint `json:"m"`
|
||||||
|
N mybool `json:"n"`
|
||||||
|
O myuintptr `json:"o"`
|
||||||
|
}
|
||||||
|
|
||||||
|
should.Nil(UnmarshalFromString(`{"a" : 1, "stream" : 1, "c": 1, "d" : 1, "e" : 1, "f" : 1, "g" : 1, "h": 1, "i" : 1, "j" : 1, "k" :"xxxx", "l" : 1, "m":1, "n": true, "o" : 1}`, &a))
|
||||||
|
should.Equal(myfloat32(1), a.I)
|
||||||
|
should.Equal(myfloat64(1), a.J)
|
||||||
|
should.Equal(myint8(1), a.A)
|
||||||
|
should.Equal(myint16(1), a.B)
|
||||||
|
should.Equal(myint32(1), a.C)
|
||||||
|
should.Equal(myint64(1), a.D)
|
||||||
|
should.Equal(myuint8(1), a.E)
|
||||||
|
should.Equal(myuint16(1), a.F)
|
||||||
|
should.Equal(myuint32(1), a.G)
|
||||||
|
should.Equal(myuint64(1), a.H)
|
||||||
|
should.Equal(mystring("xxxx"), a.K)
|
||||||
|
should.Equal(mybool(true), a.N)
|
||||||
|
should.Equal(myuintptr(1), a.O)
|
||||||
|
b, err := Marshal(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"a":1,"stream":1,"c":1,"d":1,"e":1,"f":1,"g":1,"h":1,"i":1,"j":1,"k":"xxxx","l":1,"m":1,"n":true,"o":1}`, string(b))
|
||||||
|
|
||||||
|
}
|
@ -1,17 +1,18 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_empty_array_as_any(t *testing.T) {
|
func Test_read_empty_array_as_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("[]"))
|
any := Get([]byte("[]"))
|
||||||
should.Equal(Array, any.Get().ValueType())
|
should.Equal(ArrayValue, any.Get().ValueType())
|
||||||
should.Equal(Invalid, any.Get(0.3).ValueType())
|
should.Equal(InvalidValue, any.Get(0.3).ValueType())
|
||||||
should.Equal(0, any.Size())
|
should.Equal(0, any.Size())
|
||||||
should.Equal(Array, any.ValueType())
|
should.Equal(ArrayValue, any.ValueType())
|
||||||
should.Nil(any.LastError())
|
should.Nil(any.LastError())
|
||||||
should.Equal(0, any.ToInt())
|
should.Equal(0, any.ToInt())
|
||||||
should.Equal(int32(0), any.ToInt32())
|
should.Equal(int32(0), any.ToInt32())
|
||||||
@ -36,7 +37,6 @@ func Test_read_two_element_array_as_any(t *testing.T) {
|
|||||||
should.Equal(2, any.Size())
|
should.Equal(2, any.Size())
|
||||||
should.True(any.ToBool())
|
should.True(any.ToBool())
|
||||||
should.Equal(1, any.ToInt())
|
should.Equal(1, any.ToInt())
|
||||||
should.Equal(1, any.GetArray()[0].ToInt())
|
|
||||||
should.Equal([]interface{}{float64(1), float64(2)}, any.GetInterface())
|
should.Equal([]interface{}{float64(1), float64(2)}, any.GetInterface())
|
||||||
stream := NewStream(ConfigDefault, nil, 32)
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
any.WriteTo(stream)
|
any.WriteTo(stream)
|
||||||
@ -46,10 +46,36 @@ func Test_read_two_element_array_as_any(t *testing.T) {
|
|||||||
should.Equal([]int{1, 2}, arr)
|
should.Equal([]int{1, 2}, arr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_wrap_array(t *testing.T) {
|
func Test_wrap_array_and_convert_to_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Wrap([]int{1, 2, 3})
|
any := Wrap([]int{1, 2, 3})
|
||||||
|
any2 := Wrap([]int{})
|
||||||
|
|
||||||
should.Equal("[1,2,3]", any.ToString())
|
should.Equal("[1,2,3]", any.ToString())
|
||||||
|
should.True(any.ToBool())
|
||||||
|
should.False(any2.ToBool())
|
||||||
|
|
||||||
|
should.Equal(1, any.ToInt())
|
||||||
|
should.Equal(0, any2.ToInt())
|
||||||
|
should.Equal(int32(1), any.ToInt32())
|
||||||
|
should.Equal(int32(0), any2.ToInt32())
|
||||||
|
should.Equal(int64(1), any.ToInt64())
|
||||||
|
should.Equal(int64(0), any2.ToInt64())
|
||||||
|
should.Equal(uint(1), any.ToUint())
|
||||||
|
should.Equal(uint(0), any2.ToUint())
|
||||||
|
should.Equal(uint32(1), any.ToUint32())
|
||||||
|
should.Equal(uint32(0), any2.ToUint32())
|
||||||
|
should.Equal(uint64(1), any.ToUint64())
|
||||||
|
should.Equal(uint64(0), any2.ToUint64())
|
||||||
|
should.Equal(float32(1), any.ToFloat32())
|
||||||
|
should.Equal(float32(0), any2.ToFloat32())
|
||||||
|
should.Equal(float64(1), any.ToFloat64())
|
||||||
|
should.Equal(float64(0), any2.ToFloat64())
|
||||||
|
should.Equal(3, any.Size())
|
||||||
|
should.Equal(0, any2.Size())
|
||||||
|
|
||||||
|
var i interface{} = []int{1, 2, 3}
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_array_lazy_any_get(t *testing.T) {
|
func Test_array_lazy_any_get(t *testing.T) {
|
||||||
@ -75,7 +101,7 @@ func Test_array_wrapper_any_get_all(t *testing.T) {
|
|||||||
{5, 6},
|
{5, 6},
|
||||||
})
|
})
|
||||||
should.Equal("[1,3,5]", any.Get('*', 0).ToString())
|
should.Equal("[1,3,5]", any.Get('*', 0).ToString())
|
||||||
should.Equal(Array, any.ValueType())
|
should.Equal(ArrayValue, any.ValueType())
|
||||||
should.True(any.ToBool())
|
should.True(any.ToBool())
|
||||||
should.Equal(1, any.Get(0, 0).ToInt())
|
should.Equal(1, any.Get(0, 0).ToInt())
|
||||||
}
|
}
|
||||||
@ -83,14 +109,14 @@ func Test_array_wrapper_any_get_all(t *testing.T) {
|
|||||||
func Test_array_lazy_any_get_invalid(t *testing.T) {
|
func Test_array_lazy_any_get_invalid(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("[]"))
|
any := Get([]byte("[]"))
|
||||||
should.Equal(Invalid, any.Get(1, 1).ValueType())
|
should.Equal(InvalidValue, any.Get(1, 1).ValueType())
|
||||||
should.NotNil(any.Get(1, 1).LastError())
|
should.NotNil(any.Get(1, 1).LastError())
|
||||||
should.Equal(Invalid, any.Get("1").ValueType())
|
should.Equal(InvalidValue, any.Get("1").ValueType())
|
||||||
should.NotNil(any.Get("1").LastError())
|
should.NotNil(any.Get("1").LastError())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_invalid_array(t *testing.T) {
|
func Test_invalid_array(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("["), 0)
|
any := Get([]byte("["), 0)
|
||||||
should.Equal(Invalid, any.ValueType())
|
should.Equal(InvalidValue, any.ValueType())
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,64 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var boolConvertMap = map[string]bool{
|
||||||
|
"null": false,
|
||||||
|
"true": true,
|
||||||
|
"false": false,
|
||||||
|
|
||||||
|
`"true"`: true,
|
||||||
|
`"false"`: true,
|
||||||
|
|
||||||
|
"123": true,
|
||||||
|
`"123"`: true,
|
||||||
|
"0": false,
|
||||||
|
`"0"`: false,
|
||||||
|
"-1": true,
|
||||||
|
`"-1"`: true,
|
||||||
|
|
||||||
|
"1.1": true,
|
||||||
|
"0.0": false,
|
||||||
|
"-1.1": true,
|
||||||
|
`""`: false,
|
||||||
|
"[1,2]": true,
|
||||||
|
"[]": false,
|
||||||
|
"{}": true,
|
||||||
|
`{"abc":1}`: true,
|
||||||
|
}
|
||||||
|
|
||||||
func Test_read_bool_as_any(t *testing.T) {
|
func Test_read_bool_as_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("true"))
|
|
||||||
should.True(any.ToBool())
|
var any Any
|
||||||
|
for k, v := range boolConvertMap {
|
||||||
|
any = Get([]byte(k))
|
||||||
|
if v {
|
||||||
|
should.True(any.ToBool(), fmt.Sprintf("origin val is %v", k))
|
||||||
|
} else {
|
||||||
|
should.False(any.ToBool(), fmt.Sprintf("origin val is %v", k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_write_bool_to_stream(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := Get([]byte("true"))
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("true", string(stream.Buffer()))
|
||||||
|
should.Equal(any.ValueType(), BoolValue)
|
||||||
|
|
||||||
|
any = Get([]byte("false"))
|
||||||
|
stream = NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("false", string(stream.Buffer()))
|
||||||
|
|
||||||
|
should.Equal(any.ValueType(), BoolValue)
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,102 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_float_as_any(t *testing.T) {
|
var floatConvertMap = map[string]float64{
|
||||||
should := require.New(t)
|
"null": 0,
|
||||||
any := Get([]byte("12.3"))
|
"true": 1,
|
||||||
should.Equal(float64(12.3), any.ToFloat64())
|
"false": 0,
|
||||||
should.Equal("12.3", any.ToString())
|
|
||||||
should.True(any.ToBool())
|
`"true"`: 0,
|
||||||
|
`"false"`: 0,
|
||||||
|
|
||||||
|
"1e1": 10,
|
||||||
|
"1e+1": 10,
|
||||||
|
"1e-1": .1,
|
||||||
|
"1E1": 10,
|
||||||
|
"1E+1": 10,
|
||||||
|
"1E-1": .1,
|
||||||
|
|
||||||
|
"-1e1": -10,
|
||||||
|
"-1e+1": -10,
|
||||||
|
"-1e-1": -.1,
|
||||||
|
"-1E1": -10,
|
||||||
|
"-1E+1": -10,
|
||||||
|
"-1E-1": -.1,
|
||||||
|
|
||||||
|
`"1e1"`: 10,
|
||||||
|
`"1e+1"`: 10,
|
||||||
|
`"1e-1"`: .1,
|
||||||
|
`"1E1"`: 10,
|
||||||
|
`"1E+1"`: 10,
|
||||||
|
`"1E-1"`: .1,
|
||||||
|
|
||||||
|
`"-1e1"`: -10,
|
||||||
|
`"-1e+1"`: -10,
|
||||||
|
`"-1e-1"`: -.1,
|
||||||
|
`"-1E1"`: -10,
|
||||||
|
`"-1E+1"`: -10,
|
||||||
|
`"-1E-1"`: -.1,
|
||||||
|
|
||||||
|
"123": 123,
|
||||||
|
`"123true"`: 123,
|
||||||
|
`"+"`: 0,
|
||||||
|
`"-"`: 0,
|
||||||
|
|
||||||
|
`"-123true"`: -123,
|
||||||
|
`"-99.9true"`: -99.9,
|
||||||
|
"0": 0,
|
||||||
|
`"0"`: 0,
|
||||||
|
"-1": -1,
|
||||||
|
|
||||||
|
"1.1": 1.1,
|
||||||
|
"0.0": 0,
|
||||||
|
"-1.1": -1.1,
|
||||||
|
`"+1.1"`: 1.1,
|
||||||
|
`""`: 0,
|
||||||
|
"[1,2]": 1,
|
||||||
|
"[]": 0,
|
||||||
|
"{}": 0,
|
||||||
|
`{"abc":1}`: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_any_to_float(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
for k, v := range floatConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(float64(v), any.ToFloat64(), "the original val is "+k)
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range floatConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(float32(v), any.ToFloat32(), "the original val is "+k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_float_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := WrapFloat64(12.3)
|
||||||
|
anyFloat64 := float64(12.3)
|
||||||
|
//negaAnyFloat64 := float64(-1.1)
|
||||||
|
any2 := WrapFloat64(-1.1)
|
||||||
|
should.Equal(float64(12.3), any.ToFloat64())
|
||||||
|
//should.Equal("12.3", any.ToString())
|
||||||
|
should.True(any.ToBool())
|
||||||
|
should.Equal(float32(anyFloat64), any.ToFloat32())
|
||||||
|
should.Equal(int(anyFloat64), any.ToInt())
|
||||||
|
should.Equal(int32(anyFloat64), any.ToInt32())
|
||||||
|
should.Equal(int64(anyFloat64), any.ToInt64())
|
||||||
|
should.Equal(uint(anyFloat64), any.ToUint())
|
||||||
|
should.Equal(uint32(anyFloat64), any.ToUint32())
|
||||||
|
should.Equal(uint64(anyFloat64), any.ToUint64())
|
||||||
|
should.Equal(uint(0), any2.ToUint())
|
||||||
|
should.Equal(uint32(0), any2.ToUint32())
|
||||||
|
should.Equal(uint64(0), any2.ToUint64())
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
|
||||||
|
should.Equal("1.23E+01", any.ToString())
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,197 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"fmt"
|
||||||
"io"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_int64_as_any(t *testing.T) {
|
var intConvertMap = map[string]int{
|
||||||
|
"null": 0,
|
||||||
|
"321.1": 321,
|
||||||
|
"-321.1": -321,
|
||||||
|
`"1.1"`: 1,
|
||||||
|
`"-321.1"`: -321,
|
||||||
|
"0.0": 0,
|
||||||
|
"0": 0,
|
||||||
|
`"0"`: 0,
|
||||||
|
`"0.0"`: 0,
|
||||||
|
"-1.1": -1,
|
||||||
|
"true": 1,
|
||||||
|
"false": 0,
|
||||||
|
`"true"`: 0,
|
||||||
|
`"false"`: 0,
|
||||||
|
`"true123"`: 0,
|
||||||
|
`"123true"`: 123,
|
||||||
|
`"-123true"`: -123,
|
||||||
|
`"1.2332e6"`: 1,
|
||||||
|
`""`: 0,
|
||||||
|
"+": 0,
|
||||||
|
"-": 0,
|
||||||
|
"[]": 0,
|
||||||
|
"[1,2]": 1,
|
||||||
|
`["1","2"]`: 1,
|
||||||
|
// object in php cannot convert to int
|
||||||
|
"{}": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_any_to_int(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("1234"))
|
|
||||||
should.Equal(1234, any.ToInt())
|
// int
|
||||||
should.Equal(io.EOF, any.LastError())
|
for k, v := range intConvertMap {
|
||||||
should.Equal("1234", any.ToString())
|
any := Get([]byte(k))
|
||||||
should.True(any.ToBool())
|
should.Equal(v, any.ToInt(), fmt.Sprintf("origin val %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
// int32
|
||||||
|
for k, v := range intConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(int32(v), any.ToInt32(), fmt.Sprintf("original val is %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
// int64
|
||||||
|
for k, v := range intConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(int64(v), any.ToInt64(), fmt.Sprintf("original val is %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
var uintConvertMap = map[string]int{
|
||||||
|
"null": 0,
|
||||||
|
"321.1": 321,
|
||||||
|
`"1.1"`: 1,
|
||||||
|
`"-123.1"`: 0,
|
||||||
|
"0.0": 0,
|
||||||
|
"0": 0,
|
||||||
|
`"0"`: 0,
|
||||||
|
`"0.0"`: 0,
|
||||||
|
`"00.0"`: 0,
|
||||||
|
"true": 1,
|
||||||
|
"false": 0,
|
||||||
|
`"true"`: 0,
|
||||||
|
`"false"`: 0,
|
||||||
|
`"true123"`: 0,
|
||||||
|
`"+1"`: 1,
|
||||||
|
`"123true"`: 123,
|
||||||
|
`"-123true"`: 0,
|
||||||
|
`"1.2332e6"`: 1,
|
||||||
|
`""`: 0,
|
||||||
|
"+": 0,
|
||||||
|
"-": 0,
|
||||||
|
".": 0,
|
||||||
|
"[]": 0,
|
||||||
|
"[1,2]": 1,
|
||||||
|
"{}": 0,
|
||||||
|
"{1,2}": 0,
|
||||||
|
"-1.1": 0,
|
||||||
|
"-321.1": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_any_to_uint(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
for k, v := range uintConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(uint64(v), any.ToUint64(), fmt.Sprintf("origin val %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range uintConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range uintConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(uint(v), any.ToUint(), fmt.Sprintf("origin val %v", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_int64_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := WrapInt64(12345)
|
||||||
|
should.Equal(12345, any.ToInt())
|
||||||
|
should.Equal(int32(12345), any.ToInt32())
|
||||||
|
should.Equal(int64(12345), any.ToInt64())
|
||||||
|
should.Equal(uint(12345), any.ToUint())
|
||||||
|
should.Equal(uint32(12345), any.ToUint32())
|
||||||
|
should.Equal(uint64(12345), any.ToUint64())
|
||||||
|
should.Equal(float32(12345), any.ToFloat32())
|
||||||
|
should.Equal(float64(12345), any.ToFloat64())
|
||||||
|
should.Equal("12345", any.ToString())
|
||||||
|
should.Equal(true, any.ToBool())
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("12345", string(stream.Buffer()))
|
||||||
|
}
|
||||||
|
func Test_read_int32_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := WrapInt32(12345)
|
||||||
|
should.Equal(12345, any.ToInt())
|
||||||
|
should.Equal(int32(12345), any.ToInt32())
|
||||||
|
should.Equal(int64(12345), any.ToInt64())
|
||||||
|
should.Equal(uint(12345), any.ToUint())
|
||||||
|
should.Equal(uint32(12345), any.ToUint32())
|
||||||
|
should.Equal(uint64(12345), any.ToUint64())
|
||||||
|
should.Equal(float32(12345), any.ToFloat32())
|
||||||
|
should.Equal(float64(12345), any.ToFloat64())
|
||||||
|
should.Equal("12345", any.ToString())
|
||||||
|
should.Equal(true, any.ToBool())
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("12345", string(stream.Buffer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_uint32_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := WrapUint32(12345)
|
||||||
|
should.Equal(12345, any.ToInt())
|
||||||
|
should.Equal(int32(12345), any.ToInt32())
|
||||||
|
should.Equal(int64(12345), any.ToInt64())
|
||||||
|
should.Equal(uint(12345), any.ToUint())
|
||||||
|
should.Equal(uint32(12345), any.ToUint32())
|
||||||
|
should.Equal(uint64(12345), any.ToUint64())
|
||||||
|
should.Equal(float32(12345), any.ToFloat32())
|
||||||
|
should.Equal(float64(12345), any.ToFloat64())
|
||||||
|
should.Equal("12345", any.ToString())
|
||||||
|
should.Equal(true, any.ToBool())
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("12345", string(stream.Buffer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_uint64_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := WrapUint64(12345)
|
||||||
|
should.Equal(12345, any.ToInt())
|
||||||
|
should.Equal(int32(12345), any.ToInt32())
|
||||||
|
should.Equal(int64(12345), any.ToInt64())
|
||||||
|
should.Equal(uint(12345), any.ToUint())
|
||||||
|
should.Equal(uint32(12345), any.ToUint32())
|
||||||
|
should.Equal(uint64(12345), any.ToUint64())
|
||||||
|
should.Equal(float32(12345), any.ToFloat32())
|
||||||
|
should.Equal(float64(12345), any.ToFloat64())
|
||||||
|
should.Equal("12345", any.ToString())
|
||||||
|
should.Equal(true, any.ToBool())
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("12345", string(stream.Buffer()))
|
||||||
|
stream = NewStream(ConfigDefault, nil, 32)
|
||||||
|
stream.WriteUint(uint(123))
|
||||||
|
should.Equal("123", string(stream.Buffer()))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_int_lazy_any_get(t *testing.T) {
|
func Test_int_lazy_any_get(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte("1234"))
|
any := Get([]byte("1234"))
|
||||||
should.Equal(Invalid, any.Get(1, "2").ValueType())
|
// panic!!
|
||||||
|
//should.Equal(any.LastError(), io.EOF)
|
||||||
|
should.Equal(InvalidValue, any.Get(1, "2").ValueType())
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1,54 +1,68 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_object_as_any(t *testing.T) {
|
func Test_read_object_as_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte(`{"a":"b","c":"d"}`))
|
any := Get([]byte(`{"a":"stream","c":"d"}`))
|
||||||
should.Equal(`{"a":"b","c":"d"}`, any.ToString())
|
should.Equal(`{"a":"stream","c":"d"}`, any.ToString())
|
||||||
// partial parse
|
// partial parse
|
||||||
should.Equal("b", any.Get("a").ToString())
|
should.Equal("stream", any.Get("a").ToString())
|
||||||
should.Equal("d", any.Get("c").ToString())
|
should.Equal("d", any.Get("c").ToString())
|
||||||
should.Equal(2, len(any.Keys()))
|
should.Equal(2, len(any.Keys()))
|
||||||
any = Get([]byte(`{"a":"b","c":"d"}`))
|
any = Get([]byte(`{"a":"stream","c":"d"}`))
|
||||||
// full parse
|
// full parse
|
||||||
should.Equal(2, len(any.Keys()))
|
should.Equal(2, len(any.Keys()))
|
||||||
should.Equal(2, any.Size())
|
should.Equal(2, any.Size())
|
||||||
should.True(any.ToBool())
|
should.True(any.ToBool())
|
||||||
should.Equal(1, any.ToInt())
|
should.Equal(0, any.ToInt())
|
||||||
should.Equal(Object, any.ValueType())
|
should.Equal(ObjectValue, any.ValueType())
|
||||||
should.Nil(any.LastError())
|
should.Nil(any.LastError())
|
||||||
should.Equal("b", any.GetObject()["a"].ToString())
|
|
||||||
obj := struct {
|
obj := struct {
|
||||||
A string
|
A string
|
||||||
}{}
|
}{}
|
||||||
any.ToVal(&obj)
|
any.ToVal(&obj)
|
||||||
should.Equal("b", obj.A)
|
should.Equal("stream", obj.A)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_object_lazy_any_get(t *testing.T) {
|
func Test_object_lazy_any_get(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte(`{"a":{"b":{"c":"d"}}}`))
|
any := Get([]byte(`{"a":{"stream":{"c":"d"}}}`))
|
||||||
should.Equal("d", any.Get("a", "b", "c").ToString())
|
should.Equal("d", any.Get("a", "stream", "c").ToString())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_object_lazy_any_get_all(t *testing.T) {
|
func Test_object_lazy_any_get_all(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte(`{"a":[0],"b":[1]}`))
|
any := Get([]byte(`{"a":[0],"stream":[1]}`))
|
||||||
should.Contains(any.Get('*', 0).ToString(), `"a":0`)
|
should.Contains(any.Get('*', 0).ToString(), `"a":0`)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_object_lazy_any_get_invalid(t *testing.T) {
|
func Test_object_lazy_any_get_invalid(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte(`{}`))
|
any := Get([]byte(`{}`))
|
||||||
should.Equal(Invalid, any.Get("a", "b", "c").ValueType())
|
should.Equal(InvalidValue, any.Get("a", "stream", "c").ValueType())
|
||||||
should.Equal(Invalid, any.Get(1).ValueType())
|
should.Equal(InvalidValue, any.Get(1).ValueType())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_wrap_object(t *testing.T) {
|
func Test_wrap_map_and_convert_to_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := Wrap(map[string]interface{}{"a": 1})
|
||||||
|
should.True(any.ToBool())
|
||||||
|
should.Equal(0, any.ToInt())
|
||||||
|
should.Equal(int32(0), any.ToInt32())
|
||||||
|
should.Equal(int64(0), any.ToInt64())
|
||||||
|
should.Equal(float32(0), any.ToFloat32())
|
||||||
|
should.Equal(float64(0), any.ToFloat64())
|
||||||
|
should.Equal(uint(0), any.ToUint())
|
||||||
|
should.Equal(uint32(0), any.ToUint32())
|
||||||
|
should.Equal(uint64(0), any.ToUint64())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_wrap_object_and_convert_to_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
type TestObject struct {
|
type TestObject struct {
|
||||||
Field1 string
|
Field1 string
|
||||||
@ -59,6 +73,24 @@ func Test_wrap_object(t *testing.T) {
|
|||||||
any = Wrap(TestObject{"hello", "world"})
|
any = Wrap(TestObject{"hello", "world"})
|
||||||
should.Equal(2, any.Size())
|
should.Equal(2, any.Size())
|
||||||
should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString())
|
should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString())
|
||||||
|
|
||||||
|
should.Equal(0, any.ToInt())
|
||||||
|
should.Equal(int32(0), any.ToInt32())
|
||||||
|
should.Equal(int64(0), any.ToInt64())
|
||||||
|
should.Equal(float32(0), any.ToFloat32())
|
||||||
|
should.Equal(float64(0), any.ToFloat64())
|
||||||
|
should.Equal(uint(0), any.ToUint())
|
||||||
|
should.Equal(uint32(0), any.ToUint32())
|
||||||
|
should.Equal(uint64(0), any.ToUint64())
|
||||||
|
should.True(any.ToBool())
|
||||||
|
should.Equal(`{"Field1":"hello"}`, any.ToString())
|
||||||
|
|
||||||
|
// cannot pass!
|
||||||
|
//stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
//any.WriteTo(stream)
|
||||||
|
//should.Equal(`{"Field1":"hello"}`, string(stream.Buffer()))
|
||||||
|
// cannot pass!
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_any_within_struct(t *testing.T) {
|
func Test_any_within_struct(t *testing.T) {
|
||||||
|
@ -1,10 +1,41 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var stringConvertMap = map[string]string{
|
||||||
|
"null": "",
|
||||||
|
"321.1": "321.1",
|
||||||
|
`"1.1"`: "1.1",
|
||||||
|
`"-123.1"`: "-123.1",
|
||||||
|
"0.0": "0.0",
|
||||||
|
"0": "0",
|
||||||
|
`"0"`: "0",
|
||||||
|
`"0.0"`: "0.0",
|
||||||
|
`"00.0"`: "00.0",
|
||||||
|
"true": "true",
|
||||||
|
"false": "false",
|
||||||
|
`"true"`: "true",
|
||||||
|
`"false"`: "false",
|
||||||
|
`"true123"`: "true123",
|
||||||
|
`"+1"`: "+1",
|
||||||
|
"[]": "[]",
|
||||||
|
"[1,2]": "[1,2]",
|
||||||
|
"{}": "{}",
|
||||||
|
`{"a":1, "stream":true}`: `{"a":1, "stream":true}`,
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_any_to_string(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
for k, v := range stringConvertMap {
|
||||||
|
any := Get([]byte(k))
|
||||||
|
should.Equal(v, any.ToString(), "original val "+k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func Test_read_string_as_any(t *testing.T) {
|
func Test_read_string_as_any(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Get([]byte(`"hello"`))
|
any := Get([]byte(`"hello"`))
|
||||||
@ -13,7 +44,7 @@ func Test_read_string_as_any(t *testing.T) {
|
|||||||
any = Get([]byte(`" "`))
|
any = Get([]byte(`" "`))
|
||||||
should.False(any.ToBool())
|
should.False(any.ToBool())
|
||||||
any = Get([]byte(`"false"`))
|
any = Get([]byte(`"false"`))
|
||||||
should.False(any.ToBool())
|
should.True(any.ToBool())
|
||||||
any = Get([]byte(`"123"`))
|
any = Get([]byte(`"123"`))
|
||||||
should.Equal(123, any.ToInt())
|
should.Equal(123, any.ToInt())
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,7 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -156,7 +156,7 @@ func Test_encode_byte_array(t *testing.T) {
|
|||||||
should.Equal(`"AQID"`, string(bytes))
|
should.Equal(`"AQID"`, string(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_decode_byte_array(t *testing.T) {
|
func Test_decode_byte_array_from_base64(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
data := []byte{}
|
data := []byte{}
|
||||||
err := json.Unmarshal([]byte(`"AQID"`), &data)
|
err := json.Unmarshal([]byte(`"AQID"`), &data)
|
||||||
@ -167,6 +167,17 @@ func Test_decode_byte_array(t *testing.T) {
|
|||||||
should.Equal([]byte{1, 2, 3}, data)
|
should.Equal([]byte{1, 2, 3}, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_decode_byte_array_from_array(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
data := []byte{}
|
||||||
|
err := json.Unmarshal([]byte(`[1,2,3]`), &data)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal([]byte{1, 2, 3}, data)
|
||||||
|
err = Unmarshal([]byte(`[1,2,3]`), &data)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal([]byte{1, 2, 3}, data)
|
||||||
|
}
|
||||||
|
|
||||||
func Test_decode_slice(t *testing.T) {
|
func Test_decode_slice(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
slice := make([]string, 0, 5)
|
slice := make([]string, 0, 5)
|
||||||
|
@ -3,8 +3,9 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_true(t *testing.T) {
|
func Test_true(t *testing.T) {
|
||||||
@ -27,9 +28,10 @@ func Test_write_true_false(t *testing.T) {
|
|||||||
stream := NewStream(ConfigDefault, buf, 4096)
|
stream := NewStream(ConfigDefault, buf, 4096)
|
||||||
stream.WriteTrue()
|
stream.WriteTrue()
|
||||||
stream.WriteFalse()
|
stream.WriteFalse()
|
||||||
|
stream.WriteBool(false)
|
||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal("truefalse", buf.String())
|
should.Equal("truefalsefalse", buf.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_val_bool(t *testing.T) {
|
func Test_write_val_bool(t *testing.T) {
|
||||||
@ -37,7 +39,9 @@ func Test_write_val_bool(t *testing.T) {
|
|||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
stream := NewStream(ConfigDefault, buf, 4096)
|
stream := NewStream(ConfigDefault, buf, 4096)
|
||||||
stream.WriteVal(true)
|
stream.WriteVal(true)
|
||||||
|
should.Equal(stream.Buffered(), 4)
|
||||||
stream.Flush()
|
stream.Flush()
|
||||||
|
should.Equal(stream.Buffered(), 0)
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal("true", buf.String())
|
should.Equal("true", buf.String())
|
||||||
}
|
}
|
||||||
@ -78,3 +82,32 @@ func Test_decode_string_bool(t *testing.T) {
|
|||||||
err = Unmarshal([]byte(`{"Field":true}`), &obj)
|
err = Unmarshal([]byte(`{"Field":true}`), &obj)
|
||||||
should.NotNil(err)
|
should.NotNil(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_bool_can_be_null(t *testing.T) {
|
||||||
|
type TestData struct {
|
||||||
|
Field bool `json:"field"`
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
obj := TestData{}
|
||||||
|
data1 := []byte(`{"field": true}`)
|
||||||
|
err := Unmarshal(data1, &obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(true, obj.Field)
|
||||||
|
|
||||||
|
data2 := []byte(`{"field": null}`)
|
||||||
|
err = Unmarshal(data2, &obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
// Same behavior as stdlib, not touching the existing value.
|
||||||
|
should.Equal(true, obj.Field)
|
||||||
|
|
||||||
|
// Checking stdlib behavior as well
|
||||||
|
obj2 := TestData{}
|
||||||
|
err = json.Unmarshal(data1, &obj2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(true, obj2.Field)
|
||||||
|
|
||||||
|
err = json.Unmarshal(data2, &obj2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(true, obj2.Field)
|
||||||
|
}
|
||||||
|
@ -2,7 +2,7 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@ -18,7 +18,7 @@ func Test_customize_type_decoder(t *testing.T) {
|
|||||||
}
|
}
|
||||||
*((*time.Time)(ptr)) = t
|
*((*time.Time)(ptr)) = t
|
||||||
})
|
})
|
||||||
defer ConfigDefault.cleanDecoders()
|
defer ConfigDefault.(*frozenConfig).cleanDecoders()
|
||||||
val := time.Time{}
|
val := time.Time{}
|
||||||
err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
|
err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -36,7 +36,7 @@ func Test_customize_type_encoder(t *testing.T) {
|
|||||||
t := *((*time.Time)(ptr))
|
t := *((*time.Time)(ptr))
|
||||||
stream.WriteString(t.UTC().Format("2006-01-02 15:04:05"))
|
stream.WriteString(t.UTC().Format("2006-01-02 15:04:05"))
|
||||||
}, nil)
|
}, nil)
|
||||||
defer ConfigDefault.cleanEncoders()
|
defer ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
val := time.Unix(0, 0)
|
val := time.Unix(0, 0)
|
||||||
str, err := MarshalToString(val)
|
str, err := MarshalToString(val)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
@ -44,13 +44,13 @@ func Test_customize_type_encoder(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_customize_byte_array_encoder(t *testing.T) {
|
func Test_customize_byte_array_encoder(t *testing.T) {
|
||||||
ConfigDefault.cleanEncoders()
|
ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *Stream) {
|
RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *Stream) {
|
||||||
t := *((*[]byte)(ptr))
|
t := *((*[]byte)(ptr))
|
||||||
stream.WriteString(string(t))
|
stream.WriteString(string(t))
|
||||||
}, nil)
|
}, nil)
|
||||||
defer ConfigDefault.cleanEncoders()
|
defer ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
val := []byte("abc")
|
val := []byte("abc")
|
||||||
str, err := MarshalToString(val)
|
str, err := MarshalToString(val)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
@ -73,7 +73,7 @@ func Test_customize_field_decoder(t *testing.T) {
|
|||||||
RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
|
RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
|
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
|
||||||
})
|
})
|
||||||
defer ConfigDefault.cleanDecoders()
|
defer ConfigDefault.(*frozenConfig).cleanDecoders()
|
||||||
tom := Tom{}
|
tom := Tom{}
|
||||||
err := Unmarshal([]byte(`{"field1": 100}`), &tom)
|
err := Unmarshal([]byte(`{"field1": 100}`), &tom)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -118,25 +118,6 @@ func Test_customize_field_by_extension(t *testing.T) {
|
|||||||
should.Equal(`{"field-1":100}`, str)
|
should.Equal(`{"field-1":100}`, str)
|
||||||
}
|
}
|
||||||
|
|
||||||
//func Test_unexported_fields(t *testing.T) {
|
|
||||||
// jsoniter := Config{SupportUnexportedStructFields: true}.Froze()
|
|
||||||
// should := require.New(t)
|
|
||||||
// type TestObject struct {
|
|
||||||
// field1 string
|
|
||||||
// field2 string `json:"field-2"`
|
|
||||||
// }
|
|
||||||
// obj := TestObject{}
|
|
||||||
// obj.field1 = "hello"
|
|
||||||
// should.Nil(jsoniter.UnmarshalFromString(`{}`, &obj))
|
|
||||||
// should.Equal("hello", obj.field1)
|
|
||||||
// should.Nil(jsoniter.UnmarshalFromString(`{"field1": "world", "field-2": "abc"}`, &obj))
|
|
||||||
// should.Equal("world", obj.field1)
|
|
||||||
// should.Equal("abc", obj.field2)
|
|
||||||
// str, err := jsoniter.MarshalToString(obj)
|
|
||||||
// should.Nil(err)
|
|
||||||
// should.Contains(str, `"field-2":"abc"`)
|
|
||||||
//}
|
|
||||||
|
|
||||||
type timeImplementedMarshaler time.Time
|
type timeImplementedMarshaler time.Time
|
||||||
|
|
||||||
func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) {
|
func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) {
|
||||||
@ -163,7 +144,7 @@ func Test_marshaler_and_encoder(t *testing.T) {
|
|||||||
type TestObject struct {
|
type TestObject struct {
|
||||||
Field *timeImplementedMarshaler
|
Field *timeImplementedMarshaler
|
||||||
}
|
}
|
||||||
ConfigDefault.cleanEncoders()
|
ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
RegisterTypeEncoderFunc("jsoniter.timeImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
|
RegisterTypeEncoderFunc("jsoniter.timeImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
|
||||||
stream.WriteString("hello from encoder")
|
stream.WriteString("hello from encoder")
|
||||||
@ -180,26 +161,22 @@ func Test_marshaler_and_encoder(t *testing.T) {
|
|||||||
|
|
||||||
type ObjectImplementedUnmarshaler int
|
type ObjectImplementedUnmarshaler int
|
||||||
|
|
||||||
func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON([]byte) error {
|
func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON(s []byte) error {
|
||||||
*obj = 100
|
val, _ := strconv.ParseInt(string(s[1:len(s)-1]), 10, 64)
|
||||||
|
*obj = ObjectImplementedUnmarshaler(val)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_unmarshaler(t *testing.T) {
|
func Test_unmarshaler(t *testing.T) {
|
||||||
type TestObject struct {
|
|
||||||
Field *ObjectImplementedUnmarshaler
|
|
||||||
Field2 string
|
|
||||||
}
|
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
obj := TestObject{}
|
var obj ObjectImplementedUnmarshaler
|
||||||
val := ObjectImplementedUnmarshaler(0)
|
err := json.Unmarshal([]byte(` "100" `), &obj)
|
||||||
obj.Field = &val
|
|
||||||
err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
|
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(100, int(*obj.Field))
|
should.Equal(100, int(obj))
|
||||||
err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
|
iter := ParseString(ConfigDefault, ` "100" `)
|
||||||
|
iter.ReadVal(&obj)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(100, int(*obj.Field))
|
should.Equal(100, int(obj))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_unmarshaler_and_decoder(t *testing.T) {
|
func Test_unmarshaler_and_decoder(t *testing.T) {
|
||||||
@ -207,7 +184,7 @@ func Test_unmarshaler_and_decoder(t *testing.T) {
|
|||||||
Field *ObjectImplementedUnmarshaler
|
Field *ObjectImplementedUnmarshaler
|
||||||
Field2 string
|
Field2 string
|
||||||
}
|
}
|
||||||
ConfigDefault.cleanDecoders()
|
ConfigDefault.(*frozenConfig).cleanDecoders()
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
|
RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
*(*ObjectImplementedUnmarshaler)(ptr) = 10
|
*(*ObjectImplementedUnmarshaler)(ptr) = 10
|
||||||
@ -216,10 +193,10 @@ func Test_unmarshaler_and_decoder(t *testing.T) {
|
|||||||
obj := TestObject{}
|
obj := TestObject{}
|
||||||
val := ObjectImplementedUnmarshaler(0)
|
val := ObjectImplementedUnmarshaler(0)
|
||||||
obj.Field = &val
|
obj.Field = &val
|
||||||
err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
|
err := json.Unmarshal([]byte(`{"Field":"100"}`), &obj)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(100, int(*obj.Field))
|
should.Equal(100, int(*obj.Field))
|
||||||
err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
|
err = Unmarshal([]byte(`{"Field":"100"}`), &obj)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(10, int(*obj.Field))
|
should.Equal(10, int(*obj.Field))
|
||||||
}
|
}
|
||||||
@ -242,3 +219,122 @@ func Test_marshaler_on_struct(t *testing.T) {
|
|||||||
//json.Marshal(fixed)
|
//json.Marshal(fixed)
|
||||||
Marshal(fixed)
|
Marshal(fixed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type withChan struct {
|
||||||
|
F2 chan []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q withChan) MarshalJSON() ([]byte, error) {
|
||||||
|
return []byte(`""`), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *withChan) UnmarshalJSON(value []byte) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_marshal_json_with_chan(t *testing.T) {
|
||||||
|
type TestObject struct {
|
||||||
|
F1 withChan
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(TestObject{})
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"F1":""}`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
type withTime struct {
|
||||||
|
time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *withTime) UnmarshalJSON(b []byte) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (t withTime) MarshalJSON() ([]byte, error) {
|
||||||
|
return []byte(`"fake"`), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_marshal_json_with_time(t *testing.T) {
|
||||||
|
type S1 struct {
|
||||||
|
F1 withTime
|
||||||
|
F2 *withTime
|
||||||
|
}
|
||||||
|
type TestObject struct {
|
||||||
|
TF1 S1
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
obj := TestObject{
|
||||||
|
S1{
|
||||||
|
F1: withTime{
|
||||||
|
time.Unix(0, 0),
|
||||||
|
},
|
||||||
|
F2: &withTime{
|
||||||
|
time.Unix(0, 0),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
output, err := json.Marshal(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output))
|
||||||
|
output, err = Marshal(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output))
|
||||||
|
obj = TestObject{}
|
||||||
|
should.Nil(json.Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj))
|
||||||
|
should.NotNil(obj.TF1.F2)
|
||||||
|
obj = TestObject{}
|
||||||
|
should.Nil(Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj))
|
||||||
|
should.NotNil(obj.TF1.F2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_customize_tag_key(t *testing.T) {
|
||||||
|
|
||||||
|
type TestObject struct {
|
||||||
|
Field string `orm:"field"`
|
||||||
|
}
|
||||||
|
|
||||||
|
should := require.New(t)
|
||||||
|
json := Config{TagKey: "orm"}.Froze()
|
||||||
|
str, err := json.MarshalToString(TestObject{"hello"})
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"field":"hello"}`, str)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_recursive_empty_interface_customization(t *testing.T) {
|
||||||
|
t.Skip()
|
||||||
|
var obj interface{}
|
||||||
|
RegisterTypeDecoderFunc("interface {}", func(ptr unsafe.Pointer, iter *Iterator) {
|
||||||
|
switch iter.WhatIsNext() {
|
||||||
|
case NumberValue:
|
||||||
|
*(*interface{})(ptr) = iter.ReadInt64()
|
||||||
|
default:
|
||||||
|
*(*interface{})(ptr) = iter.Read()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
should := require.New(t)
|
||||||
|
Unmarshal([]byte("[100]"), &obj)
|
||||||
|
should.Equal([]interface{}{int64(100)}, obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
type GeoLocation struct {
|
||||||
|
Id string `json:"id,omitempty" db:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *GeoLocation) MarshalJSON() ([]byte, error) {
|
||||||
|
return []byte(`{}`), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *GeoLocation) UnmarshalJSON(input []byte) error {
|
||||||
|
p.Id = "hello"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_marshal_and_unmarshal_on_non_pointer(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
locations := []GeoLocation{{"000"}}
|
||||||
|
bytes, err := Marshal(locations)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("[{}]", string(bytes))
|
||||||
|
err = Unmarshal([]byte("[1]"), &locations)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("hello", locations[0].Id)
|
||||||
|
}
|
||||||
|
@ -2,9 +2,9 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_bind_api_demo(t *testing.T) {
|
func Test_bind_api_demo(t *testing.T) {
|
||||||
@ -16,12 +16,13 @@ func Test_bind_api_demo(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_iterator_api_demo(t *testing.T) {
|
func Test_iterator_api_demo(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `[0,1,2,3]`)
|
iter := ParseString(ConfigDefault, `[0,1,2,3]`)
|
||||||
total := 0
|
total := 0
|
||||||
for iter.ReadArray() {
|
for iter.ReadArray() {
|
||||||
total += iter.ReadInt()
|
total += iter.ReadInt()
|
||||||
}
|
}
|
||||||
fmt.Println(total)
|
should.Equal(6, total)
|
||||||
}
|
}
|
||||||
|
|
||||||
type People struct {
|
type People struct {
|
||||||
|
42
jsoniter_encode_interface_test.go
Normal file
42
jsoniter_encode_interface_test.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_encode_interface(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var a interface{}
|
||||||
|
a = int8(10)
|
||||||
|
str, err := MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "10")
|
||||||
|
a = float32(3)
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "3")
|
||||||
|
a = map[string]interface{}{"abc": 1}
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, `{"abc":1}`)
|
||||||
|
a = uintptr(1)
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "1")
|
||||||
|
a = uint(1)
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "1")
|
||||||
|
a = uint8(1)
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "1")
|
||||||
|
a = json.RawMessage("abc")
|
||||||
|
MarshalToString(a)
|
||||||
|
str, err = MarshalToString(a)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(str, "abc")
|
||||||
|
}
|
50
jsoniter_enum_marshaler_test.go
Normal file
50
jsoniter_enum_marshaler_test.go
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MyEnum int64
|
||||||
|
|
||||||
|
const (
|
||||||
|
MyEnumA MyEnum = iota
|
||||||
|
MyEnumB
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *MyEnum) MarshalJSON() ([]byte, error) {
|
||||||
|
return []byte(fmt.Sprintf(`"foo-%d"`, int(*m))), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MyEnum) UnmarshalJSON(jb []byte) error {
|
||||||
|
switch string(jb) {
|
||||||
|
case `"foo-1"`:
|
||||||
|
*m = MyEnumB
|
||||||
|
default:
|
||||||
|
*m = MyEnumA
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_custom_marshaler_on_enum(t *testing.T) {
|
||||||
|
type Wrapper struct {
|
||||||
|
Payload interface{}
|
||||||
|
}
|
||||||
|
type Wrapper2 struct {
|
||||||
|
Payload MyEnum
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
w := Wrapper{Payload: MyEnumB}
|
||||||
|
|
||||||
|
jb, err := Marshal(w)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(`{"Payload":"foo-1"}`, string(jb))
|
||||||
|
|
||||||
|
var w2 Wrapper2
|
||||||
|
err = Unmarshal(jb, &w2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(MyEnumB, w2.Payload)
|
||||||
|
}
|
@ -2,7 +2,7 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1,12 +1,15 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_big_float(t *testing.T) {
|
func Test_read_big_float(t *testing.T) {
|
||||||
@ -26,7 +29,10 @@ func Test_read_big_int(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_float(t *testing.T) {
|
func Test_read_float(t *testing.T) {
|
||||||
inputs := []string{`1.1`, `1000`, `9223372036854775807`, `12.3`, `-12.3`, `720368.54775807`, `720368.547758075`}
|
inputs := []string{
|
||||||
|
`1.1`, `1000`, `9223372036854775807`, `12.3`, `-12.3`, `720368.54775807`, `720368.547758075`,
|
||||||
|
`1e1`, `1e+1`, `1e-1`, `1E1`, `1E+1`, `1E-1`, `-1e1`, `-1e+1`, `-1e-1`,
|
||||||
|
}
|
||||||
for _, input := range inputs {
|
for _, input := range inputs {
|
||||||
// non-streaming
|
// non-streaming
|
||||||
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
||||||
@ -54,9 +60,10 @@ func Test_read_float(t *testing.T) {
|
|||||||
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := Parse(ConfigDefault, bytes.NewBufferString(input+","), 2)
|
iter := Parse(ConfigDefault, bytes.NewBufferString(input+","), 2)
|
||||||
expected, err := strconv.ParseFloat(input, 64)
|
val := float64(0)
|
||||||
|
err := json.Unmarshal([]byte(input), &val)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(expected, iter.ReadFloat64())
|
should.Equal(val, iter.ReadFloat64())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -85,7 +92,9 @@ func Test_write_float32(t *testing.T) {
|
|||||||
stream.WriteFloat32Lossy(val)
|
stream.WriteFloat32Lossy(val)
|
||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal(strconv.FormatFloat(float64(val), 'f', -1, 32), buf.String())
|
output, err := json.Marshal(val)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(string(output), buf.String())
|
||||||
})
|
})
|
||||||
t.Run(fmt.Sprintf("%v", val), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v", val), func(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
@ -94,7 +103,9 @@ func Test_write_float32(t *testing.T) {
|
|||||||
stream.WriteVal(val)
|
stream.WriteVal(val)
|
||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal(strconv.FormatFloat(float64(val), 'f', -1, 32), buf.String())
|
output, err := json.Marshal(val)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(string(output), buf.String())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
@ -105,6 +116,10 @@ func Test_write_float32(t *testing.T) {
|
|||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal("abcdefg1.123456", buf.String())
|
should.Equal("abcdefg1.123456", buf.String())
|
||||||
|
|
||||||
|
stream = NewStream(ConfigDefault, nil, 0)
|
||||||
|
stream.WriteFloat32(float32(0.0000001))
|
||||||
|
should.Equal("1e-07", string(stream.buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_float64(t *testing.T) {
|
func Test_write_float64(t *testing.T) {
|
||||||
@ -138,6 +153,10 @@ func Test_write_float64(t *testing.T) {
|
|||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal("abcdefg1.123456", buf.String())
|
should.Equal("abcdefg1.123456", buf.String())
|
||||||
|
|
||||||
|
stream = NewStream(ConfigDefault, nil, 0)
|
||||||
|
stream.WriteFloat64(float64(0.0000001))
|
||||||
|
should.Equal("1e-07", string(stream.buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_float64_cursor(t *testing.T) {
|
func Test_read_float64_cursor(t *testing.T) {
|
||||||
|
@ -1,13 +1,16 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_uint64_invalid(t *testing.T) {
|
func Test_read_uint64_invalid(t *testing.T) {
|
||||||
@ -17,7 +20,45 @@ func Test_read_uint64_invalid(t *testing.T) {
|
|||||||
should.NotNil(iter.Error)
|
should.NotNil(iter.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_int8(t *testing.T) {
|
func Test_read_int_from_null(t *testing.T) {
|
||||||
|
|
||||||
|
type TestObject struct {
|
||||||
|
F1 int8
|
||||||
|
F2 int16
|
||||||
|
F3 int32
|
||||||
|
F4 int64
|
||||||
|
F5 int
|
||||||
|
F6 uint8
|
||||||
|
F7 uint16
|
||||||
|
F8 uint32
|
||||||
|
F9 uint64
|
||||||
|
F10 uint
|
||||||
|
F11 float32
|
||||||
|
F12 float64
|
||||||
|
F13 uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
should := require.New(t)
|
||||||
|
obj := TestObject{}
|
||||||
|
err := Unmarshal([]byte(`{
|
||||||
|
"f1":null,
|
||||||
|
"f2":null,
|
||||||
|
"f3":null,
|
||||||
|
"f4":null,
|
||||||
|
"f5":null,
|
||||||
|
"f6":null,
|
||||||
|
"f7":null,
|
||||||
|
"f8":null,
|
||||||
|
"f9":null,
|
||||||
|
"f10":null,
|
||||||
|
"f11":null,
|
||||||
|
"f12":null,
|
||||||
|
"f13":null
|
||||||
|
}`), &obj)
|
||||||
|
should.Nil(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _int8(t *testing.T) {
|
||||||
inputs := []string{`127`, `-128`}
|
inputs := []string{`127`, `-128`}
|
||||||
for _, input := range inputs {
|
for _, input := range inputs {
|
||||||
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
||||||
@ -79,12 +120,52 @@ func Test_read_int64_array(t *testing.T) {
|
|||||||
should.Equal(3, len(val))
|
should.Equal(3, len(val))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_int32_overflow(t *testing.T) {
|
func Test_read_int_overflow(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
input := "123456789123456789,"
|
inputArr := []string{"123451", "-123451"}
|
||||||
iter := ParseString(ConfigDefault, input)
|
for _, s := range inputArr {
|
||||||
iter.ReadInt32()
|
iter := ParseString(ConfigDefault, s)
|
||||||
should.NotNil(iter.Error)
|
iter.ReadInt8()
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
|
||||||
|
iterU := ParseString(ConfigDefault, s)
|
||||||
|
iterU.ReadUint8()
|
||||||
|
should.NotNil(iterU.Error)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
inputArr = []string{"12345678912", "-12345678912"}
|
||||||
|
for _, s := range inputArr {
|
||||||
|
iter := ParseString(ConfigDefault, s)
|
||||||
|
iter.ReadInt16()
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
|
||||||
|
iterUint := ParseString(ConfigDefault, s)
|
||||||
|
iterUint.ReadUint16()
|
||||||
|
should.NotNil(iterUint.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputArr = []string{"3111111111", "-3111111111", "1234232323232323235678912", "-1234567892323232323212"}
|
||||||
|
for _, s := range inputArr {
|
||||||
|
iter := ParseString(ConfigDefault, s)
|
||||||
|
iter.ReadInt32()
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
|
||||||
|
iterUint := ParseString(ConfigDefault, s)
|
||||||
|
iterUint.ReadUint32()
|
||||||
|
should.NotNil(iterUint.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputArr = []string{"9223372036854775811", "-9523372036854775807", "1234232323232323235678912", "-1234567892323232323212"}
|
||||||
|
for _, s := range inputArr {
|
||||||
|
iter := ParseString(ConfigDefault, s)
|
||||||
|
iter.ReadInt64()
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
|
||||||
|
iterUint := ParseString(ConfigDefault, s)
|
||||||
|
iterUint.ReadUint64()
|
||||||
|
should.NotNil(iterUint.Error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_int64(t *testing.T) {
|
func Test_read_int64(t *testing.T) {
|
||||||
@ -414,6 +495,17 @@ func Test_json_number(t *testing.T) {
|
|||||||
should.Equal(`[1]`, str)
|
should.Equal(`[1]`, str)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_jsoniter_number(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var arr []Number
|
||||||
|
err := Unmarshal([]byte(`[1]`), &arr)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(Number("1"), arr[0])
|
||||||
|
str, isNumber := CastJsonNumber(arr[0])
|
||||||
|
should.True(isNumber)
|
||||||
|
should.Equal("1", str)
|
||||||
|
}
|
||||||
|
|
||||||
func Benchmark_jsoniter_encode_int(b *testing.B) {
|
func Benchmark_jsoniter_encode_int(b *testing.B) {
|
||||||
stream := NewStream(ConfigDefault, ioutil.Discard, 64)
|
stream := NewStream(ConfigDefault, ioutil.Discard, 64)
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
|
@ -2,9 +2,11 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_write_array_of_interface(t *testing.T) {
|
func Test_write_array_of_interface(t *testing.T) {
|
||||||
@ -81,6 +83,15 @@ func Test_read_interface(t *testing.T) {
|
|||||||
err := UnmarshalFromString(`"hello"`, &val)
|
err := UnmarshalFromString(`"hello"`, &val)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal("hello", val)
|
should.Equal("hello", val)
|
||||||
|
err = UnmarshalFromString(`1e1`, &val)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(float64(10), val)
|
||||||
|
err = UnmarshalFromString(`1.0e1`, &val)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(float64(10), val)
|
||||||
|
err = json.Unmarshal([]byte(`1.0e1`), &val)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(float64(10), val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_custom_interface(t *testing.T) {
|
func Test_read_custom_interface(t *testing.T) {
|
||||||
@ -141,8 +152,8 @@ func Test_encode_object_contain_non_empty_interface(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_nil_non_empty_interface(t *testing.T) {
|
func Test_nil_non_empty_interface(t *testing.T) {
|
||||||
ConfigDefault.cleanEncoders()
|
ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
ConfigDefault.cleanDecoders()
|
ConfigDefault.(*frozenConfig).cleanDecoders()
|
||||||
type TestObject struct {
|
type TestObject struct {
|
||||||
Field []MyInterface
|
Field []MyInterface
|
||||||
}
|
}
|
||||||
@ -162,3 +173,200 @@ func Test_read_large_number_as_interface(t *testing.T) {
|
|||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(`123456789123456789123456789`, output)
|
should.Equal(`123456789123456789123456789`, output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_nested_one_field_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type YetYetAnotherObject struct {
|
||||||
|
Field string
|
||||||
|
}
|
||||||
|
type YetAnotherObject struct {
|
||||||
|
Field *YetYetAnotherObject
|
||||||
|
}
|
||||||
|
type AnotherObject struct {
|
||||||
|
Field *YetAnotherObject
|
||||||
|
}
|
||||||
|
type TestObject struct {
|
||||||
|
Me *AnotherObject
|
||||||
|
}
|
||||||
|
obj := TestObject{&AnotherObject{&YetAnotherObject{&YetYetAnotherObject{"abc"}}}}
|
||||||
|
str, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str)
|
||||||
|
str, err = MarshalToString(&obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_struct_with_embedded_ptr_with_tag(t *testing.T) {
|
||||||
|
type O1 struct {
|
||||||
|
O1F string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option struct {
|
||||||
|
O1 *O1
|
||||||
|
}
|
||||||
|
|
||||||
|
type T struct {
|
||||||
|
Option `json:","`
|
||||||
|
}
|
||||||
|
var obj T
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"O1":null}`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_struct_with_one_nil(t *testing.T) {
|
||||||
|
type TestObject struct {
|
||||||
|
F *float64
|
||||||
|
}
|
||||||
|
var obj TestObject
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"F":null}`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_struct_with_one_nil_embedded(t *testing.T) {
|
||||||
|
type Parent struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
}
|
||||||
|
type TestObject struct {
|
||||||
|
*Parent
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should := require.New(t)
|
||||||
|
bytes, err := json.Marshal(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("{}", string(bytes))
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{}`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_struct_with_not_nil_embedded(t *testing.T) {
|
||||||
|
type Parent struct {
|
||||||
|
Field0 string
|
||||||
|
Field1 []string
|
||||||
|
Field2 map[string]interface{}
|
||||||
|
}
|
||||||
|
type TestObject struct {
|
||||||
|
*Parent
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
var obj TestObject
|
||||||
|
err := UnmarshalFromString(`{"Field0":"1","Field1":null,"Field2":{"K":"V"}}`, &obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Nil(obj.Field1)
|
||||||
|
should.Equal(map[string]interface{}{"K": "V"}, obj.Field2)
|
||||||
|
should.Equal("1", obj.Field0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_array_with_one_nil_ptr(t *testing.T) {
|
||||||
|
obj := [1]*float64{nil}
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`[null]`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_array_with_one_not_nil_ptr(t *testing.T) {
|
||||||
|
two := float64(2)
|
||||||
|
obj := [1]*float64{&two}
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`[2]`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_embedded_array_with_one_nil(t *testing.T) {
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 int
|
||||||
|
Field2 [1]*float64
|
||||||
|
}
|
||||||
|
var obj TestObject
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Contains(output, `"Field2":[null]`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_array_with_nothing(t *testing.T) {
|
||||||
|
var obj [2]*float64
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := MarshalToString(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`[null,null]`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_unmarshal_ptr_to_interface(t *testing.T) {
|
||||||
|
type TestData struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
var obj interface{} = &TestData{}
|
||||||
|
err := json.Unmarshal([]byte(`{"name":"value"}`), &obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("&{value}", fmt.Sprintf("%v", obj))
|
||||||
|
obj = interface{}(&TestData{})
|
||||||
|
err = Unmarshal([]byte(`{"name":"value"}`), &obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("&{value}", fmt.Sprintf("%v", obj))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_nil_out_null_interface(t *testing.T) {
|
||||||
|
type TestData struct {
|
||||||
|
Field interface{} `json:"field"`
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
var boolVar bool
|
||||||
|
obj := TestData{
|
||||||
|
Field: &boolVar,
|
||||||
|
}
|
||||||
|
|
||||||
|
data1 := []byte(`{"field": true}`)
|
||||||
|
|
||||||
|
err := Unmarshal(data1, &obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(true, *(obj.Field.(*bool)))
|
||||||
|
|
||||||
|
data2 := []byte(`{"field": null}`)
|
||||||
|
|
||||||
|
err = Unmarshal(data2, &obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(nil, obj.Field)
|
||||||
|
|
||||||
|
// Checking stdlib behavior matches.
|
||||||
|
obj2 := TestData{
|
||||||
|
Field: &boolVar,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(data1, &obj2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(true, *(obj2.Field.(*bool)))
|
||||||
|
|
||||||
|
err = json.Unmarshal(data2, &obj2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(nil, obj2.Field)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_omitempty_nil_interface(t *testing.T) {
|
||||||
|
type TestData struct {
|
||||||
|
Field interface{} `json:"field,omitempty"`
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
obj := TestData{
|
||||||
|
Field: nil,
|
||||||
|
}
|
||||||
|
|
||||||
|
js, err := json.Marshal(obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal("{}", string(js))
|
||||||
|
|
||||||
|
str, err := MarshalToString(obj)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(string(js), str)
|
||||||
|
}
|
||||||
|
132
jsoniter_invalid_test.go
Normal file
132
jsoniter_invalid_test.go
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"io"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_missing_object_end(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Metric string `json:"metric"`
|
||||||
|
Tags map[string]interface{} `json:"tags"`
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.NotNil(UnmarshalFromString(`{"metric": "sys.777","tags": {"a":"123"}`, &obj))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_missing_array_end(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
should.NotNil(UnmarshalFromString(`[1,2,3`, &[]int{}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_any(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := Get([]byte("[]"))
|
||||||
|
should.Equal(InvalidValue, any.Get(0.3).ValueType())
|
||||||
|
// is nil correct ?
|
||||||
|
should.Equal(nil, any.Get(0.3).GetInterface())
|
||||||
|
|
||||||
|
any = any.Get(0.3)
|
||||||
|
should.Equal(false, any.ToBool())
|
||||||
|
should.Equal(int(0), any.ToInt())
|
||||||
|
should.Equal(int32(0), any.ToInt32())
|
||||||
|
should.Equal(int64(0), any.ToInt64())
|
||||||
|
should.Equal(uint(0), any.ToUint())
|
||||||
|
should.Equal(uint32(0), any.ToUint32())
|
||||||
|
should.Equal(uint64(0), any.ToUint64())
|
||||||
|
should.Equal(float32(0), any.ToFloat32())
|
||||||
|
should.Equal(float64(0), any.ToFloat64())
|
||||||
|
should.Equal("", any.ToString())
|
||||||
|
|
||||||
|
should.Equal(InvalidValue, any.Get(0.1).Get(1).ValueType())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_struct_input(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct{}
|
||||||
|
input := []byte{54, 141, 30}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.NotNil(Unmarshal(input, &obj))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_slice_input(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct{}
|
||||||
|
input := []byte{93}
|
||||||
|
obj := []string{}
|
||||||
|
should.NotNil(Unmarshal(input, &obj))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_array_input(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct{}
|
||||||
|
input := []byte{93}
|
||||||
|
obj := [0]string{}
|
||||||
|
should.NotNil(Unmarshal(input, &obj))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_float(t *testing.T) {
|
||||||
|
inputs := []string{
|
||||||
|
`1.e1`, // dot without following digit
|
||||||
|
`1.`, // dot can not be the last char
|
||||||
|
``, // empty number
|
||||||
|
`01`, // extra leading zero
|
||||||
|
`-`, // negative without digit
|
||||||
|
`--`, // double negative
|
||||||
|
`--2`, // double negative
|
||||||
|
}
|
||||||
|
for _, input := range inputs {
|
||||||
|
t.Run(input, func(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
iter := ParseString(ConfigDefault, input+",")
|
||||||
|
iter.Skip()
|
||||||
|
should.NotEqual(io.EOF, iter.Error)
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
v := float64(0)
|
||||||
|
should.NotNil(json.Unmarshal([]byte(input), &v))
|
||||||
|
iter = ParseString(ConfigDefault, input+",")
|
||||||
|
iter.ReadFloat64()
|
||||||
|
should.NotEqual(io.EOF, iter.Error)
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
iter = ParseString(ConfigDefault, input+",")
|
||||||
|
iter.ReadFloat32()
|
||||||
|
should.NotEqual(io.EOF, iter.Error)
|
||||||
|
should.NotNil(iter.Error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_chan(t *testing.T) {
|
||||||
|
t.Skip("do not support chan")
|
||||||
|
|
||||||
|
type TestObject struct {
|
||||||
|
MyChan chan bool
|
||||||
|
MyField int
|
||||||
|
}
|
||||||
|
|
||||||
|
should := require.New(t)
|
||||||
|
obj := TestObject{}
|
||||||
|
str, err := json.Marshal(obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(``, str)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_invalid_number(t *testing.T) {
|
||||||
|
type Message struct {
|
||||||
|
Number int `json:"number"`
|
||||||
|
}
|
||||||
|
obj := Message{}
|
||||||
|
decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(bytes.NewBufferString(`{"number":"5"}`))
|
||||||
|
err := decoder.Decode(&obj)
|
||||||
|
invalidStr := err.Error()
|
||||||
|
result, err := ConfigCompatibleWithStandardLibrary.Marshal(invalidStr)
|
||||||
|
should := require.New(t)
|
||||||
|
should.Nil(err)
|
||||||
|
result2, err := json.Marshal(invalidStr)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(string(result2), string(result))
|
||||||
|
}
|
@ -2,6 +2,7 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
"io"
|
"io"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@ -19,11 +20,6 @@ func Test_read_by_one(t *testing.T) {
|
|||||||
if iter.Error != nil {
|
if iter.Error != nil {
|
||||||
t.Fatal(iter.Error)
|
t.Fatal(iter.Error)
|
||||||
}
|
}
|
||||||
iter.unreadByte()
|
|
||||||
if iter.Error == nil {
|
|
||||||
t.FailNow()
|
|
||||||
}
|
|
||||||
iter.Error = nil
|
|
||||||
b = iter.readByte()
|
b = iter.readByte()
|
||||||
if iter.Error != nil {
|
if iter.Error != nil {
|
||||||
t.Fatal(iter.Error)
|
t.Fatal(iter.Error)
|
||||||
@ -34,36 +30,21 @@ func Test_read_by_one(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_by_two(t *testing.T) {
|
func Test_read_by_two(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2)
|
iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2)
|
||||||
b := iter.readByte()
|
b := iter.readByte()
|
||||||
if iter.Error != nil {
|
should.Nil(iter.Error)
|
||||||
t.Fatal(iter.Error)
|
should.Equal(byte('a'), b)
|
||||||
}
|
|
||||||
if b != 'a' {
|
|
||||||
t.Fatal(b)
|
|
||||||
}
|
|
||||||
b = iter.readByte()
|
b = iter.readByte()
|
||||||
if iter.Error != nil {
|
should.Nil(iter.Error)
|
||||||
t.Fatal(iter.Error)
|
should.Equal(byte('b'), b)
|
||||||
}
|
|
||||||
if b != 'b' {
|
|
||||||
t.Fatal(b)
|
|
||||||
}
|
|
||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
if iter.Error != nil {
|
should.Nil(iter.Error)
|
||||||
t.Fatal(iter.Error)
|
|
||||||
}
|
|
||||||
iter.unreadByte()
|
iter.unreadByte()
|
||||||
if iter.Error != nil {
|
should.Nil(iter.Error)
|
||||||
t.Fatal(iter.Error)
|
|
||||||
}
|
|
||||||
b = iter.readByte()
|
b = iter.readByte()
|
||||||
if iter.Error != nil {
|
should.Nil(iter.Error)
|
||||||
t.Fatal(iter.Error)
|
should.Equal(byte('a'), b)
|
||||||
}
|
|
||||||
if b != 'a' {
|
|
||||||
t.Fatal(b)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_read_until_eof(t *testing.T) {
|
func Test_read_until_eof(t *testing.T) {
|
||||||
|
@ -2,7 +2,12 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_bad_case(t *testing.T) {
|
func Test_bad_case(t *testing.T) {
|
||||||
@ -33,3 +38,29 @@ func Test_bad_case(t *testing.T) {
|
|||||||
t.Fatal(count)
|
t.Fatal(count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_iterator_use_number(t *testing.T) {
|
||||||
|
// Test UseNumber with iterator Read()
|
||||||
|
inputs := []string{`2147483647`, `-2147483648`}
|
||||||
|
for _, input := range inputs {
|
||||||
|
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
iter := ParseString(Config{UseNumber: true}.Froze(), input)
|
||||||
|
expected := json.Number(input)
|
||||||
|
should.Equal(expected, iter.Read())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_iterator_without_number(t *testing.T) {
|
||||||
|
inputs := []string{`2147483647`, `-2147483648`}
|
||||||
|
for _, input := range inputs {
|
||||||
|
t.Run(fmt.Sprintf("%v", input), func(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
iter := ParseString(ConfigDefault, input)
|
||||||
|
expected, err := strconv.ParseInt(input, 10, 32)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(float64(expected), iter.Read())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -23,17 +23,122 @@ import (
|
|||||||
// }
|
// }
|
||||||
//}
|
//}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
ioutil.WriteFile("/tmp/large-file.json", []byte(`[{
|
||||||
|
"person": {
|
||||||
|
"id": "d50887ca-a6ce-4e59-b89f-14f0b5d03b03",
|
||||||
|
"name": {
|
||||||
|
"fullName": "Leonid Bugaev",
|
||||||
|
"givenName": "Leonid",
|
||||||
|
"familyName": "Bugaev"
|
||||||
|
},
|
||||||
|
"email": "leonsbox@gmail.com",
|
||||||
|
"gender": "male",
|
||||||
|
"location": "Saint Petersburg, Saint Petersburg, RU",
|
||||||
|
"geo": {
|
||||||
|
"city": "Saint Petersburg",
|
||||||
|
"state": "Saint Petersburg",
|
||||||
|
"country": "Russia",
|
||||||
|
"lat": 59.9342802,
|
||||||
|
"lng": 30.3350986
|
||||||
|
},
|
||||||
|
"bio": "Senior engineer at Granify.com",
|
||||||
|
"site": "http://flickfaver.com",
|
||||||
|
"avatar": "https://d1ts43dypk8bqh.cloudfront.net/v1/avatars/d50887ca-a6ce-4e59-b89f-14f0b5d03b03",
|
||||||
|
"employment": {
|
||||||
|
"name": "www.latera.ru",
|
||||||
|
"title": "Software Engineer",
|
||||||
|
"domain": "gmail.com"
|
||||||
|
},
|
||||||
|
"facebook": {
|
||||||
|
"handle": "leonid.bugaev"
|
||||||
|
},
|
||||||
|
"github": {
|
||||||
|
"handle": "buger",
|
||||||
|
"id": 14009,
|
||||||
|
"avatar": "https://avatars.githubusercontent.com/u/14009?v=3",
|
||||||
|
"company": "Granify",
|
||||||
|
"blog": "http://leonsbox.com",
|
||||||
|
"followers": 95,
|
||||||
|
"following": 10
|
||||||
|
},
|
||||||
|
"twitter": {
|
||||||
|
"handle": "flickfaver",
|
||||||
|
"id": 77004410,
|
||||||
|
"bio": null,
|
||||||
|
"followers": 2,
|
||||||
|
"following": 1,
|
||||||
|
"statuses": 5,
|
||||||
|
"favorites": 0,
|
||||||
|
"location": "",
|
||||||
|
"site": "http://flickfaver.com",
|
||||||
|
"avatar": null
|
||||||
|
},
|
||||||
|
"linkedin": {
|
||||||
|
"handle": "in/leonidbugaev"
|
||||||
|
},
|
||||||
|
"googleplus": {
|
||||||
|
"handle": null
|
||||||
|
},
|
||||||
|
"angellist": {
|
||||||
|
"handle": "leonid-bugaev",
|
||||||
|
"id": 61541,
|
||||||
|
"bio": "Senior engineer at Granify.com",
|
||||||
|
"blog": "http://buger.github.com",
|
||||||
|
"site": "http://buger.github.com",
|
||||||
|
"followers": 41,
|
||||||
|
"avatar": "https://d1qb2nb5cznatu.cloudfront.net/users/61541-medium_jpg?1405474390"
|
||||||
|
},
|
||||||
|
"klout": {
|
||||||
|
"handle": null,
|
||||||
|
"score": null
|
||||||
|
},
|
||||||
|
"foursquare": {
|
||||||
|
"handle": null
|
||||||
|
},
|
||||||
|
"aboutme": {
|
||||||
|
"handle": "leonid.bugaev",
|
||||||
|
"bio": null,
|
||||||
|
"avatar": null
|
||||||
|
},
|
||||||
|
"gravatar": {
|
||||||
|
"handle": "buger",
|
||||||
|
"urls": [
|
||||||
|
],
|
||||||
|
"avatar": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510",
|
||||||
|
"avatars": [
|
||||||
|
{
|
||||||
|
"url": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510",
|
||||||
|
"type": "thumbnail"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"fuzzy": false
|
||||||
|
},
|
||||||
|
"company": "hello"
|
||||||
|
}]`), 0666)
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
200000 8886 ns/op 4336 B/op 6 allocs/op
|
||||||
|
50000 34244 ns/op 6744 B/op 14 allocs/op
|
||||||
|
*/
|
||||||
func Benchmark_jsoniter_large_file(b *testing.B) {
|
func Benchmark_jsoniter_large_file(b *testing.B) {
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
file, _ := os.Open("/tmp/large-file.json")
|
file, _ := os.Open("/tmp/large-file.json")
|
||||||
iter := Parse(ConfigDefault, file, 4096)
|
iter := Parse(ConfigDefault, file, 4096)
|
||||||
count := 0
|
count := 0
|
||||||
for iter.ReadArray() {
|
iter.ReadArrayCB(func(iter *Iterator) bool {
|
||||||
|
// Skip() is strict by default, use --tags jsoniter-sloppy to skip without validation
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
count++
|
count++
|
||||||
}
|
return true
|
||||||
|
})
|
||||||
file.Close()
|
file.Close()
|
||||||
|
if iter.Error != nil {
|
||||||
|
b.Error(iter.Error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,6 +149,9 @@ func Benchmark_json_large_file(b *testing.B) {
|
|||||||
bytes, _ := ioutil.ReadAll(file)
|
bytes, _ := ioutil.ReadAll(file)
|
||||||
file.Close()
|
file.Close()
|
||||||
result := []struct{}{}
|
result := []struct{}{}
|
||||||
json.Unmarshal(bytes, &result)
|
err := json.Unmarshal(bytes, &result)
|
||||||
|
if err != nil {
|
||||||
|
b.Error(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,9 +2,11 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"math/big"
|
"math/big"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_read_map(t *testing.T) {
|
func Test_read_map(t *testing.T) {
|
||||||
@ -30,6 +32,13 @@ func Test_map_wrapper_any_get_all(t *testing.T) {
|
|||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
any := Wrap(map[string][]int{"Field1": {1, 2}})
|
any := Wrap(map[string][]int{"Field1": {1, 2}})
|
||||||
should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString())
|
should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString())
|
||||||
|
should.Contains(any.Keys(), "Field1")
|
||||||
|
|
||||||
|
// map write to
|
||||||
|
stream := NewStream(ConfigDefault, nil, 0)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
// TODO cannot pass
|
||||||
|
//should.Equal(string(stream.buf), "")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_val_map(t *testing.T) {
|
func Test_write_val_map(t *testing.T) {
|
||||||
@ -120,3 +129,32 @@ func Test_encode_map_with_sorted_keys(t *testing.T) {
|
|||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(string(bytes), output)
|
should.Equal(string(bytes), output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_encode_map_uint_keys(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
m := map[uint64]interface{}{
|
||||||
|
uint64(1): "a",
|
||||||
|
uint64(2): "a",
|
||||||
|
uint64(4): "a",
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes, err := json.Marshal(m)
|
||||||
|
should.Nil(err)
|
||||||
|
|
||||||
|
output, err := ConfigCompatibleWithStandardLibrary.MarshalToString(m)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(string(bytes), output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_read_map_with_reader(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
input := `{"branch":"beta","change_log":"add the rows{10}","channel":"fros","create_time":"2017-06-13 16:39:08","firmware_list":"","md5":"80dee2bf7305bcf179582088e29fd7b9","note":{"CoreServices":{"md5":"d26975c0a8c7369f70ed699f2855cc2e","package_name":"CoreServices","version_code":"76","version_name":"1.0.76"},"FrDaemon":{"md5":"6b1f0626673200bc2157422cd2103f5d","package_name":"FrDaemon","version_code":"390","version_name":"1.0.390"},"FrGallery":{"md5":"90d767f0f31bcd3c1d27281ec979ba65","package_name":"FrGallery","version_code":"349","version_name":"1.0.349"},"FrLocal":{"md5":"f15a215b2c070a80a01f07bde4f219eb","package_name":"FrLocal","version_code":"791","version_name":"1.0.791"}},"pack_region_urls":{"CN":"https://s3.cn-north-1.amazonaws.com.cn/xxx-os/ttt_xxx_android_1.5.3.344.393.zip","default":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip","local":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip"},"pack_version":"1.5.3.344.393","pack_version_code":393,"region":"all","release_flag":0,"revision":62,"size":38966875,"status":3}`
|
||||||
|
reader := strings.NewReader(input)
|
||||||
|
decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(reader)
|
||||||
|
m1 := map[string]interface{}{}
|
||||||
|
should.Nil(decoder.Decode(&m1))
|
||||||
|
m2 := map[string]interface{}{}
|
||||||
|
should.Nil(json.Unmarshal([]byte(input), &m2))
|
||||||
|
should.Equal(m2, m1)
|
||||||
|
should.Equal("1.0.76", m1["note"].(map[string]interface{})["CoreServices"].(map[string]interface{})["version_name"])
|
||||||
|
}
|
||||||
|
71
jsoniter_must_be_valid_test.go
Normal file
71
jsoniter_must_be_valid_test.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// if must be valid is useless, just drop this test
|
||||||
|
func Test_must_be_valid(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
any := Get([]byte("123"))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 123)
|
||||||
|
|
||||||
|
any = Wrap(int8(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(int16(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(int32(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(int64(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(uint(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(uint8(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(uint16(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(uint32(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(uint64(10))
|
||||||
|
should.Equal(any.MustBeValid().ToInt(), 10)
|
||||||
|
|
||||||
|
any = Wrap(float32(10))
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(10))
|
||||||
|
|
||||||
|
any = Wrap(float64(10))
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(10))
|
||||||
|
|
||||||
|
any = Wrap(true)
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(1))
|
||||||
|
|
||||||
|
any = Wrap(false)
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap(nil)
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap(struct{ age int }{age: 1})
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap(map[string]interface{}{"abc": 1})
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap("abc")
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap([]int{})
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
|
||||||
|
|
||||||
|
any = Wrap([]int{1, 2})
|
||||||
|
should.Equal(any.MustBeValid().ToFloat64(), float64(1))
|
||||||
|
}
|
@ -3,7 +3,8 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
"io"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -13,6 +14,12 @@ func Test_read_null(t *testing.T) {
|
|||||||
should.True(iter.ReadNil())
|
should.True(iter.ReadNil())
|
||||||
iter = ParseString(ConfigDefault, `null`)
|
iter = ParseString(ConfigDefault, `null`)
|
||||||
should.Nil(iter.Read())
|
should.Nil(iter.Read())
|
||||||
|
iter = ParseString(ConfigDefault, `navy`)
|
||||||
|
iter.Read()
|
||||||
|
should.True(iter.Error != nil && iter.Error != io.EOF)
|
||||||
|
iter = ParseString(ConfigDefault, `navy`)
|
||||||
|
iter.ReadNil()
|
||||||
|
should.True(iter.Error != nil && iter.Error != io.EOF)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_null(t *testing.T) {
|
func Test_write_null(t *testing.T) {
|
||||||
@ -32,7 +39,7 @@ func Test_encode_null(t *testing.T) {
|
|||||||
should.Equal("null", str)
|
should.Equal("null", str)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_decode_null_object(t *testing.T) {
|
func Test_decode_null_object_field(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `[null,"a"]`)
|
iter := ParseString(ConfigDefault, `[null,"a"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
@ -51,16 +58,27 @@ func Test_decode_null_object(t *testing.T) {
|
|||||||
should.Len(objs, 1)
|
should.Len(objs, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_decode_null_array(t *testing.T) {
|
func Test_decode_null_array_element(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `[null,"a"]`)
|
iter := ParseString(ConfigDefault, `[null,"a"]`)
|
||||||
iter.ReadArray()
|
should.True(iter.ReadArray())
|
||||||
if iter.ReadArray() != false {
|
should.True(iter.ReadNil())
|
||||||
t.FailNow()
|
should.True(iter.ReadArray())
|
||||||
}
|
should.Equal("a", iter.ReadString())
|
||||||
iter.ReadArray()
|
}
|
||||||
if iter.ReadString() != "a" {
|
|
||||||
t.FailNow()
|
func Test_decode_null_array(t *testing.T) {
|
||||||
}
|
should := require.New(t)
|
||||||
|
arr := []string{}
|
||||||
|
should.Nil(UnmarshalFromString("null", &arr))
|
||||||
|
should.Nil(arr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_null_map(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
arr := map[string]string{}
|
||||||
|
should.Nil(UnmarshalFromString("null", &arr))
|
||||||
|
should.Nil(arr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_decode_null_string(t *testing.T) {
|
func Test_decode_null_string(t *testing.T) {
|
||||||
|
@ -3,8 +3,9 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_empty_object(t *testing.T) {
|
func Test_empty_object(t *testing.T) {
|
||||||
@ -21,27 +22,29 @@ func Test_empty_object(t *testing.T) {
|
|||||||
|
|
||||||
func Test_one_field(t *testing.T) {
|
func Test_one_field(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `{"a": "b"}`)
|
iter := ParseString(ConfigDefault, `{"a": "stream"}`)
|
||||||
field := iter.ReadObject()
|
field := iter.ReadObject()
|
||||||
should.Equal("a", field)
|
should.Equal("a", field)
|
||||||
value := iter.ReadString()
|
value := iter.ReadString()
|
||||||
should.Equal("b", value)
|
should.Equal("stream", value)
|
||||||
field = iter.ReadObject()
|
field = iter.ReadObject()
|
||||||
should.Equal("", field)
|
should.Equal("", field)
|
||||||
iter = ParseString(ConfigDefault, `{"a": "b"}`)
|
iter = ParseString(ConfigDefault, `{"a": "stream"}`)
|
||||||
should.True(iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
should.True(iter.ReadObjectCB(func(iter *Iterator, field string) bool {
|
||||||
should.Equal("a", field)
|
should.Equal("a", field)
|
||||||
|
iter.Skip()
|
||||||
return true
|
return true
|
||||||
}))
|
}))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_two_field(t *testing.T) {
|
func Test_two_field(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `{ "a": "b" , "c": "d" }`)
|
iter := ParseString(ConfigDefault, `{ "a": "stream" , "c": "d" }`)
|
||||||
field := iter.ReadObject()
|
field := iter.ReadObject()
|
||||||
should.Equal("a", field)
|
should.Equal("a", field)
|
||||||
value := iter.ReadString()
|
value := iter.ReadString()
|
||||||
should.Equal("b", value)
|
should.Equal("stream", value)
|
||||||
field = iter.ReadObject()
|
field = iter.ReadObject()
|
||||||
should.Equal("c", field)
|
should.Equal("c", field)
|
||||||
value = iter.ReadString()
|
value = iter.ReadString()
|
||||||
@ -69,6 +72,11 @@ func Test_object_wrapper_any_get_all(t *testing.T) {
|
|||||||
}
|
}
|
||||||
any := Wrap(TestObject{[]int{1, 2}, []int{3, 4}})
|
any := Wrap(TestObject{[]int{1, 2}, []int{3, 4}})
|
||||||
should.Contains(any.Get('*', 0).ToString(), `"Field2":3`)
|
should.Contains(any.Get('*', 0).ToString(), `"Field2":3`)
|
||||||
|
should.Contains(any.Keys(), "Field1")
|
||||||
|
should.Contains(any.Keys(), "Field2")
|
||||||
|
should.NotContains(any.Keys(), "Field3")
|
||||||
|
|
||||||
|
//should.Contains(any.GetObject()["Field1"].GetArray()[0], 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_object(t *testing.T) {
|
func Test_write_object(t *testing.T) {
|
||||||
@ -84,136 +92,7 @@ func Test_write_object(t *testing.T) {
|
|||||||
stream.WriteObjectEnd()
|
stream.WriteObjectEnd()
|
||||||
stream.Flush()
|
stream.Flush()
|
||||||
should.Nil(stream.Error)
|
should.Nil(stream.Error)
|
||||||
should.Equal("{\n \"hello\":1,\n \"world\":2\n}", buf.String())
|
should.Equal("{\n \"hello\": 1,\n \"world\": 2\n}", buf.String())
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_one_field_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"field1": "hello"}`, &obj))
|
|
||||||
should.Equal("hello", obj.Field1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_two_fields_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
Field2 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "b"}`, &obj))
|
|
||||||
should.Equal("a", obj.Field1)
|
|
||||||
should.Equal("b", obj.Field2)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_three_fields_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
Field2 string
|
|
||||||
Field3 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "b", "Field3": "c"}`, &obj))
|
|
||||||
should.Equal("a", obj.Field1)
|
|
||||||
should.Equal("b", obj.Field2)
|
|
||||||
should.Equal("c", obj.Field3)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_four_fields_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
Field2 string
|
|
||||||
Field3 string
|
|
||||||
Field4 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "b", "Field3": "c", "Field4": "d"}`, &obj))
|
|
||||||
should.Equal("a", obj.Field1)
|
|
||||||
should.Equal("b", obj.Field2)
|
|
||||||
should.Equal("c", obj.Field3)
|
|
||||||
should.Equal("d", obj.Field4)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_five_fields_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
Field2 string
|
|
||||||
Field3 string
|
|
||||||
Field4 string
|
|
||||||
Field5 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "b", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
|
|
||||||
should.Equal("a", obj.Field1)
|
|
||||||
should.Equal("b", obj.Field2)
|
|
||||||
should.Equal("c", obj.Field3)
|
|
||||||
should.Equal("d", obj.Field4)
|
|
||||||
should.Equal("e", obj.Field5)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_ten_fields_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string
|
|
||||||
Field2 string
|
|
||||||
Field3 string
|
|
||||||
Field4 string
|
|
||||||
Field5 string
|
|
||||||
Field6 string
|
|
||||||
Field7 string
|
|
||||||
Field8 string
|
|
||||||
Field9 string
|
|
||||||
Field10 string
|
|
||||||
}
|
|
||||||
obj := TestObject{}
|
|
||||||
should.Nil(UnmarshalFromString(`{}`, &obj))
|
|
||||||
should.Equal("", obj.Field1)
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "b", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
|
|
||||||
should.Equal("a", obj.Field1)
|
|
||||||
should.Equal("b", obj.Field2)
|
|
||||||
should.Equal("c", obj.Field3)
|
|
||||||
should.Equal("d", obj.Field4)
|
|
||||||
should.Equal("e", obj.Field5)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_struct_field_with_tag(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 string `json:"field-1"`
|
|
||||||
Field2 string `json:"-"`
|
|
||||||
Field3 int `json:",string"`
|
|
||||||
}
|
|
||||||
obj := TestObject{Field2: "world"}
|
|
||||||
UnmarshalFromString(`{"field-1": "hello", "field2": "", "Field3": "100"}`, &obj)
|
|
||||||
should.Equal("hello", obj.Field1)
|
|
||||||
should.Equal("world", obj.Field2)
|
|
||||||
should.Equal(100, obj.Field3)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_decode_struct_field_with_tag_string(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type TestObject struct {
|
|
||||||
Field1 int `json:",string"`
|
|
||||||
}
|
|
||||||
obj := TestObject{Field1: 100}
|
|
||||||
should.Nil(UnmarshalFromString(`{"Field1": "100"}`, &obj))
|
|
||||||
should.Equal(100, obj.Field1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_write_val_zero_field_struct(t *testing.T) {
|
func Test_write_val_zero_field_struct(t *testing.T) {
|
||||||
@ -242,7 +121,7 @@ func Test_mixed(t *testing.T) {
|
|||||||
type AA struct {
|
type AA struct {
|
||||||
ID int `json:"id"`
|
ID int `json:"id"`
|
||||||
Payload map[string]interface{} `json:"payload"`
|
Payload map[string]interface{} `json:"payload"`
|
||||||
buf *bytes.Buffer `json:"-"`
|
buf *bytes.Buffer
|
||||||
}
|
}
|
||||||
aa := AA{}
|
aa := AA{}
|
||||||
err := UnmarshalFromString(` {"id":1, "payload":{"account":"123","password":"456"}}`, &aa)
|
err := UnmarshalFromString(` {"id":1, "payload":{"account":"123","password":"456"}}`, &aa)
|
||||||
@ -265,6 +144,20 @@ func Test_omit_empty(t *testing.T) {
|
|||||||
should.Equal(`{"field-2":"hello"}`, str)
|
should.Equal(`{"field-2":"hello"}`, str)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_ignore_field_on_not_valid_type(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string `json:"field-1,omitempty"`
|
||||||
|
Field2 func() `json:"-"`
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
obj.Field1 = "hello world"
|
||||||
|
obj.Field2 = func() {}
|
||||||
|
str, err := MarshalToString(&obj)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"field-1":"hello world"}`, str)
|
||||||
|
}
|
||||||
|
|
||||||
func Test_recursive_struct(t *testing.T) {
|
func Test_recursive_struct(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
type TestObject struct {
|
type TestObject struct {
|
||||||
@ -280,29 +173,6 @@ func Test_recursive_struct(t *testing.T) {
|
|||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_one_field_struct(t *testing.T) {
|
|
||||||
should := require.New(t)
|
|
||||||
type YetYetAnotherObject struct {
|
|
||||||
Field string
|
|
||||||
}
|
|
||||||
type YetAnotherObject struct {
|
|
||||||
Field *YetYetAnotherObject
|
|
||||||
}
|
|
||||||
type AnotherObject struct {
|
|
||||||
Field *YetAnotherObject
|
|
||||||
}
|
|
||||||
type TestObject struct {
|
|
||||||
Me *AnotherObject
|
|
||||||
}
|
|
||||||
obj := TestObject{&AnotherObject{&YetAnotherObject{&YetYetAnotherObject{"abc"}}}}
|
|
||||||
str, err := MarshalToString(obj)
|
|
||||||
should.Nil(err)
|
|
||||||
should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str)
|
|
||||||
str, err = MarshalToString(&obj)
|
|
||||||
should.Nil(err)
|
|
||||||
should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_encode_anonymous_struct(t *testing.T) {
|
func Test_encode_anonymous_struct(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
type TestObject struct {
|
type TestObject struct {
|
||||||
@ -349,10 +219,7 @@ func Test_multiple_level_anonymous_struct(t *testing.T) {
|
|||||||
obj := Level3{Level2{Level1{"1"}, "2"}, "3"}
|
obj := Level3{Level2{Level1{"1"}, "2"}, "3"}
|
||||||
output, err := MarshalToString(obj)
|
output, err := MarshalToString(obj)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
fmt.Println(output)
|
should.Equal(`{"Field1":"1","Field2":"2","Field3":"3"}`, output)
|
||||||
should.Contains(output, `"Field1":"1"`)
|
|
||||||
should.Contains(output, `"Field2":"2"`)
|
|
||||||
should.Contains(output, `"Field3":"3"`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_multiple_level_anonymous_struct_with_ptr(t *testing.T) {
|
func Test_multiple_level_anonymous_struct_with_ptr(t *testing.T) {
|
||||||
@ -407,6 +274,35 @@ func Test_shadow_struct_field(t *testing.T) {
|
|||||||
should.Contains(output, `"max_age":20`)
|
should.Contains(output, `"max_age":20`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_embedded_order(t *testing.T) {
|
||||||
|
type A struct {
|
||||||
|
Field2 string
|
||||||
|
}
|
||||||
|
|
||||||
|
type C struct {
|
||||||
|
Field5 string
|
||||||
|
}
|
||||||
|
|
||||||
|
type B struct {
|
||||||
|
Field4 string
|
||||||
|
C
|
||||||
|
Field6 string
|
||||||
|
}
|
||||||
|
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
A
|
||||||
|
Field3 string
|
||||||
|
B
|
||||||
|
Field7 string
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
s := TestObject{}
|
||||||
|
output, err := MarshalToString(s)
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`{"Field1":"","Field2":"","Field3":"","Field4":"","Field5":"","Field6":"","Field7":""}`, output)
|
||||||
|
}
|
||||||
|
|
||||||
func Test_decode_nested(t *testing.T) {
|
func Test_decode_nested(t *testing.T) {
|
||||||
type StructOfString struct {
|
type StructOfString struct {
|
||||||
Field1 string
|
Field1 string
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ package jsoniter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -72,3 +72,17 @@ func Test_encode_map_of_jsoniter_raw_message(t *testing.T) {
|
|||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(`{"hello":[]}`, output)
|
should.Equal(`{"hello":[]}`, output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_marshal_invalid_json_raw_message(t *testing.T) {
|
||||||
|
type A struct {
|
||||||
|
Raw json.RawMessage `json:"raw"`
|
||||||
|
}
|
||||||
|
message := []byte(`{}`)
|
||||||
|
|
||||||
|
a := A{}
|
||||||
|
should := require.New(t)
|
||||||
|
should.Nil(ConfigCompatibleWithStandardLibrary.Unmarshal(message, &a))
|
||||||
|
aout, aouterr := ConfigCompatibleWithStandardLibrary.Marshal(&a)
|
||||||
|
should.Equal(`{"raw":null}`, string(aout))
|
||||||
|
should.Nil(aouterr)
|
||||||
|
}
|
||||||
|
57
jsoniter_reader_test.go
Normal file
57
jsoniter_reader_test.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_reader_and_load_more(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
reader := strings.NewReader(`
|
||||||
|
{
|
||||||
|
"agency": null,
|
||||||
|
"candidateId": 0,
|
||||||
|
"candidate": "Blah Blah",
|
||||||
|
"bookingId": 0,
|
||||||
|
"shiftId": 1,
|
||||||
|
"shiftTypeId": 0,
|
||||||
|
"shift": "Standard",
|
||||||
|
"bonus": 0,
|
||||||
|
"bonusNI": 0,
|
||||||
|
"days": [],
|
||||||
|
"totalHours": 27,
|
||||||
|
"expenses": [],
|
||||||
|
"weekEndingDateSystem": "2016-10-09",
|
||||||
|
"weekEndingDateClient": "2016-10-09",
|
||||||
|
"submittedAt": null,
|
||||||
|
"submittedById": null,
|
||||||
|
"approvedAt": "2016-10-10T18:38:04Z",
|
||||||
|
"approvedById": 0,
|
||||||
|
"authorisedAt": "2016-10-10T18:38:04Z",
|
||||||
|
"authorisedById": 0,
|
||||||
|
"invoicedAt": "2016-10-10T20:00:00Z",
|
||||||
|
"revokedAt": null,
|
||||||
|
"revokedById": null,
|
||||||
|
"revokeReason": null,
|
||||||
|
"rejectedAt": null,
|
||||||
|
"rejectedById": null,
|
||||||
|
"rejectReasonCode": null,
|
||||||
|
"rejectReason": null,
|
||||||
|
"createdAt": "2016-10-03T00:00:00Z",
|
||||||
|
"updatedAt": "2016-11-09T10:26:13Z",
|
||||||
|
"updatedById": null,
|
||||||
|
"overrides": [],
|
||||||
|
"bookingApproverId": null,
|
||||||
|
"bookingApprover": null,
|
||||||
|
"status": "approved"
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(reader)
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(decoder.Decode(&obj))
|
||||||
|
}
|
@ -3,94 +3,105 @@ package jsoniter
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_skip_number(t *testing.T) {
|
func Test_skip_number_in_array(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[-0.12, "b"]`)
|
should := require.New(t)
|
||||||
|
iter := ParseString(ConfigDefault, `[-0.12, "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
should.Nil(iter.Error)
|
||||||
t.FailNow()
|
should.Equal("stream", iter.ReadString())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_skip_string_in_array(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
iter := ParseString(ConfigDefault, `["hello", "stream"]`)
|
||||||
|
iter.ReadArray()
|
||||||
|
iter.Skip()
|
||||||
|
iter.ReadArray()
|
||||||
|
should.Nil(iter.Error)
|
||||||
|
should.Equal("stream", iter.ReadString())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_null(t *testing.T) {
|
func Test_skip_null(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[null , "b"]`)
|
iter := ParseString(ConfigDefault, `[null , "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_true(t *testing.T) {
|
func Test_skip_true(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[true , "b"]`)
|
iter := ParseString(ConfigDefault, `[true , "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_false(t *testing.T) {
|
func Test_skip_false(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[false , "b"]`)
|
iter := ParseString(ConfigDefault, `[false , "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_array(t *testing.T) {
|
func Test_skip_array(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[[1, [2, [3], 4]], "b"]`)
|
iter := ParseString(ConfigDefault, `[[1, [2, [3], 4]], "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_empty_array(t *testing.T) {
|
func Test_skip_empty_array(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[ [ ], "b"]`)
|
iter := ParseString(ConfigDefault, `[ [ ], "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_nested(t *testing.T) {
|
func Test_skip_nested(t *testing.T) {
|
||||||
iter := ParseString(ConfigDefault, `[ {"a" : [{"b": "c"}], "d": 102 }, "b"]`)
|
iter := ParseString(ConfigDefault, `[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
iter.Skip()
|
iter.Skip()
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
if iter.ReadString() != "b" {
|
if iter.ReadString() != "stream" {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_and_return_bytes(t *testing.T) {
|
func Test_skip_and_return_bytes(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, `[ {"a" : [{"b": "c"}], "d": 102 }, "b"]`)
|
iter := ParseString(ConfigDefault, `[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
skipped := iter.SkipAndReturnBytes()
|
skipped := iter.SkipAndReturnBytes()
|
||||||
should.Equal(`{"a" : [{"b": "c"}], "d": 102 }`, string(skipped))
|
should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(skipped))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_skip_and_return_bytes_with_reader(t *testing.T) {
|
func Test_skip_and_return_bytes_with_reader(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := Parse(ConfigDefault, bytes.NewBufferString(`[ {"a" : [{"b": "c"}], "d": 102 }, "b"]`), 4)
|
iter := Parse(ConfigDefault, bytes.NewBufferString(`[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`), 4)
|
||||||
iter.ReadArray()
|
iter.ReadArray()
|
||||||
skipped := iter.SkipAndReturnBytes()
|
skipped := iter.SkipAndReturnBytes()
|
||||||
should.Equal(`{"a" : [{"b": "c"}], "d": 102 }`, string(skipped))
|
should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(skipped))
|
||||||
}
|
}
|
||||||
|
|
||||||
type TestResp struct {
|
type TestResp struct {
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
|
//+build jsoniter-sloppy
|
||||||
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"io"
|
"io"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
@ -1,7 +1,7 @@
|
|||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/json-iterator/go/require"
|
"github.com/stretchr/testify/require"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1,14 +1,73 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
package jsoniter
|
package jsoniter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/json-iterator/go/require"
|
|
||||||
"testing"
|
"testing"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func Test_read_string(t *testing.T) {
|
||||||
|
badInputs := []string{
|
||||||
|
``,
|
||||||
|
`"`,
|
||||||
|
`"\"`,
|
||||||
|
`"\\\"`,
|
||||||
|
"\"\n\"",
|
||||||
|
`"\U0001f64f"`,
|
||||||
|
`"\uD83D\u00"`,
|
||||||
|
}
|
||||||
|
for i := 0; i < 32; i++ {
|
||||||
|
// control characters are invalid
|
||||||
|
badInputs = append(badInputs, string([]byte{'"', byte(i), '"'}))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, input := range badInputs {
|
||||||
|
testReadString(t, input, "", true, "json.Unmarshal", json.Unmarshal)
|
||||||
|
testReadString(t, input, "", true, "jsoniter.Unmarshal", Unmarshal)
|
||||||
|
testReadString(t, input, "", true, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
goodInputs := []struct {
|
||||||
|
input string
|
||||||
|
expectValue string
|
||||||
|
}{
|
||||||
|
{`""`, ""},
|
||||||
|
{`"a"`, "a"},
|
||||||
|
{`null`, ""},
|
||||||
|
{`"Iñtërnâtiônàlizætiøn,💝🐹🌇⛔"`, "Iñtërnâtiônàlizætiøn,💝🐹🌇⛔"},
|
||||||
|
{`"\uD83D"`, string([]byte{239, 191, 189})},
|
||||||
|
{`"\uD83D\\"`, string([]byte{239, 191, 189, '\\'})},
|
||||||
|
{`"\uD83D\ub000"`, string([]byte{239, 191, 189, 235, 128, 128})},
|
||||||
|
{`"\uD83D\ude04"`, "😄"},
|
||||||
|
{`"\uDEADBEEF"`, string([]byte{239, 191, 189, 66, 69, 69, 70})},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range goodInputs {
|
||||||
|
testReadString(t, tc.input, tc.expectValue, false, "json.Unmarshal", json.Unmarshal)
|
||||||
|
testReadString(t, tc.input, tc.expectValue, false, "jsoniter.Unmarshal", Unmarshal)
|
||||||
|
testReadString(t, tc.input, tc.expectValue, false, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReadString(t *testing.T, input string, expectValue string, expectError bool, marshalerName string, marshaler func([]byte, interface{}) error) {
|
||||||
|
var value string
|
||||||
|
err := marshaler([]byte(input), &value)
|
||||||
|
if expectError != (err != nil) {
|
||||||
|
t.Errorf("%q: %s: expected error %v, got %v", input, marshalerName, expectError, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if value != expectValue {
|
||||||
|
t.Errorf("%q: %s: expected %q, got %q", input, marshalerName, expectValue, value)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func Test_read_normal_string(t *testing.T) {
|
func Test_read_normal_string(t *testing.T) {
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
`"0123456789012345678901234567890123456789"`: `0123456789012345678901234567890123456789`,
|
`"0123456789012345678901234567890123456789"`: `0123456789012345678901234567890123456789`,
|
||||||
@ -42,7 +101,16 @@ func Test_read_normal_string(t *testing.T) {
|
|||||||
func Test_read_exotic_string(t *testing.T) {
|
func Test_read_exotic_string(t *testing.T) {
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
`"hel\"lo"`: `hel"lo`,
|
`"hel\"lo"`: `hel"lo`,
|
||||||
`"hel\nlo"`: "hel\nlo",
|
`"hel\\\/lo"`: `hel\/lo`,
|
||||||
|
`"hel\\blo"`: `hel\blo`,
|
||||||
|
`"hel\\\blo"`: "hel\\\blo",
|
||||||
|
`"hel\\nlo"`: `hel\nlo`,
|
||||||
|
`"hel\\\nlo"`: "hel\\\nlo",
|
||||||
|
`"hel\\tlo"`: `hel\tlo`,
|
||||||
|
`"hel\\flo"`: `hel\flo`,
|
||||||
|
`"hel\\\flo"`: "hel\\\flo",
|
||||||
|
`"hel\\\rlo"`: "hel\\\rlo",
|
||||||
|
`"hel\\\tlo"`: "hel\\\tlo",
|
||||||
`"\u4e2d\u6587"`: "中文",
|
`"\u4e2d\u6587"`: "中文",
|
||||||
`"\ud83d\udc4a"`: "\xf0\x9f\x91\x8a", // surrogate
|
`"\ud83d\udc4a"`: "\xf0\x9f\x91\x8a", // surrogate
|
||||||
}
|
}
|
||||||
@ -50,7 +118,9 @@ func Test_read_exotic_string(t *testing.T) {
|
|||||||
t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
iter := ParseString(ConfigDefault, input)
|
iter := ParseString(ConfigDefault, input)
|
||||||
should.Equal(output, iter.ReadString())
|
var v string
|
||||||
|
should.Nil(json.Unmarshal([]byte(input), &v))
|
||||||
|
should.Equal(v, iter.ReadString())
|
||||||
})
|
})
|
||||||
t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) {
|
t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
@ -101,6 +171,10 @@ func Test_html_escape(t *testing.T) {
|
|||||||
output, err = ConfigCompatibleWithStandardLibrary.Marshal(`>`)
|
output, err = ConfigCompatibleWithStandardLibrary.Marshal(`>`)
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal(`"\u003e"`, string(output))
|
should.Equal(`"\u003e"`, string(output))
|
||||||
|
type MyString string
|
||||||
|
output, err = ConfigCompatibleWithStandardLibrary.Marshal(MyString(`>`))
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`"\u003e"`, string(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_string_encode_with_std(t *testing.T) {
|
func Test_string_encode_with_std(t *testing.T) {
|
||||||
@ -117,23 +191,33 @@ func Test_string_encode_with_std(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_string_encode_with_std_without_html_escape(t *testing.T) {
|
func Test_unicode(t *testing.T) {
|
||||||
api := Config{EscapeHtml: false}.Froze()
|
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
for i := 0; i < utf8.RuneSelf; i++ {
|
output, _ := MarshalToString(map[string]interface{}{"a": "数字山谷"})
|
||||||
input := string([]byte{byte(i)})
|
should.Equal(`{"a":"数字山谷"}`, output)
|
||||||
buf := &bytes.Buffer{}
|
output, _ = Config{EscapeHTML: false}.Froze().MarshalToString(map[string]interface{}{"a": "数字山谷"})
|
||||||
encoder := json.NewEncoder(buf)
|
should.Equal(`{"a":"数字山谷"}`, output)
|
||||||
encoder.SetEscapeHTML(false)
|
}
|
||||||
err := encoder.Encode(input)
|
|
||||||
should.Nil(err)
|
func Test_unicode_and_escape(t *testing.T) {
|
||||||
stdOutput := buf.String()
|
should := require.New(t)
|
||||||
stdOutput = stdOutput[:len(stdOutput)-1]
|
output, err := MarshalToString(`"数字山谷"`)
|
||||||
jsoniterOutputBytes, err := api.Marshal(input)
|
should.Nil(err)
|
||||||
should.Nil(err)
|
should.Equal(`"\"数字山谷\""`, output)
|
||||||
jsoniterOutput := string(jsoniterOutputBytes)
|
output, err = ConfigFastest.MarshalToString(`"数字山谷"`)
|
||||||
should.Equal(stdOutput, jsoniterOutput)
|
should.Nil(err)
|
||||||
}
|
should.Equal(`"\"数字山谷\""`, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_unsafe_unicode(t *testing.T) {
|
||||||
|
ConfigDefault.(*frozenConfig).cleanEncoders()
|
||||||
|
should := require.New(t)
|
||||||
|
output, err := ConfigDefault.MarshalToString("he\u2029\u2028he")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal(`"he\u2029\u2028he"`, output)
|
||||||
|
output, err = ConfigFastest.MarshalToString("he\u2029\u2028he")
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("\"he\u2029\u2028he\"", output)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_jsoniter_unicode(b *testing.B) {
|
func Benchmark_jsoniter_unicode(b *testing.B) {
|
||||||
|
267
jsoniter_struct_decoder_test.go
Normal file
267
jsoniter_struct_decoder_test.go
Normal file
@ -0,0 +1,267 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_decode_one_field_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"field1": "hello"}`, &obj))
|
||||||
|
should.Equal("hello", obj.Field1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_two_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_three_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_four_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_five_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_six_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal("x", obj.Field6)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_seven_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
Field7 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal("x", obj.Field6)
|
||||||
|
should.Equal("y", obj.Field7)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_eight_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
Field7 string
|
||||||
|
Field8 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field8":"1", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal("x", obj.Field6)
|
||||||
|
should.Equal("y", obj.Field7)
|
||||||
|
should.Equal("1", obj.Field8)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_nine_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
Field7 string
|
||||||
|
Field8 string
|
||||||
|
Field9 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field8" : "zzzzzzzzzzz", "Field7": "zz", "Field6" : "xx", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field9":"f"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal("xx", obj.Field6)
|
||||||
|
should.Equal("zz", obj.Field7)
|
||||||
|
should.Equal("zzzzzzzzzzz", obj.Field8)
|
||||||
|
should.Equal("f", obj.Field9)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_ten_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
Field7 string
|
||||||
|
Field8 string
|
||||||
|
Field9 string
|
||||||
|
Field10 string
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field10":"x", "Field9": "x", "Field8":"x", "Field7":"x", "Field6":"x", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal("x", obj.Field6)
|
||||||
|
should.Equal("x", obj.Field7)
|
||||||
|
should.Equal("x", obj.Field8)
|
||||||
|
should.Equal("x", obj.Field9)
|
||||||
|
should.Equal("x", obj.Field10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_more_than_ten_fields_struct(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
Field3 string
|
||||||
|
Field4 string
|
||||||
|
Field5 string
|
||||||
|
Field6 string
|
||||||
|
Field7 string
|
||||||
|
Field8 string
|
||||||
|
Field9 string
|
||||||
|
Field10 string
|
||||||
|
Field11 int
|
||||||
|
}
|
||||||
|
obj := TestObject{}
|
||||||
|
should.Nil(UnmarshalFromString(`{}`, &obj))
|
||||||
|
should.Equal("", obj.Field1)
|
||||||
|
should.Nil(UnmarshalFromString(`{"field11":1, "field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
|
||||||
|
should.Equal("a", obj.Field1)
|
||||||
|
should.Equal("stream", obj.Field2)
|
||||||
|
should.Equal("c", obj.Field3)
|
||||||
|
should.Equal("d", obj.Field4)
|
||||||
|
should.Equal("e", obj.Field5)
|
||||||
|
should.Equal(1, obj.Field11)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_struct_field_with_tag(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 string `json:"field-1"`
|
||||||
|
Field2 string `json:"-"`
|
||||||
|
Field3 int `json:",string"`
|
||||||
|
}
|
||||||
|
obj := TestObject{Field2: "world"}
|
||||||
|
UnmarshalFromString(`{"field-1": "hello", "field2": "", "Field3": "100"}`, &obj)
|
||||||
|
should.Equal("hello", obj.Field1)
|
||||||
|
should.Equal("world", obj.Field2)
|
||||||
|
should.Equal(100, obj.Field3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_decode_struct_field_with_tag_string(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
type TestObject struct {
|
||||||
|
Field1 int `json:",string"`
|
||||||
|
}
|
||||||
|
obj := TestObject{Field1: 100}
|
||||||
|
should.Nil(UnmarshalFromString(`{"Field1": "100"}`, &obj))
|
||||||
|
should.Equal(100, obj.Field1)
|
||||||
|
}
|
118
jsoniter_wrap_test.go
Normal file
118
jsoniter_wrap_test.go
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_wrap_and_valuetype_everything(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
var i interface{}
|
||||||
|
any := Get([]byte("123"))
|
||||||
|
// default of number type is float64
|
||||||
|
i = float64(123)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(int8(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
// get interface is not int8 interface
|
||||||
|
// i = int8(10)
|
||||||
|
// should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(int16(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
//i = int16(10)
|
||||||
|
//should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(int32(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = int32(10)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(int64(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = int64(10)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(uint(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
// not equal
|
||||||
|
//i = uint(10)
|
||||||
|
//should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(uint8(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
// not equal
|
||||||
|
// i = uint8(10)
|
||||||
|
// should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(uint16(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
any = Wrap(uint32(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = uint32(10)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(uint64(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = uint64(10)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(float32(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
// not equal
|
||||||
|
//i = float32(10)
|
||||||
|
//should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(float64(10))
|
||||||
|
should.Equal(any.ValueType(), NumberValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = float64(10)
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(true)
|
||||||
|
should.Equal(any.ValueType(), BoolValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = true
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
any = Wrap(false)
|
||||||
|
should.Equal(any.ValueType(), BoolValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = false
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(nil)
|
||||||
|
should.Equal(any.ValueType(), NilValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = nil
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
stream := NewStream(ConfigDefault, nil, 32)
|
||||||
|
any.WriteTo(stream)
|
||||||
|
should.Equal("null", string(stream.Buffer()))
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
|
||||||
|
any = Wrap(struct{ age int }{age: 1})
|
||||||
|
should.Equal(any.ValueType(), ObjectValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = struct{ age int }{age: 1}
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap(map[string]interface{}{"abc": 1})
|
||||||
|
should.Equal(any.ValueType(), ObjectValue)
|
||||||
|
should.Equal(any.LastError(), nil)
|
||||||
|
i = map[string]interface{}{"abc": 1}
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
|
||||||
|
any = Wrap("abc")
|
||||||
|
i = "abc"
|
||||||
|
should.Equal(i, any.GetInterface())
|
||||||
|
should.Equal(nil, any.LastError())
|
||||||
|
|
||||||
|
}
|
152
output_tests/array/array/bool/json_test.go
Normal file
152
output_tests/array/array/bool/json_test.go
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/davecgh/go-spew/spew"
|
||||||
|
fuzz "github.com/google/gofuzz"
|
||||||
|
jsoniter "github.com/json-iterator/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Roundtrip(t *testing.T) {
|
||||||
|
fz := fuzz.New().MaxDepth(10).NilChance(0.3)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
var before typeForTest
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
|
||||||
|
jbStd, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with stdlib: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbStd))) == 0 {
|
||||||
|
t.Fatal("stdlib marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with jsoniter: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbIter))) == 0 {
|
||||||
|
t.Fatal("jsoniter marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
if string(jbStd) != string(jbIter) {
|
||||||
|
t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s",
|
||||||
|
indent(jbStd, " "), indent(jbIter, " "), dump(before))
|
||||||
|
}
|
||||||
|
|
||||||
|
var afterStd typeForTest
|
||||||
|
err = json.Unmarshal(jbIter, &afterStd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
var afterIter typeForTest
|
||||||
|
err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
if fingerprint(afterStd) != fingerprint(afterIter) {
|
||||||
|
t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s",
|
||||||
|
dump(afterStd), dump(afterIter), indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indentStr = "> "
|
||||||
|
|
||||||
|
func fingerprint(obj interface{}) string {
|
||||||
|
c := spew.ConfigState{
|
||||||
|
SortKeys: true,
|
||||||
|
SpewKeys: true,
|
||||||
|
}
|
||||||
|
return c.Sprintf("%v", obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dump(obj interface{}) string {
|
||||||
|
cfg := spew.ConfigState{
|
||||||
|
Indent: indentStr,
|
||||||
|
}
|
||||||
|
return cfg.Sdump(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func indent(src []byte, prefix string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := json.Indent(&buf, src, prefix, indentStr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("!!! %v", err)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var obj typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&obj)
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
jb, err := fn(obj)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err)
|
||||||
|
}
|
||||||
|
_ = jb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var before typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
jb, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
var after typeForTest
|
||||||
|
err = fn(jb, &after)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardMarshal(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "stdlib", json.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardUnmarshal(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "stdlib", json.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalFastest(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalFastest(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalDefault(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalDefault(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
3
output_tests/array/array/bool/types.go
Normal file
3
output_tests/array/array/bool/types.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
type typeForTest [4][4]bool
|
152
output_tests/array/array/byte/json_test.go
Normal file
152
output_tests/array/array/byte/json_test.go
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/davecgh/go-spew/spew"
|
||||||
|
fuzz "github.com/google/gofuzz"
|
||||||
|
jsoniter "github.com/json-iterator/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Roundtrip(t *testing.T) {
|
||||||
|
fz := fuzz.New().MaxDepth(10).NilChance(0.3)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
var before typeForTest
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
|
||||||
|
jbStd, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with stdlib: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbStd))) == 0 {
|
||||||
|
t.Fatal("stdlib marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with jsoniter: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbIter))) == 0 {
|
||||||
|
t.Fatal("jsoniter marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
if string(jbStd) != string(jbIter) {
|
||||||
|
t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s",
|
||||||
|
indent(jbStd, " "), indent(jbIter, " "), dump(before))
|
||||||
|
}
|
||||||
|
|
||||||
|
var afterStd typeForTest
|
||||||
|
err = json.Unmarshal(jbIter, &afterStd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
var afterIter typeForTest
|
||||||
|
err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
if fingerprint(afterStd) != fingerprint(afterIter) {
|
||||||
|
t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s",
|
||||||
|
dump(afterStd), dump(afterIter), indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indentStr = "> "
|
||||||
|
|
||||||
|
func fingerprint(obj interface{}) string {
|
||||||
|
c := spew.ConfigState{
|
||||||
|
SortKeys: true,
|
||||||
|
SpewKeys: true,
|
||||||
|
}
|
||||||
|
return c.Sprintf("%v", obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dump(obj interface{}) string {
|
||||||
|
cfg := spew.ConfigState{
|
||||||
|
Indent: indentStr,
|
||||||
|
}
|
||||||
|
return cfg.Sdump(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func indent(src []byte, prefix string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := json.Indent(&buf, src, prefix, indentStr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("!!! %v", err)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var obj typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&obj)
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
jb, err := fn(obj)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err)
|
||||||
|
}
|
||||||
|
_ = jb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var before typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
jb, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
var after typeForTest
|
||||||
|
err = fn(jb, &after)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardMarshal(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "stdlib", json.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardUnmarshal(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "stdlib", json.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalFastest(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalFastest(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalDefault(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalDefault(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
3
output_tests/array/array/byte/types.go
Normal file
3
output_tests/array/array/byte/types.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
type typeForTest [4][4]byte
|
152
output_tests/array/array/float64/json_test.go
Normal file
152
output_tests/array/array/float64/json_test.go
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/davecgh/go-spew/spew"
|
||||||
|
fuzz "github.com/google/gofuzz"
|
||||||
|
jsoniter "github.com/json-iterator/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Roundtrip(t *testing.T) {
|
||||||
|
fz := fuzz.New().MaxDepth(10).NilChance(0.3)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
var before typeForTest
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
|
||||||
|
jbStd, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with stdlib: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbStd))) == 0 {
|
||||||
|
t.Fatal("stdlib marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with jsoniter: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbIter))) == 0 {
|
||||||
|
t.Fatal("jsoniter marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
if string(jbStd) != string(jbIter) {
|
||||||
|
t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s",
|
||||||
|
indent(jbStd, " "), indent(jbIter, " "), dump(before))
|
||||||
|
}
|
||||||
|
|
||||||
|
var afterStd typeForTest
|
||||||
|
err = json.Unmarshal(jbIter, &afterStd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
var afterIter typeForTest
|
||||||
|
err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
if fingerprint(afterStd) != fingerprint(afterIter) {
|
||||||
|
t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s",
|
||||||
|
dump(afterStd), dump(afterIter), indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indentStr = "> "
|
||||||
|
|
||||||
|
func fingerprint(obj interface{}) string {
|
||||||
|
c := spew.ConfigState{
|
||||||
|
SortKeys: true,
|
||||||
|
SpewKeys: true,
|
||||||
|
}
|
||||||
|
return c.Sprintf("%v", obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dump(obj interface{}) string {
|
||||||
|
cfg := spew.ConfigState{
|
||||||
|
Indent: indentStr,
|
||||||
|
}
|
||||||
|
return cfg.Sdump(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func indent(src []byte, prefix string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := json.Indent(&buf, src, prefix, indentStr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("!!! %v", err)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var obj typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&obj)
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
jb, err := fn(obj)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err)
|
||||||
|
}
|
||||||
|
_ = jb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var before typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
jb, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
var after typeForTest
|
||||||
|
err = fn(jb, &after)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardMarshal(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "stdlib", json.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardUnmarshal(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "stdlib", json.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalFastest(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalFastest(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalDefault(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalDefault(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
3
output_tests/array/array/float64/types.go
Normal file
3
output_tests/array/array/float64/types.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
type typeForTest [4][4]float64
|
152
output_tests/array/array/int32/json_test.go
Normal file
152
output_tests/array/array/int32/json_test.go
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/davecgh/go-spew/spew"
|
||||||
|
fuzz "github.com/google/gofuzz"
|
||||||
|
jsoniter "github.com/json-iterator/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Roundtrip(t *testing.T) {
|
||||||
|
fz := fuzz.New().MaxDepth(10).NilChance(0.3)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
var before typeForTest
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
|
||||||
|
jbStd, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with stdlib: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbStd))) == 0 {
|
||||||
|
t.Fatal("stdlib marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal with jsoniter: %v", err)
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(jbIter))) == 0 {
|
||||||
|
t.Fatal("jsoniter marshal produced empty result and no error")
|
||||||
|
}
|
||||||
|
if string(jbStd) != string(jbIter) {
|
||||||
|
t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s",
|
||||||
|
indent(jbStd, " "), indent(jbIter, " "), dump(before))
|
||||||
|
}
|
||||||
|
|
||||||
|
var afterStd typeForTest
|
||||||
|
err = json.Unmarshal(jbIter, &afterStd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
var afterIter typeForTest
|
||||||
|
err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s",
|
||||||
|
err, indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
if fingerprint(afterStd) != fingerprint(afterIter) {
|
||||||
|
t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s",
|
||||||
|
dump(afterStd), dump(afterIter), indent(jbIter, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indentStr = "> "
|
||||||
|
|
||||||
|
func fingerprint(obj interface{}) string {
|
||||||
|
c := spew.ConfigState{
|
||||||
|
SortKeys: true,
|
||||||
|
SpewKeys: true,
|
||||||
|
}
|
||||||
|
return c.Sprintf("%v", obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dump(obj interface{}) string {
|
||||||
|
cfg := spew.ConfigState{
|
||||||
|
Indent: indentStr,
|
||||||
|
}
|
||||||
|
return cfg.Sdump(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func indent(src []byte, prefix string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := json.Indent(&buf, src, prefix, indentStr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("!!! %v", err)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var obj typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&obj)
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
jb, err := fn(obj)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err)
|
||||||
|
}
|
||||||
|
_ = jb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) {
|
||||||
|
t.ReportAllocs()
|
||||||
|
t.ResetTimer()
|
||||||
|
|
||||||
|
var before typeForTest
|
||||||
|
fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3)
|
||||||
|
fz.Fuzz(&before)
|
||||||
|
jb, err := json.Marshal(before)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < t.N; i++ {
|
||||||
|
var after typeForTest
|
||||||
|
err = fn(jb, &after)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardMarshal(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "stdlib", json.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStandardUnmarshal(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "stdlib", json.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalFastest(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalFastest(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalDefault(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalDefault(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterMarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) {
|
||||||
|
benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal)
|
||||||
|
}
|
3
output_tests/array/array/int32/types.go
Normal file
3
output_tests/array/array/int32/types.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
type typeForTest [4][4]int32
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user