diff --git a/.github/workflows/benchmark-linux-arm64.yml b/.github/workflows/benchmark-linux-arm64.yml index 8027e6077..9dbcab5b4 100644 --- a/.github/workflows/benchmark-linux-arm64.yml +++ b/.github/workflows/benchmark-linux-arm64.yml @@ -14,7 +14,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.17.1 + go-version: 1.22 - uses: actions/cache@v2 with: diff --git a/.github/workflows/benchmark-linux-x64.yml b/.github/workflows/benchmark-linux-x64.yml index 41f271434..47d1bfb0a 100644 --- a/.github/workflows/benchmark-linux-x64.yml +++ b/.github/workflows/benchmark-linux-x64.yml @@ -14,7 +14,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.17.1 + go-version: 1.22 - uses: actions/cache@v2 with: diff --git a/.github/workflows/compatibility_test-windows.yml b/.github/workflows/compatibility_test-windows.yml index 2c07c8141..e854c8fe1 100644 --- a/.github/workflows/compatibility_test-windows.yml +++ b/.github/workflows/compatibility_test-windows.yml @@ -6,7 +6,7 @@ jobs: build: strategy: matrix: - go-version: [1.17.x, 1.21.x] + go-version: [1.17.x, 1.22.x] runs-on: windows-latest steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/compatibility_test.yml b/.github/workflows/compatibility_test.yml index 954f5a2b7..cb4b23d4b 100644 --- a/.github/workflows/compatibility_test.yml +++ b/.github/workflows/compatibility_test.yml @@ -6,7 +6,7 @@ jobs: build: strategy: matrix: - go-version: [1.15.x, 1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x, 1.21.x] + go-version: [1.15.x, 1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x, 1.21.x, 1.22.x] os: [arm, X64] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/unit_test-linux-x64.yml b/.github/workflows/unit_test-linux-x64.yml index bdc597aff..35acd33db 100644 --- a/.github/workflows/unit_test-linux-x64.yml +++ b/.github/workflows/unit_test-linux-x64.yml @@ -6,7 +6,7 @@ jobs: build: strategy: matrix: - go-version: [1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x, 1.21.x] + go-version: [1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x, 1.21.x, 1.22.x] runs-on: [self-hosted, X64] steps: - name: Clear repository diff --git a/README.md b/README.md index 9527b71fe..a74fc4968 100644 --- a/README.md +++ b/README.md @@ -5,21 +5,27 @@ English | [中文](README_ZH_CN.md) A blazingly fast JSON serializing & deserializing library, accelerated by JIT (just-in-time compiling) and SIMD (single-instruction-multiple-data). ## Requirement -- Go 1.16~1.21 + +- Go 1.16~1.22 - Linux / MacOS / Windows(need go1.17 above) - Amd64 ARCH ## Features + - Runtime object binding without code generation - Complete APIs for JSON value manipulation - Fast, fast, fast! ## APIs + see [go.dev](https://pkg.go.dev/github.com/bytedance/sonic) ## Benchmarks + For **all sizes** of json and **all scenarios** of usage, **Sonic performs best**. + - [Medium](https://github.com/bytedance/sonic/blob/main/decoder/testdata_test.go#L19) (13KB, 300+ key, 6 layers) + ```powershell goversion: 1.17.1 goos: darwin @@ -84,6 +90,7 @@ BenchmarkLoadNode_Parallel/LoadAll()-16 5493 ns/op 2370.6 BenchmarkLoadNode/Interface()-16 17722 ns/op 734.85 MB/s 13323 B/op 88 allocs/op BenchmarkLoadNode_Parallel/Interface()-16 10330 ns/op 1260.70 MB/s 15178 B/op 88 allocs/op ``` + - [Small](https://github.com/bytedance/sonic/blob/main/testdata/small.go) (400B, 11 keys, 3 layers) ![small benchmarks](./docs/imgs/bench-small.png) - [Large](https://github.com/bytedance/sonic/blob/main/testdata/twitter.json) (635KB, 10000+ key, 6 layers) @@ -92,6 +99,7 @@ BenchmarkLoadNode_Parallel/Interface()-16 10330 ns/op 1260.7 See [bench.sh](https://github.com/bytedance/sonic/blob/main/scripts/bench.sh) for benchmark codes. ## How it works + See [INTRODUCTION.md](./docs/INTRODUCTION.md). ## Usage @@ -99,6 +107,7 @@ See [INTRODUCTION.md](./docs/INTRODUCTION.md). ### Marshal/Unmarshal Default behaviors are mostly consistent with `encoding/json`, except HTML escaping form (see [Escape HTML](https://github.com/bytedance/sonic/blob/main/README.md#escape-html)) and `SortKeys` feature (optional support see [Sort Keys](https://github.com/bytedance/sonic/blob/main/README.md#sort-keys)) that is **NOT** in conformity to [RFC8259](https://datatracker.ietf.org/doc/html/rfc8259). + ```go import "github.com/bytedance/sonic" @@ -110,8 +119,11 @@ err := sonic.Unmarshal(output, &data) ``` ### Streaming IO + Sonic supports decoding json from `io.Reader` or encoding objects into `io.Writer`, aims at handling multiple values as well as reducing memory consumption. + - encoder + ```go var o1 = map[string]interface{}{ "a": "b", @@ -126,7 +138,9 @@ fmt.Println(w.String()) // {"a":"b"} // 1 ``` + - decoder + ```go var o = map[string]interface{}{} var r = strings.NewReader(`{"a":"b"}{"1":"2"}`) @@ -139,6 +153,7 @@ fmt.Printf("%+v", o) ``` ### Use Number/Use Int64 + ```go import "github.com/bytedance/sonic/decoder" @@ -167,7 +182,9 @@ fm := root.Interface().(float64) // jn == jm ``` ### Sort Keys + On account of the performance loss from sorting (roughly 10%), sonic doesn't enable this feature by default. If your component depends on it to work (like [zstd](https://github.com/facebook/zstd)), Use it like this: + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/encoder" @@ -180,19 +197,26 @@ v, err := encoder.Encode(m, encoder.SortMapKeys) var root := sonic.Get(JSON) err := root.SortKeys() ``` + ### Escape HTML + On account of the performance loss (roughly 15%), sonic doesn't enable this feature by default. You can use `encoder.EscapeHTML` option to open this feature (align with `encoding/json.HTMLEscape`). + ```go import "github.com/bytedance/sonic" v := map[string]string{"&&":"<>"} ret, err := Encode(v, EscapeHTML) // ret == `{"\u0026\u0026":{"X":"\u003c\u003e"}}` ``` + ### Compact Format + Sonic encodes primitive objects (struct/map...) as compact-format JSON by default, except marshaling `json.RawMessage` or `json.Marshaler`: sonic ensures validating their output JSON but **DONOT** compacting them for performance concerns. We provide the option `encoder.CompactMarshaler` to add compacting process. ### Print Error + If there invalid syntax in input JSON, sonic will return `decoder.SyntaxError`, which supports pretty-printing of error position + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/decoder" @@ -218,7 +242,9 @@ if err != nil { ``` #### Mismatched Types [Sonic v1.6.0] + If there a **mismatch-typed** value for a given key, sonic will report `decoder.MismatchTypeError` (if there are many, report the last one), but still skip wrong the value and keep decoding next JSON. + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/decoder" @@ -231,10 +257,15 @@ err := UnmarshalString(`{"A":"1","B":1}`, &data) println(err.Error()) // Mismatch type int with value string "at index 5: mismatched type with value\n\n\t{\"A\":\"1\",\"B\":1}\n\t.....^.........\n" fmt.Printf("%+v", data) // {A:0 B:1} ``` + ### Ast.Node + Sonic/ast.Node is a completely self-contained AST for JSON. It implements serialization and deserialization both and provides robust APIs for obtaining and modification of generic data. + #### Get/Index + Search partial JSON by given paths, which must be non-negative integer or string, or nil + ```go import "github.com/bytedance/sonic" @@ -248,10 +279,13 @@ raw := root.Raw() // == string(input) root, err := sonic.Get(input, "key1", 1, "key2") sub := root.Get("key3").Index(2).Int64() // == 3 ``` + **Tip**: since `Index()` uses offset to locate data, which is much faster than scanning like `Get()`, we suggest you use it as much as possible. And sonic also provides another API `IndexOrGet()` to underlying use offset as well as ensure the key is matched. #### Set/Unset + Modify the json content by Set()/Unset() + ```go import "github.com/bytedance/sonic" @@ -268,7 +302,9 @@ println(root.Get("key4").Check()) // "value not exist" ``` #### Serialize + To encode `ast.Node` as json, use `MarshalJson()` or `json.Marshal()` (MUST pass the node's pointer) + ```go import ( "encoding/json" @@ -282,6 +318,7 @@ println(string(buf) == string(exp)) // true ``` #### APIs + - validation: `Check()`, `Error()`, `Valid()`, `Exist()` - searching: `Index()`, `Get()`, `IndexPair()`, `IndexOrGet()`, `GetByPath()` - go-type casting: `Int64()`, `Float64()`, `String()`, `Number()`, `Bool()`, `Map[UseNumber|UseNode]()`, `Array[UseNumber|UseNode]()`, `Interface[UseNumber|UseNode]()` @@ -290,7 +327,9 @@ println(string(buf) == string(exp)) // true - modification: `Set()`, `SetByIndex()`, `Add()` ### Ast.Visitor + Sonic provides an advanced API for fully parsing JSON into non-standard types (neither `struct` not `map[string]interface{}`) without using any intermediate representation (`ast.Node` or `interface{}`). For example, you might have the following types which are like `interface{}` but actually not `interface{}`: + ```go type UserNode interface {} @@ -305,7 +344,9 @@ type ( UserArray struct{ Value []UserNode } ) ``` + Sonic provides the following API to return **the preorder traversal of a JSON AST**. The `ast.Visitor` is a SAX style interface which is used in some C++ JSON library. You should implement `ast.Visitor` by yourself and pass it to `ast.Preorder()` method. In your visitor you can make your custom types to represent JSON values. There may be an O(n) space container (such as stack) in your visitor to record the object / array hierarchy. + ```go func Preorder(str string, visitor Visitor, opts *VisitorOptions) error @@ -326,12 +367,14 @@ type Visitor interface { See [ast/visitor.go](https://github.com/bytedance/sonic/blob/main/ast/visitor.go) for detailed usage. We also implement a demo visitor for `UserNode` in [ast/visitor_test.go](https://github.com/bytedance/sonic/blob/main/ast/visitor_test.go). ## Compatibility + Sonic **DOES NOT** ensure to support all environments, due to the difficulty of developing high-performance codes. For developers who use sonic to build their applications in different environments, we have the following suggestions: - Developing on **Mac M1**: Make sure you have Rosetta 2 installed on your machine, and set `GOARCH=amd64` when building your application. Rosetta 2 can automatically translate x86 binaries to arm64 binaries and run x86 applications on Mac M1. - Developing on **Linux arm64**: You can install qemu and use the `qemu-x86_64 -cpu max` command to convert x86 binaries to amr64 binaries for applications built with sonic. The qemu can achieve a similar transfer effect to Rosetta 2 on Mac M1. For developers who want to use sonic on Linux arm64 without qemu, or those who want to handle JSON strictly consistent with `encoding/json`, we provide some compatible APIs as `sonic.API` + - `ConfigDefault`: the sonic's default config (`EscapeHTML=false`,`SortKeys=false`...) to run on sonic-supporting environment. It will fall back to `encoding/json` with the corresponding config, and some options like `SortKeys=false` will be invalid. - `ConfigStd`: the std-compatible config (`EscapeHTML=true`,`SortKeys=true`...) to run on sonic-supporting environment. It will fall back to `encoding/json`. - `ConfigFastest`: the fastest config (`NoQuoteTextMarshaler=true`) to run on sonic-supporting environment. It will fall back to `encoding/json` with the corresponding config, and some options will be invalid. @@ -339,7 +382,9 @@ For developers who want to use sonic on Linux arm64 without qemu, or those who w ## Tips ### Pretouch + Since Sonic uses [golang-asm](https://github.com/twitchyliquid64/golang-asm) as a JIT assembler, which is NOT very suitable for runtime compiling, first-hit running of a huge schema may cause request-timeout or even process-OOM. For better stability, we advise **using `Pretouch()` for huge-schema or compact-memory applications** before `Marshal()/Unmarshal()`. + ```go import ( "reflect" @@ -365,18 +410,23 @@ func init() { ``` ### Copy string + When decoding **string values without any escaped characters**, sonic references them from the origin JSON buffer instead of mallocing a new buffer to copy. This helps a lot for CPU performance but may leave the whole JSON buffer in memory as long as the decoded objects are being used. In practice, we found the extra memory introduced by referring JSON buffer is usually 20% ~ 80% of decoded objects. Once an application holds these objects for a long time (for example, cache the decoded objects for reusing), its in-use memory on the server may go up. - `Config.CopyString`/`decoder.CopyString()`: We provide the option for `Decode()` / `Unmarshal()` users to choose not to reference the JSON buffer, which may cause a decline in CPU performance to some degree. + - `GetFromStringNoCopy()`: For memory safty, `sonic.Get()` / `sonic.GetFromString()` now copies return JSON. If users want to get json more quickly and not care about memory usage, you can use `GetFromStringNoCopy()` to return a JSON direclty referenced from source. ### Pass string or []byte? + For alignment to `encoding/json`, we provide API to pass `[]byte` as an argument, but the string-to-bytes copy is conducted at the same time considering safety, which may lose performance when the origin JSON is huge. Therefore, you can use `UnmarshalString()` and `GetFromString()` to pass a string, as long as your origin data is a string or **nocopy-cast** is safe for your []byte. We also provide API `MarshalString()` for convenient **nocopy-cast** of encoded JSON []byte, which is safe since sonic's output bytes is always duplicated and unique. ### Accelerate `encoding.TextMarshaler` -To ensure data security, sonic.Encoder quotes and escapes string values from `encoding.TextMarshaler` interfaces by default, which may degrade performance much if most of your data is in form of them. We provide `encoder.NoQuoteTextMarshaler` to skip these operations, which means you **MUST** ensure their output string escaped and quoted following [RFC8259](https://datatracker.ietf.org/doc/html/rfc8259). +To ensure data security, sonic.Encoder quotes and escapes string values from `encoding.TextMarshaler` interfaces by default, which may degrade performance much if most of your data is in form of them. We provide `encoder.NoQuoteTextMarshaler` to skip these operations, which means you **MUST** ensure their output string escaped and quoted following [RFC8259](https://datatracker.ietf.org/doc/html/rfc8259). ### Better performance for generic data + In **fully-parsed** scenario, `Unmarshal()` performs better than `Get()`+`Node.Interface()`. But if you only have a part of the schema for specific json, you can combine `Get()` and `Unmarshal()` together: + ```go import "github.com/bytedance/sonic" @@ -384,7 +434,9 @@ node, err := sonic.GetFromString(_TwitterJson, "statuses", 3, "user") var user User // your partial schema... err = sonic.UnmarshalString(node.Raw(), &user) ``` + Even if you don't have any schema, use `ast.Node` as the container of generic values instead of `map` or `interface`: + ```go import "github.com/bytedance/sonic" @@ -395,7 +447,9 @@ err = user.Check() // err = user.LoadAll() // only call this when you want to use 'user' concurrently... go someFunc(user) ``` + Why? Because `ast.Node` stores its children using `array`: + - `Array`'s performance is **much better** than `Map` when Inserting (Deserialize) and Scanning (Serialize) data; - **Hashing** (`map[x]`) is not as efficient as **Indexing** (`array[x]`), which `ast.Node` can conduct on **both array and object**; - Using `Interface()`/`Map()` means Sonic must parse all the underlying values, while `ast.Node` can parse them **on demand**. @@ -403,6 +457,7 @@ Why? Because `ast.Node` stores its children using `array`: **CAUTION:** `ast.Node` **DOESN'T** ensure concurrent security directly, due to its **lazy-load** design. However, you can call `Node.Load()`/`Node.LoadAll()` to achieve that, which may bring performance reduction while it still works faster than converting to `map` or `interface{}` ### Ast.Node or Ast.Visitor? + For generic data, `ast.Node` should be enough for your needs in most cases. However, `ast.Node` is designed for partially processing JSON string. It has some special designs such as lazy-load which might not be suitable for directly parsing the whole JSON string like `Unmarshal()`. Although `ast.Node` is better then `map` or `interface{}`, it's also a kind of intermediate representation after all if your final types are customized and you have to convert the above types to your custom types after parsing. @@ -412,4 +467,5 @@ For better performance, in previous case the `ast.Visitor` will be the better ch But `ast.Visitor` is not a very handy API. You might need to write a lot of code to implement your visitor and carefully maintain the tree hierarchy during decoding. Please read the comments in [ast/visitor.go](https://github.com/bytedance/sonic/blob/main/ast/visitor.go) carefully if you decide to use this API. ## Community + Sonic is a subproject of [CloudWeGo](https://www.cloudwego.io/). We are committed to building a cloud native ecosystem. diff --git a/README_ZH_CN.md b/README_ZH_CN.md index 396c089b9..d0341ab72 100644 --- a/README_ZH_CN.md +++ b/README_ZH_CN.md @@ -6,11 +6,12 @@ ## 依赖 -- Go 1.16~1.21 +- Go 1.16~1.22 - Linux / MacOS / Windows(需要 Go1.17 以上) - Amd64 架构 ## 接口 + 详见 [go.dev](https://pkg.go.dev/github.com/bytedance/sonic) ## 特色 @@ -22,7 +23,9 @@ ## 基准测试 对于**所有大小**的 json 和**所有使用场景**, **Sonic 表现均为最佳**。 + - [中型](https://github.com/bytedance/sonic/blob/main/decoder/testdata_test.go#L19) (13kB, 300+ 键, 6 层) + ```powershell goversion: 1.17.1 goos: darwin @@ -87,6 +90,7 @@ BenchmarkLoadNode_Parallel/LoadAll()-16 5493 ns/op 2370.6 BenchmarkLoadNode/Interface()-16 17722 ns/op 734.85 MB/s 13323 B/op 88 allocs/op BenchmarkLoadNode_Parallel/Interface()-16 10330 ns/op 1260.70 MB/s 15178 B/op 88 allocs/op ``` + - [小型](https://github.com/bytedance/sonic/blob/main/testdata/small.go) (400B, 11 个键, 3 层) ![small benchmarks](./docs/imgs/bench-small.png) - [大型](https://github.com/bytedance/sonic/blob/main/testdata/twitter.json) (635kB, 10000+ 个键, 6 层) @@ -103,6 +107,7 @@ BenchmarkLoadNode_Parallel/Interface()-16 10330 ns/op 1260.7 ### 序列化/反序列化 默认的行为基本上与 `encoding/json` 相一致,除了 HTML 转义形式(参见 [Escape HTML](https://github.com/bytedance/sonic/blob/main/README.md#escape-html)) 和 `SortKeys` 功能(参见 [Sort Keys](https://github.com/bytedance/sonic/blob/main/README.md#sort-keys))**没有**遵循 [RFC8259](https://datatracker.ietf.org/doc/html/rfc8259) 。 + ```go import "github.com/bytedance/sonic" @@ -116,7 +121,9 @@ err := sonic.Unmarshal(output, &data) ### 流式输入输出 Sonic 支持解码 `io.Reader` 中输入的 json,或将对象编码为 json 后输出至 `io.Writer`,以处理多个值并减少内存消耗。 + - 编码器 + ```go var o1 = map[string]interface{}{ "a": "b", @@ -131,7 +138,9 @@ fmt.Println(w.String()) // {"a":"b"} // 1 ``` + - 解码器 + ```go var o = map[string]interface{}{} var r = strings.NewReader(`{"a":"b"}{"1":"2"}`) @@ -175,6 +184,7 @@ fm := root.Interface().(float64) // jn == jm ### 对键排序 考虑到排序带来的性能损失(约 10% ), sonic 默认不会启用这个功能。如果你的组件依赖这个行为(如 [zstd](https://github.com/facebook/zstd)) ,可以仿照下面的例子: + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/encoder" @@ -191,6 +201,7 @@ err := root.SortKeys() ### HTML 转义 考虑到性能损失(约15%), sonic 默认不会启用这个功能。你可以使用 `encoder.EscapeHTML` 选项来开启(与 `encoding/json.HTMLEscape` 行为一致)。 + ```go import "github.com/bytedance/sonic" @@ -199,11 +210,13 @@ ret, err := Encode(v, EscapeHTML) // ret == `{"\u0026\u0026":{"X":"\u003c\u003e" ``` ### 紧凑格式 + Sonic 默认将基本类型( `struct` , `map` 等)编码为紧凑格式的 JSON ,除非使用 `json.RawMessage` or `json.Marshaler` 进行编码: sonic 确保输出的 JSON 合法,但出于性能考虑,**不会**加工成紧凑格式。我们提供选项 `encoder.CompactMarshaler` 来添加此过程, ### 打印错误 如果输入的 JSON 存在无效的语法,sonic 将返回 `decoder.SyntaxError`,该错误支持错误位置的美化输出。 + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/decoder" @@ -231,6 +244,7 @@ if err != nil { #### 类型不匹配 [Sonic v1.6.0] 如果给定键中存在**类型不匹配**的值, sonic 会抛出 `decoder.MismatchTypeError` (如果有多个,只会报告最后一个),但仍会跳过错误的值并解码下一个 JSON 。 + ```go import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/decoder" @@ -243,6 +257,7 @@ err := UnmarshalString(`{"A":"1","B":1}`, &data) println(err.Error()) // Mismatch type int with value string "at index 5: mismatched type with value\n\n\t{\"A\":\"1\",\"B\":1}\n\t.....^.........\n" fmt.Printf("%+v", data) // {A:0 B:1} ``` + ### `Ast.Node` Sonic/ast.Node 是完全独立的 JSON 抽象语法树库。它实现了序列化和反序列化,并提供了获取和修改通用数据的鲁棒的 API。 @@ -250,6 +265,7 @@ Sonic/ast.Node 是完全独立的 JSON 抽象语法树库。它实现了序列 #### 查找/索引 通过给定的路径搜索 JSON 片段,路径必须为非负整数,字符串或 `nil` 。 + ```go import "github.com/bytedance/sonic" @@ -263,11 +279,13 @@ raw := root.Raw() // == string(input) root, err := sonic.Get(input, "key1", 1, "key2") sub := root.Get("key3").Index(2).Int64() // == 3 ``` + **注意**:由于 `Index()` 使用偏移量来定位数据,比使用扫描的 `Get()` 要快的多,建议尽可能的使用 `Index` 。 Sonic 也提供了另一个 API, `IndexOrGet()` ,以偏移量为基础并且也确保键的匹配。 #### 修改 -使用 ` Set()` / `Unset()` 修改 json 的内容 +使用 `Set()` / `Unset()` 修改 json 的内容 + ```go import "github.com/bytedance/sonic" @@ -284,7 +302,9 @@ println(root.Get("key4").Check()) // "value not exist" ``` #### 序列化 + 要将 `ast.Node` 编码为 json ,使用 `MarshalJson()` 或者 `json.Marshal()` (必须传递指向节点的指针) + ```go import ( "encoding/json" @@ -298,6 +318,7 @@ println(string(buf) == string(exp)) // true ``` #### APIs + - 合法性检查: `Check()`, `Error()`, `Valid()`, `Exist()` - 索引: `Index()`, `Get()`, `IndexPair()`, `IndexOrGet()`, `GetByPath()` - 转换至 go 内置类型: `Int64()`, `Float64()`, `String()`, `Number()`, `Bool()`, `Map[UseNumber|UseNode]()`, `Array[UseNumber|UseNode]()`, `Interface[UseNumber|UseNode]()` @@ -306,7 +327,9 @@ println(string(buf) == string(exp)) // true - 修改: `Set()`, `SetByIndex()`, `Add()` ### `Ast.Visitor` + Sonic 提供了一个高级的 API 用于直接全量解析 JSON 到非标准容器里 (既不是 `struct` 也不是 `map[string]interface{}`) 且不需要借助任何中间表示 (`ast.Node` 或 `interface{}`)。举个例子,你可能定义了下述的类型,它们看起来像 `interface{}`,但实际上并不是: + ```go type UserNode interface {} @@ -321,7 +344,9 @@ type ( UserArray struct{ Value []UserNode } ) ``` + Sonic 提供了下述的 API 来返回 **“对 JSON AST 的前序遍历”**。`ast.Visitor` 是一个 SAX 风格的接口,这在某些 C++ 的 JSON 解析库中被使用到。你需要自己实现一个 `ast.Visitor`,将它传递给 `ast.Preorder()` 方法。在你的实现中你可以使用自定义的类型来表示 JSON 的值。在你的 `ast.Visitor` 中,可能需要有一个 O(n) 空间复杂度的容器(比如说栈)来记录 object / array 的层级。 + ```go func Preorder(str string, visitor Visitor, opts *VisitorOptions) error @@ -338,15 +363,18 @@ type Visitor interface { OnArrayEnd() error } ``` + 详细用法参看 [ast/visitor.go](https://github.com/bytedance/sonic/blob/main/ast/visitor.go),我们还为 `UserNode` 实现了一个示例 `ast.Visitor`,你可以在 [ast/visitor_test.go](https://github.com/bytedance/sonic/blob/main/ast/visitor_test.go) 中找到它。 ## 兼容性 + 由于开发高性能代码的困难性, Sonic **不**保证对所有环境的支持。对于在不同环境中使用 Sonic 构建应用程序的开发者,我们有以下建议: - 在 **Mac M1** 上开发:确保在您的计算机上安装了 Rosetta 2,并在构建时设置 `GOARCH=amd64` 。 Rosetta 2 可以自动将 x86 二进制文件转换为 arm64 二进制文件,并在 Mac M1 上运行 x86 应用程序。 - 在 **Linux arm64** 上开发:您可以安装 qemu 并使用 `qemu-x86_64 -cpu max` 命令来将 x86 二进制文件转换为 arm64 二进制文件。qemu可以实现与Mac M1上的Rosetta 2类似的转换效果。 对于希望在不使用 qemu 下使用 sonic 的开发者,或者希望处理 JSON 时与 `encoding/JSON` 严格保持一致的开发者,我们在 `sonic.API` 中提供了一些兼容性 API + - `ConfigDefault`: 在支持 sonic 的环境下 sonic 的默认配置(`EscapeHTML=false`,`SortKeys=false`等)。行为与具有相应配置的 `encoding/json` 一致,一些选项,如 `SortKeys=false` 将无效。 - `ConfigStd`: 在支持 sonic 的环境下与标准库兼容的配置(`EscapeHTML=true`,`SortKeys=true`等)。行为与 `encoding/json` 一致。 - `ConfigFastest`: 在支持 sonic 的环境下运行最快的配置(`NoQuoteTextMarshaler=true`)。行为与具有相应配置的 `encoding/json` 一致,某些选项将无效。 @@ -354,7 +382,9 @@ type Visitor interface { ## 注意事项 ### 预热 + 由于 Sonic 使用 [golang-asm](https://github.com/twitchyliquid64/golang-asm) 作为 JIT 汇编器,这个库并不适用于运行时编译,第一次运行一个大型模式可能会导致请求超时甚至进程内存溢出。为了更好地稳定性,我们建议在运行大型模式或在内存有限的应用中,在使用 `Marshal()/Unmarshal()` 前运行 `Pretouch()`。 + ```go import ( "reflect" @@ -384,16 +414,17 @@ func init() { 当解码 **没有转义字符的字符串**时, sonic 会从原始的 JSON 缓冲区内引用而不是复制到新的一个缓冲区中。这对 CPU 的性能方面很有帮助,但是可能因此在解码后对象仍在使用的时候将整个 JSON 缓冲区保留在内存中。实践中我们发现,通过引用 JSON 缓冲区引入的额外内存通常是解码后对象的 20% 至 80% ,一旦应用长期保留这些对象(如缓存以备重用),服务器所使用的内存可能会增加。我们提供了选项 `decoder.CopyString()` 供用户选择,不引用 JSON 缓冲区。这可能在一定程度上降低 CPU 性能。 ### 传递字符串还是字节数组? + 为了和 `encoding/json` 保持一致,我们提供了传递 `[]byte` 作为参数的 API ,但考虑到安全性,字符串到字节的复制是同时进行的,这在原始 JSON 非常大时可能会导致性能损失。因此,你可以使用 `UnmarshalString()` 和 `GetFromString()` 来传递字符串,只要你的原始数据是字符串,或**零拷贝类型转换**对于你的字节数组是安全的。我们也提供了 `MarshalString()` 的 API ,以便对编码的 JSON 字节数组进行**零拷贝类型转换**,因为 sonic 输出的字节始终是重复并且唯一的,所以这样是安全的。 ### 加速 `encoding.TextMarshaler` 为了保证数据安全性, `sonic.Encoder` 默认会对来自 `encoding.TextMarshaler` 接口的字符串进行引用和转义,如果大部分数据都是这种形式那可能会导致很大的性能损失。我们提供了 `encoder.NoQuoteTextMarshaler` 选项来跳过这些操作,但你**必须**保证他们的输出字符串依照 [RFC8259](https://datatracker.ietf.org/doc/html/rfc8259) 进行了转义和引用。 - ### 泛型的性能优化 在 **完全解析**的场景下, `Unmarshal()` 表现得比 `Get()`+`Node.Interface()` 更好。但是如果你只有特定 JSON 的部分模式,你可以将 `Get()` 和 `Unmarshal()` 结合使用: + ```go import "github.com/bytedance/sonic" @@ -401,7 +432,9 @@ node, err := sonic.GetFromString(_TwitterJson, "statuses", 3, "user") var user User // your partial schema... err = sonic.UnmarshalString(node.Raw(), &user) ``` + 甚至如果你没有任何模式,可以用 `ast.Node` 代替 `map` 或 `interface` 作为泛型的容器: + ```go import "github.com/bytedance/sonic" @@ -412,7 +445,9 @@ err = user.Check() // err = user.LoadAll() // only call this when you want to use 'user' concurrently... go someFunc(user) ``` + 为什么?因为 `ast.Node` 使用 `array` 来存储其子节点: + - 在插入(反序列化)和扫描(序列化)数据时,`Array` 的性能比 `Map` **好得多**; - **哈希**(`map[x]`)的效率不如**索引**(`array[x]`)高效,而 `ast.Node` 可以在数组和对象上使用索引; - 使用 `Interface()` / `Map()` 意味着 sonic 必须解析所有的底层值,而 `ast.Node` 可以**按需解析**它们。 @@ -420,6 +455,7 @@ go someFunc(user) **注意**:由于 `ast.Node` 的惰性加载设计,其**不能**直接保证并发安全性,但你可以调用 `Node.Load()` / `Node.LoadAll()` 来实现并发安全。尽管可能会带来性能损失,但仍比转换成 `map` 或 `interface{}` 更为高效。 ### 使用 `ast.Node` 还是 `ast.Visitor`? + 对于泛型数据的解析,`ast.Node` 在大多数场景上应该能够满足你的需求。 然而,`ast.Node` 是一种针对部分解析 JSON 而设计的泛型容器,它包含一些特殊设计,比如惰性加载,如果你希望像 `Unmarshal()` 那样直接解析整个 JSON,这些设计可能并不合适。尽管 `ast.Node` 相较于 `map` 或 `interface{}` 来说是更好的一种泛型容器,但它毕竟也是一种中间表示,如果你的最终类型是自定义的,你还得在解析完成后将上述类型转化成你自定义的类型。 diff --git a/ast/api_amd64.go b/ast/api_amd64.go index 15a22b7ba..fa4375630 100644 --- a/ast/api_amd64.go +++ b/ast/api_amd64.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2022 ByteDance Inc. diff --git a/ast/api_amd64_test.go b/ast/api_amd64_test.go index 6b9354ac4..a659fe98f 100644 --- a/ast/api_amd64_test.go +++ b/ast/api_amd64_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2022 ByteDance Inc. @@ -24,8 +24,66 @@ import ( `github.com/bytedance/sonic/encoder` `github.com/stretchr/testify/require` + `github.com/bytedance/sonic/internal/native/types` + `github.com/stretchr/testify/assert` ) +func TestEncodeValue(t *testing.T) { + obj := new(_TwitterStruct) + if err := json.Unmarshal([]byte(_TwitterJson), obj); err != nil { + t.Fatal(err) + } + // buf, err := encoder.Encode(obj, encoder.EscapeHTML|encoder.SortMapKeys) + buf, err := json.Marshal(obj) + if err != nil { + t.Fatal(err) + } + quote, err := json.Marshal(_TwitterJson) + if err != nil { + t.Fatal(err) + } + type Case struct { + node Node + exp string + err bool + } + input := []Case{ + {NewNull(), "null", false}, + {NewBool(true), "true", false}, + {NewBool(false), "false", false}, + {NewNumber("0.0"), "0.0", false}, + {NewString(""), `""`, false}, + {NewString(`\"\"`), `"\\\"\\\""`, false}, + {NewString(_TwitterJson), string(quote), false}, + {NewArray([]Node{}), "[]", false}, + {NewArray([]Node{NewString(""), NewNull()}), `["",null]`, false}, + {NewArray([]Node{NewBool(true), NewString("true"), NewString("\t")}), `[true,"true","\t"]`, false}, + {NewObject([]Pair{Pair{"a", NewNull()}, Pair{"b", NewNumber("0")}}), `{"a":null,"b":0}`, false}, + {NewObject([]Pair{Pair{"\ta", NewString("\t")}, Pair{"\bb", NewString("\b")}, Pair{"\nb", NewString("\n")}, Pair{"\ra", NewString("\r")}}),`{"\ta":"\t","\u0008b":"\u0008","\nb":"\n","\ra":"\r"}`, false}, + {NewObject([]Pair{}), `{}`, false}, + {NewObject([]Pair{Pair{Key: "", Value: NewNull()}}), `{"":null}`, false}, + {NewBytes([]byte("hello, world")), `"aGVsbG8sIHdvcmxk"`, false}, + {NewAny(obj), string(buf), false}, + {NewRaw(`[{ }]`), "[{}]", false}, + {Node{}, "", true}, + {Node{t: types.ValueType(1)}, "", true}, + } + for i, c := range input { + t.Log(i) + buf, err := json.Marshal(&c.node) + if c.err { + if err == nil { + t.Fatal(i) + } + continue + } + if err != nil { + t.Fatal(i, err) + } + assert.Equal(t, c.exp, string(buf)) + } +} + func TestSortNodeTwitter(t *testing.T) { root, err := NewSearcher(_TwitterJson).GetByPath() if err != nil { diff --git a/ast/api_compat.go b/ast/api_compat.go index ce7b08a63..9244e76e1 100644 --- a/ast/api_compat.go +++ b/ast/api_compat.go @@ -1,4 +1,4 @@ -// +build !amd64 !go1.16 go1.22 +// +build !amd64 !go1.16 go1.23 /* * Copyright 2022 ByteDance Inc. @@ -27,7 +27,7 @@ import ( ) func init() { - println("WARNING: sonic only supports Go1.16~1.21 && CPU amd64, but your environment is not suitable") + println("WARNING: sonic only supports Go1.16~1.22 && CPU amd64, but your environment is not suitable") } func quote(buf *[]byte, val string) { diff --git a/ast/encode_test.go b/ast/encode_test.go index a333b0688..333270732 100644 --- a/ast/encode_test.go +++ b/ast/encode_test.go @@ -22,8 +22,6 @@ import ( `sync` `testing` - `github.com/bytedance/sonic/internal/native/types` - `github.com/stretchr/testify/assert` `github.com/stretchr/testify/require` ) @@ -63,62 +61,6 @@ func TestGC_Encode(t *testing.T) { wg.Wait() } -func TestEncodeValue(t *testing.T) { - obj := new(_TwitterStruct) - if err := json.Unmarshal([]byte(_TwitterJson), obj); err != nil { - t.Fatal(err) - } - // buf, err := encoder.Encode(obj, encoder.EscapeHTML|encoder.SortMapKeys) - buf, err := json.Marshal(obj) - if err != nil { - t.Fatal(err) - } - quote, err := json.Marshal(_TwitterJson) - if err != nil { - t.Fatal(err) - } - type Case struct { - node Node - exp string - err bool - } - input := []Case{ - {NewNull(), "null", false}, - {NewBool(true), "true", false}, - {NewBool(false), "false", false}, - {NewNumber("0.0"), "0.0", false}, - {NewString(""), `""`, false}, - {NewString(`\"\"`), `"\\\"\\\""`, false}, - {NewString(_TwitterJson), string(quote), false}, - {NewArray([]Node{}), "[]", false}, - {NewArray([]Node{NewString(""), NewNull()}), `["",null]`, false}, - {NewArray([]Node{NewBool(true), NewString("true"), NewString("\t")}), `[true,"true","\t"]`, false}, - {NewObject([]Pair{Pair{"a", NewNull()}, Pair{"b", NewNumber("0")}}), `{"a":null,"b":0}`, false}, - {NewObject([]Pair{Pair{"\ta", NewString("\t")}, Pair{"\bb", NewString("\b")}, Pair{"\nb", NewString("\n")}, Pair{"\ra", NewString("\r")}}),`{"\ta":"\t","\u0008b":"\u0008","\nb":"\n","\ra":"\r"}`, false}, - {NewObject([]Pair{}), `{}`, false}, - {NewObject([]Pair{Pair{Key: "", Value: NewNull()}}), `{"":null}`, false}, - {NewBytes([]byte("hello, world")), `"aGVsbG8sIHdvcmxk"`, false}, - {NewAny(obj), string(buf), false}, - {NewRaw(`[{ }]`), "[{}]", false}, - {Node{}, "", true}, - {Node{t: types.ValueType(1)}, "", true}, - } - for i, c := range input { - t.Log(i) - buf, err := json.Marshal(&c.node) - if c.err { - if err == nil { - t.Fatal(i) - } - continue - } - if err != nil { - t.Fatal(i, err) - } - assert.Equal(t, c.exp, string(buf)) - } -} - func TestEncodeNode(t *testing.T) { data := `{"a":[{},[],-0.1,true,false,null,""],"b":0,"c":true,"d":false,"e":null,"g":""}` root, e := NewSearcher(data).GetByPath() diff --git a/compat.go b/compat.go index ec414c0cf..728bc1767 100644 --- a/compat.go +++ b/compat.go @@ -1,4 +1,4 @@ -// +build !amd64 !go1.16 go1.22 +// +build !amd64 !go1.16 go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/decode_float_test.go b/decode_float_test.go deleted file mode 100644 index ebc7f4c11..000000000 --- a/decode_float_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// +build amd64,go1.16,!go1.22 - -/* - * Copyright 2021 ByteDance Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sonic - -import ( - `encoding/json` - `reflect` - `strings` - `testing` - - `github.com/bytedance/sonic/decoder` -) - -type atofTest struct { - in string - out string - err error -} - -// Tests from Go strconv package, https://github.com/golang/go/blob/master/src/strconv/atof_test.go -// All tests are passed in Go encoding/json. -var atoftests = []atofTest{ - {"1.234e", "", nil}, // error - {"1i", "1", nil}, // pass - {"1", "1", nil}, - {"1e23", "1e+23", nil}, - {"1E23", "1e+23", nil}, - {"100000000000000000000000", "1e+23", nil}, - {"1e-100", "1e-100", nil}, - {"123456700", "1.234567e+08", nil}, - {"99999999999999974834176", "9.999999999999997e+22", nil}, - {"100000000000000000000001", "1.0000000000000001e+23", nil}, - {"100000000000000008388608", "1.0000000000000001e+23", nil}, - {"100000000000000016777215", "1.0000000000000001e+23", nil}, - {"100000000000000016777216", "1.0000000000000003e+23", nil}, - {"-1", "-1", nil}, - {"-0.1", "-0.1", nil}, - {"-0", "-0", nil}, - {"1e-20", "1e-20", nil}, - {"625e-3", "0.625", nil}, - - // zeros - {"0", "0", nil}, - {"0e0", "0", nil}, - {"-0e0", "-0", nil}, - {"0e-0", "0", nil}, - {"-0e-0", "-0", nil}, - {"0e+0", "0", nil}, - {"-0e+0", "-0", nil}, - {"0e+01234567890123456789", "0", nil}, - {"0.00e-01234567890123456789", "0", nil}, - {"-0e+01234567890123456789", "-0", nil}, - {"-0.00e-01234567890123456789", "-0", nil}, - - {"0e291", "0", nil}, // issue 15364 - {"0e292", "0", nil}, // issue 15364 - {"0e347", "0", nil}, // issue 15364 - {"0e348", "0", nil}, // issue 15364 - {"-0e291", "-0", nil}, - {"-0e292", "-0", nil}, - {"-0e347", "-0", nil}, - {"-0e348", "-0", nil}, - - // largest float64 - {"1.7976931348623157e308", "1.7976931348623157e+308", nil}, - {"-1.7976931348623157e308", "-1.7976931348623157e+308", nil}, - - // the border is ...158079 - // borderline - okay - {"1.7976931348623158e308", "1.7976931348623157e+308", nil}, - {"-1.7976931348623158e308", "-1.7976931348623157e+308", nil}, - - // a little too large - {"1e308", "1e+308", nil}, - - // denormalized - {"1e-305", "1e-305", nil}, - {"1e-306", "1e-306", nil}, - {"1e-307", "1e-307", nil}, - {"1e-308", "1e-308", nil}, - {"1e-309", "1e-309", nil}, - {"1e-310", "1e-310", nil}, - {"1e-322", "1e-322", nil}, - // smallest denormal - {"5e-324", "5e-324", nil}, - {"4e-324", "5e-324", nil}, - {"3e-324", "5e-324", nil}, - // too small - {"2e-324", "0", nil}, - // way too small - {"1e-350", "0", nil}, - {"1e-400000", "0", nil}, - - // try to overflow exponent - {"1e-4294967296", "0", nil}, - {"1e-18446744073709551616", "0", nil}, - - // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/ - {"2.2250738585072012e-308", "2.2250738585072014e-308", nil}, - // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ - {"2.2250738585072011e-308", "2.225073858507201e-308", nil}, - - // A very large number (initially wrongly parsed by the fast algorithm). - {"4.630813248087435e+307", "4.630813248087435e+307", nil}, - - // A different kind of very large number. - {"22.222222222222222", "22.22222222222222", nil}, - {"2." + strings.Repeat("2", 800) + "e+1", "22.22222222222222", nil}, - - // Exactly halfway between 1 and math.Nextafter(1, 2). - // Round to even (down). - {"1.00000000000000011102230246251565404236316680908203125", "1", nil}, - // Slightly lower; still round down. - {"1.00000000000000011102230246251565404236316680908203124", "1", nil}, - // Slightly higher; round up. - {"1.00000000000000011102230246251565404236316680908203126", "1.0000000000000002", nil}, - // Slightly higher, but you have to read all the way to the end. - {"1.00000000000000011102230246251565404236316680908203125" + strings.Repeat("0", 10000) + "1", "1.0000000000000002", nil}, - - // Halfway between x := math.Nextafter(1, 2) and math.Nextafter(x, 2) - // Round to even (up). - {"1.00000000000000033306690738754696212708950042724609375", "1.0000000000000004", nil}, - - // Halfway between 1090544144181609278303144771584 and 1090544144181609419040633126912 - // (15497564393479157p+46, should round to even 15497564393479156p+46, issue 36657) - {"1090544144181609348671888949248", "1.0905441441816093e+30", nil}, - - // Corner case between int64 and float64 for the input - {"9223372036854775807", "9223372036854775807", nil}, // max int64: (1 << 63) - 1 - {"9223372036854775808", "9223372036854775808", nil}, - {"-9223372036854775808", "-9223372036854775808", nil}, // min int64: 1 << 63 - {"-9223372036854775809", "-9223372036854775809", nil}, -} - -func TestDecodeFloat(t *testing.T) { - for i, tt := range atoftests { - // default float64 - var sonicout, stdout float64 - sonicerr := decoder.NewDecoder(tt.in).Decode(&sonicout) - stderr := json.NewDecoder(strings.NewReader(tt.in)).Decode(&stdout) - if !reflect.DeepEqual(sonicout, stdout) { - t.Fatalf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sonicout, stdout) - } - if !reflect.DeepEqual(sonicerr == nil, stderr == nil) { - t.Fatalf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sonicerr, stderr) - } - } -} diff --git a/decode_test.go b/decode_test.go index 46830f6fc..13aa0c605 100644 --- a/decode_test.go +++ b/decode_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. @@ -2586,3 +2586,230 @@ func TestDecoder_RandomInvalidUtf8(t *testing.T) { testDecodeInvalidUtf8(t, genRandJsonRune(length)) } } + + +type atofTest struct { + in string + out string + err error +} + +// Tests from Go strconv package, https://github.com/golang/go/blob/master/src/strconv/atof_test.go +// All tests are passed in Go encoding/json. +var atoftests = []atofTest{ + {"1.234e", "", nil}, // error + {"1i", "1", nil}, // pass + {"1", "1", nil}, + {"1e23", "1e+23", nil}, + {"1E23", "1e+23", nil}, + {"100000000000000000000000", "1e+23", nil}, + {"1e-100", "1e-100", nil}, + {"123456700", "1.234567e+08", nil}, + {"99999999999999974834176", "9.999999999999997e+22", nil}, + {"100000000000000000000001", "1.0000000000000001e+23", nil}, + {"100000000000000008388608", "1.0000000000000001e+23", nil}, + {"100000000000000016777215", "1.0000000000000001e+23", nil}, + {"100000000000000016777216", "1.0000000000000003e+23", nil}, + {"-1", "-1", nil}, + {"-0.1", "-0.1", nil}, + {"-0", "-0", nil}, + {"1e-20", "1e-20", nil}, + {"625e-3", "0.625", nil}, + + // zeros + {"0", "0", nil}, + {"0e0", "0", nil}, + {"-0e0", "-0", nil}, + {"0e-0", "0", nil}, + {"-0e-0", "-0", nil}, + {"0e+0", "0", nil}, + {"-0e+0", "-0", nil}, + {"0e+01234567890123456789", "0", nil}, + {"0.00e-01234567890123456789", "0", nil}, + {"-0e+01234567890123456789", "-0", nil}, + {"-0.00e-01234567890123456789", "-0", nil}, + + {"0e291", "0", nil}, // issue 15364 + {"0e292", "0", nil}, // issue 15364 + {"0e347", "0", nil}, // issue 15364 + {"0e348", "0", nil}, // issue 15364 + {"-0e291", "-0", nil}, + {"-0e292", "-0", nil}, + {"-0e347", "-0", nil}, + {"-0e348", "-0", nil}, + + // largest float64 + {"1.7976931348623157e308", "1.7976931348623157e+308", nil}, + {"-1.7976931348623157e308", "-1.7976931348623157e+308", nil}, + + // the border is ...158079 + // borderline - okay + {"1.7976931348623158e308", "1.7976931348623157e+308", nil}, + {"-1.7976931348623158e308", "-1.7976931348623157e+308", nil}, + + // a little too large + {"1e308", "1e+308", nil}, + + // denormalized + {"1e-305", "1e-305", nil}, + {"1e-306", "1e-306", nil}, + {"1e-307", "1e-307", nil}, + {"1e-308", "1e-308", nil}, + {"1e-309", "1e-309", nil}, + {"1e-310", "1e-310", nil}, + {"1e-322", "1e-322", nil}, + // smallest denormal + {"5e-324", "5e-324", nil}, + {"4e-324", "5e-324", nil}, + {"3e-324", "5e-324", nil}, + // too small + {"2e-324", "0", nil}, + // way too small + {"1e-350", "0", nil}, + {"1e-400000", "0", nil}, + + // try to overflow exponent + {"1e-4294967296", "0", nil}, + {"1e-18446744073709551616", "0", nil}, + + // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/ + {"2.2250738585072012e-308", "2.2250738585072014e-308", nil}, + // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ + {"2.2250738585072011e-308", "2.225073858507201e-308", nil}, + + // A very large number (initially wrongly parsed by the fast algorithm). + {"4.630813248087435e+307", "4.630813248087435e+307", nil}, + + // A different kind of very large number. + {"22.222222222222222", "22.22222222222222", nil}, + {"2." + strings.Repeat("2", 800) + "e+1", "22.22222222222222", nil}, + + // Exactly halfway between 1 and math.Nextafter(1, 2). + // Round to even (down). + {"1.00000000000000011102230246251565404236316680908203125", "1", nil}, + // Slightly lower; still round down. + {"1.00000000000000011102230246251565404236316680908203124", "1", nil}, + // Slightly higher; round up. + {"1.00000000000000011102230246251565404236316680908203126", "1.0000000000000002", nil}, + // Slightly higher, but you have to read all the way to the end. + {"1.00000000000000011102230246251565404236316680908203125" + strings.Repeat("0", 10000) + "1", "1.0000000000000002", nil}, + + // Halfway between x := math.Nextafter(1, 2) and math.Nextafter(x, 2) + // Round to even (up). + {"1.00000000000000033306690738754696212708950042724609375", "1.0000000000000004", nil}, + + // Halfway between 1090544144181609278303144771584 and 1090544144181609419040633126912 + // (15497564393479157p+46, should round to even 15497564393479156p+46, issue 36657) + {"1090544144181609348671888949248", "1.0905441441816093e+30", nil}, + + // Corner case between int64 and float64 for the input + {"9223372036854775807", "9223372036854775807", nil}, // max int64: (1 << 63) - 1 + {"9223372036854775808", "9223372036854775808", nil}, + {"-9223372036854775808", "-9223372036854775808", nil}, // min int64: 1 << 63 + {"-9223372036854775809", "-9223372036854775809", nil}, +} + +func TestDecodeFloat(t *testing.T) { + for i, tt := range atoftests { + // default float64 + var sonicout, stdout float64 + sonicerr := decoder.NewDecoder(tt.in).Decode(&sonicout) + stderr := json.NewDecoder(strings.NewReader(tt.in)).Decode(&stdout) + if !reflect.DeepEqual(sonicout, stdout) { + t.Fatalf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sonicout, stdout) + } + if !reflect.DeepEqual(sonicerr == nil, stderr == nil) { + t.Fatalf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sonicerr, stderr) + } + } +} + + +type useInt64Test struct { + in string + out int64 +} + +type useFloatTest struct { + in string + out float64 +} + +var useinttest = []useInt64Test{ + // int64 + {"0", 0}, + {"1", 1}, + {"-1", -1}, + {"100", 100}, + + {"-9223372036854775807", -9223372036854775807}, + {"-9223372036854775808", -9223372036854775808}, //min int64 + {"9223372036854775807", 9223372036854775807}, //max int64 + {"9223372036854775806", 9223372036854775806}, +} + +var usefloattest = []useFloatTest{ + // float64 + {"-9223372036854775809", -9223372036854775809}, // int64 overflow + {"9223372036854775808", 9223372036854775808}, // int64 overflow + {"1e2", 1e2}, + {"1e-20", 1e-20}, + {"1.0", 1}, +} + +func TestUseInt64(t *testing.T) { + for i, tt := range useinttest { + var sout interface{} + dc := decoder.NewDecoder(tt.in) + dc.UseInt64() + serr := dc.Decode(&sout) + if !reflect.DeepEqual(sout, tt.out) { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.in) + } + if serr != nil { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) + } + } + + for i, tt := range usefloattest { + var sout interface{} + dc := decoder.NewDecoder(tt.in) + dc.UseInt64() + //the input string is not int64, still return float64 + serr := dc.Decode(&sout) + if !reflect.DeepEqual(sout, tt.out) { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.in) + } + if serr != nil { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) + } + } +} + +func TestUseNumber(t *testing.T) { + for i, tt := range useinttest { + var sout interface{} + dc := decoder.NewDecoder(tt.in) + dc.UseNumber() + serr := dc.Decode(&sout) + if !reflect.DeepEqual(sout, json.Number(tt.in)) { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.out) + } + if serr != nil { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) + } + } + + for i, tt := range usefloattest { + var sout interface{} + dc := decoder.NewDecoder(tt.in) + dc.UseNumber() + serr := dc.Decode(&sout) + if !reflect.DeepEqual(sout, json.Number(tt.in)) { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.out) + } + if serr != nil { + t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) + } + } +} diff --git a/decoder/decoder_amd64.go b/decoder/decoder_amd64.go index 7c2845514..346ebbce5 100644 --- a/decoder/decoder_amd64.go +++ b/decoder/decoder_amd64.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2023 ByteDance Inc. diff --git a/decoder/decoder_amd64_test.go b/decoder/decoder_amd64_test.go index 3284c4681..7c15fa803 100644 --- a/decoder/decoder_amd64_test.go +++ b/decoder/decoder_amd64_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/decoder/decoder_compat.go b/decoder/decoder_compat.go index 070eea633..7883862c3 100644 --- a/decoder/decoder_compat.go +++ b/decoder/decoder_compat.go @@ -1,4 +1,4 @@ -// +build !amd64 !go1.16 go1.22 +// +build !amd64 !go1.16 go1.23 /* * Copyright 2023 ByteDance Inc. @@ -30,7 +30,7 @@ import ( ) func init() { - println("WARNING: sonic only supports Go1.16~1.21 && CPU amd64, but your environment is not suitable") + println("WARNING: sonic only supports Go1.16~1.22 && CPU amd64, but your environment is not suitable") } const ( diff --git a/encode_test.go b/encode_test.go index 88734cd4d..43813c10f 100644 --- a/encode_test.go +++ b/encode_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/encoder/encoder_amd64.go b/encoder/encoder_amd64.go index 1cbef7b24..b4f1b7b52 100644 --- a/encoder/encoder_amd64.go +++ b/encoder/encoder_amd64.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2023 ByteDance Inc. diff --git a/encoder/encoder_amd64_test.go b/encoder/encoder_amd64_test.go index 56db9c3df..204ce84ba 100644 --- a/encoder/encoder_amd64_test.go +++ b/encoder/encoder_amd64_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/encoder/encoder_compat.go b/encoder/encoder_compat.go index 2d3cb27a9..320dd9b5c 100644 --- a/encoder/encoder_compat.go +++ b/encoder/encoder_compat.go @@ -1,4 +1,4 @@ -// +build !amd64 !go1.16 go1.22 +// +build !amd64 !go1.16 go1.23 /* * Copyright 2023 ByteDance Inc. @@ -28,7 +28,7 @@ import ( ) func init() { - println("WARNING: sonic only supports Go1.16~1.21 && CPU amd64, but your environment is not suitable") + println("WARNING: sonic only supports Go1.16~1.22 && CPU amd64, but your environment is not suitable") } // Options is a set of encoding options. diff --git a/internal/decoder/asm_stubs_amd64_go121.go b/internal/decoder/asm_stubs_amd64_go121.go index 5db5b5cd0..6adeac0cf 100644 --- a/internal/decoder/asm_stubs_amd64_go121.go +++ b/internal/decoder/asm_stubs_amd64_go121.go @@ -1,4 +1,4 @@ -// +build go1.21,!go1.22 +// +build go1.21,!go1.23 // Copyright 2023 CloudWeGo Authors // diff --git a/internal/decoder/assembler_regabi_amd64.go b/internal/decoder/assembler_regabi_amd64.go index 17b3b7fd3..0defb75a5 100644 --- a/internal/decoder/assembler_regabi_amd64.go +++ b/internal/decoder/assembler_regabi_amd64.go @@ -1,5 +1,4 @@ -//go:build go1.17 && !go1.22 -// +build go1.17,!go1.22 +// +build go1.17,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/internal/decoder/generic_regabi_amd64.go b/internal/decoder/generic_regabi_amd64.go index 0c68c7fb6..c7514cb41 100644 --- a/internal/decoder/generic_regabi_amd64.go +++ b/internal/decoder/generic_regabi_amd64.go @@ -1,4 +1,4 @@ -// +build go1.17,!go1.22 +// +build go1.17,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/internal/decoder/generic_regabi_amd64_test.s b/internal/decoder/generic_regabi_amd64_test.s index 1c46928de..b4b0de183 100644 --- a/internal/decoder/generic_regabi_amd64_test.s +++ b/internal/decoder/generic_regabi_amd64_test.s @@ -1,4 +1,4 @@ -// +build go1.17,!go1.22 +// +build go1.17,!go1.23 // // Copyright 2021 ByteDance Inc. diff --git a/internal/encoder/asm_stubs_amd64_go121.go b/internal/encoder/asm_stubs_amd64_go121.go index 2f9445ac4..9f7ff65e6 100644 --- a/internal/encoder/asm_stubs_amd64_go121.go +++ b/internal/encoder/asm_stubs_amd64_go121.go @@ -1,4 +1,4 @@ -// +build go1.21,!go1.22 +// +build go1.21,!go1.23 // Copyright 2023 CloudWeGo Authors // diff --git a/internal/encoder/assembler_regabi_amd64.go b/internal/encoder/assembler_regabi_amd64.go index d67798d61..4584c6d29 100644 --- a/internal/encoder/assembler_regabi_amd64.go +++ b/internal/encoder/assembler_regabi_amd64.go @@ -1,5 +1,4 @@ -//go:build go1.17 && !go1.22 -// +build go1.17,!go1.22 +// +build go1.17,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/internal/encoder/debug_go117.go b/internal/encoder/debug_go117.go index 56a6cbf5e..37e6f7d4f 100644 --- a/internal/encoder/debug_go117.go +++ b/internal/encoder/debug_go117.go @@ -1,4 +1,4 @@ -// +build go1.17,!go1.22 +// +build go1.17,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/internal/encoder/primitives.go b/internal/encoder/primitives.go index 0e47987c7..0f3c40881 100644 --- a/internal/encoder/primitives.go +++ b/internal/encoder/primitives.go @@ -154,17 +154,17 @@ var ( ) var ( - _F_assertI2I = jit.Func(assertI2I) + _F_assertI2I = jit.Func(rt.AssertI2I2) ) func asText(v unsafe.Pointer) (string, error) { - text := assertI2I(_T_encoding_TextMarshaler, *(*rt.GoIface)(v)) + text := rt.AssertI2I2(_T_encoding_TextMarshaler, *(*rt.GoIface)(v)) r, e := (*(*encoding.TextMarshaler)(unsafe.Pointer(&text))).MarshalText() return rt.Mem2Str(r), e } func asJson(v unsafe.Pointer) (string, error) { - text := assertI2I(_T_json_Marshaler, *(*rt.GoIface)(v)) + text := rt.AssertI2I2(_T_json_Marshaler, *(*rt.GoIface)(v)) r, e := (*(*json.Marshaler)(unsafe.Pointer(&text))).MarshalJSON() return rt.Mem2Str(r), e } diff --git a/internal/encoder/stubs_go116.go b/internal/encoder/stubs_go116.go index 5577c58d7..a21b6b4a6 100644 --- a/internal/encoder/stubs_go116.go +++ b/internal/encoder/stubs_go116.go @@ -38,10 +38,6 @@ func memmove(to unsafe.Pointer, from unsafe.Pointer, n uintptr) //goland:noinspection GoUnusedParameter func growslice(et *rt.GoType, old rt.GoSlice, cap int) rt.GoSlice -//go:linkname assertI2I runtime.assertI2I -//goland:noinspection GoUnusedParameter -func assertI2I(inter *rt.GoType, i rt.GoIface) rt.GoIface - //go:linkname mapiternext runtime.mapiternext //goland:noinspection GoUnusedParameter func mapiternext(it *rt.GoMapIterator) diff --git a/internal/encoder/stubs_go117.go b/internal/encoder/stubs_go117.go index 6c8c6ec75..7d934be33 100644 --- a/internal/encoder/stubs_go117.go +++ b/internal/encoder/stubs_go117.go @@ -38,10 +38,6 @@ func memmove(to unsafe.Pointer, from unsafe.Pointer, n uintptr) //goland:noinspection GoUnusedParameter func growslice(et *rt.GoType, old rt.GoSlice, cap int) rt.GoSlice -//go:linkname assertI2I runtime.assertI2I2 -//goland:noinspection GoUnusedParameter -func assertI2I(inter *rt.GoType, i rt.GoIface) rt.GoIface - //go:linkname mapiternext runtime.mapiternext //goland:noinspection GoUnusedParameter func mapiternext(it *rt.GoMapIterator) diff --git a/internal/encoder/stubs_go120.go b/internal/encoder/stubs_go120.go index 94a2c0f56..ce3c88e9a 100644 --- a/internal/encoder/stubs_go120.go +++ b/internal/encoder/stubs_go120.go @@ -38,10 +38,6 @@ func memmove(to unsafe.Pointer, from unsafe.Pointer, n uintptr) //goland:noinspection GoUnusedParameter func growslice(et *rt.GoType, old rt.GoSlice, cap int) rt.GoSlice -//go:linkname assertI2I runtime.assertI2I2 -//goland:noinspection GoUnusedParameter -func assertI2I(inter *rt.GoType, i rt.GoIface) rt.GoIface - //go:linkname mapiternext runtime.mapiternext //goland:noinspection GoUnusedParameter func mapiternext(it *rt.GoMapIterator) diff --git a/internal/encoder/stubs_go121.go b/internal/encoder/stubs_go121.go index e194fbbf3..700ddf8b5 100644 --- a/internal/encoder/stubs_go121.go +++ b/internal/encoder/stubs_go121.go @@ -38,10 +38,6 @@ func memmove(to unsafe.Pointer, from unsafe.Pointer, n uintptr) //goland:noinspection GoUnusedParameter func growslice(et *rt.GoType, old rt.GoSlice, cap int) rt.GoSlice -//go:linkname assertI2I runtime.assertI2I2 -//goland:noinspection GoUnusedParameter -func assertI2I(inter *rt.GoType, i rt.GoIface) rt.GoIface - //go:linkname mapiternext runtime.mapiternext //goland:noinspection GoUnusedParameter func mapiternext(it *rt.GoMapIterator) diff --git a/internal/jit/runtime.go b/internal/jit/runtime.go index ec69d067a..e4bc829da 100644 --- a/internal/jit/runtime.go +++ b/internal/jit/runtime.go @@ -24,11 +24,6 @@ import ( `github.com/twitchyliquid64/golang-asm/obj` ) -//go:noescape -//go:linkname getitab runtime.getitab -//goland:noinspection ALL -func getitab(inter *rt.GoType, typ *rt.GoType, canfail bool) *rt.GoItab - func Func(f interface{}) obj.Addr { if p := rt.UnpackEface(f); p.Type.Kind() != reflect.Func { panic("f is not a function") @@ -42,7 +37,7 @@ func Type(t reflect.Type) obj.Addr { } func Itab(i *rt.GoType, t reflect.Type) obj.Addr { - return Imm(int64(uintptr(unsafe.Pointer(getitab(i, rt.UnpackType(t), false))))) + return Imm(int64(uintptr(unsafe.Pointer(rt.Getitab(rt.IfaceType(i), rt.UnpackType(t), false))))) } func Gitab(i *rt.GoItab) obj.Addr { diff --git a/internal/rt/fastvalue.go b/internal/rt/fastvalue.go index 2b2757f5b..befaeb715 100644 --- a/internal/rt/fastvalue.go +++ b/internal/rt/fastvalue.go @@ -211,3 +211,24 @@ func findReflectRtypeItab() *GoItab { v := reflect.TypeOf(struct{}{}) return (*GoIface)(unsafe.Pointer(&v)).Itab } + +func AssertI2I2(t *GoType, i GoIface) (r GoIface) { + inter := IfaceType(t) + tab := i.Itab + if tab == nil { + return + } + if (*GoInterfaceType)(tab.it) != inter { + tab = Getitab(inter, tab.Vt, true) + if tab == nil { + return + } + } + r.Itab = tab + r.Value = i.Value + return +} + +//go:noescape +//go:linkname Getitab runtime.getitab +func Getitab(inter *GoInterfaceType, typ *GoType, canfail bool) *GoItab diff --git a/issue_test/issue242_test.go b/issue_test/issue242_test.go index ec03508cb..98330a8ad 100644 --- a/issue_test/issue242_test.go +++ b/issue_test/issue242_test.go @@ -1,3 +1,5 @@ +// +build !go1.22 + /* * Copyright 2021 ByteDance Inc. * diff --git a/loader/funcdata_go121.go b/loader/funcdata_go121.go index f50663e2a..ebeaca5a7 100644 --- a/loader/funcdata_go121.go +++ b/loader/funcdata_go121.go @@ -1,5 +1,5 @@ -//go:build go1.21 && !go1.22 -// +build go1.21,!go1.22 +//go:build go1.21 && !go1.23 +// +build go1.21,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/loader/funcdata_latest.go b/loader/funcdata_latest.go index 52c6097fb..08618dca4 100644 --- a/loader/funcdata_latest.go +++ b/loader/funcdata_latest.go @@ -1,5 +1,5 @@ -// go:build go1.18 && !go1.22 -// +build go1.18,!go1.22 +// go:build go1.18 && !go1.23 +// +build go1.18,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/loader/loader_latest.go b/loader/loader_latest.go index b6e3e75f8..3664c04ba 100644 --- a/loader/loader_latest.go +++ b/loader/loader_latest.go @@ -1,5 +1,4 @@ -//go:build go1.16 && !go1.22 -// +build go1.16,!go1.22 +// +build go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/search_test.go b/search_test.go index 4e8c7c4df..4bb95ea6e 100644 --- a/search_test.go +++ b/search_test.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/sonic.go b/sonic.go index 91effec7e..145527fc0 100644 --- a/sonic.go +++ b/sonic.go @@ -1,4 +1,4 @@ -// +build amd64,go1.16,!go1.22 +// +build amd64,go1.16,!go1.23 /* * Copyright 2021 ByteDance Inc. diff --git a/use_number_test.go b/use_number_test.go deleted file mode 100644 index bdaed778a..000000000 --- a/use_number_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// +build amd64,go1.16,!go1.22 - -/* - * Copyright 2021 ByteDance Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sonic - -import ( - `encoding/json` - `reflect` - `testing` - - `github.com/bytedance/sonic/decoder` -) - -type useInt64Test struct { - in string - out int64 -} - -type useFloatTest struct { - in string - out float64 -} - -var useinttest = []useInt64Test{ - // int64 - {"0", 0}, - {"1", 1}, - {"-1", -1}, - {"100", 100}, - - {"-9223372036854775807", -9223372036854775807}, - {"-9223372036854775808", -9223372036854775808}, //min int64 - {"9223372036854775807", 9223372036854775807}, //max int64 - {"9223372036854775806", 9223372036854775806}, -} - -var usefloattest = []useFloatTest{ - // float64 - {"-9223372036854775809", -9223372036854775809}, // int64 overflow - {"9223372036854775808", 9223372036854775808}, // int64 overflow - {"1e2", 1e2}, - {"1e-20", 1e-20}, - {"1.0", 1}, -} - -func TestUseInt64(t *testing.T) { - for i, tt := range useinttest { - var sout interface{} - dc := decoder.NewDecoder(tt.in) - dc.UseInt64() - serr := dc.Decode(&sout) - if !reflect.DeepEqual(sout, tt.out) { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.in) - } - if serr != nil { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) - } - } - - for i, tt := range usefloattest { - var sout interface{} - dc := decoder.NewDecoder(tt.in) - dc.UseInt64() - //the input string is not int64, still return float64 - serr := dc.Decode(&sout) - if !reflect.DeepEqual(sout, tt.out) { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.in) - } - if serr != nil { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) - } - } -} - -func TestUseNumber(t *testing.T) { - for i, tt := range useinttest { - var sout interface{} - dc := decoder.NewDecoder(tt.in) - dc.UseNumber() - serr := dc.Decode(&sout) - if !reflect.DeepEqual(sout, json.Number(tt.in)) { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.out) - } - if serr != nil { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) - } - } - - for i, tt := range usefloattest { - var sout interface{} - dc := decoder.NewDecoder(tt.in) - dc.UseNumber() - serr := dc.Decode(&sout) - if !reflect.DeepEqual(sout, json.Number(tt.in)) { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n %#v\n", i, tt.in, sout, tt.out) - } - if serr != nil { - t.Errorf("Test %d, %#v\ngot:\n %#v\nexp:\n nil\n", i, tt, serr) - } - } -}