pax_global_header00006660000000000000000000000064137147526450014530gustar00rootroot0000000000000052 comment=8ab5ff9cd8e4e432e8b79f6c47d324a31dd803cf easyjson-0.7.6/000077500000000000000000000000001371475264500133755ustar00rootroot00000000000000easyjson-0.7.6/.gitignore000066400000000000000000000000541371475264500153640ustar00rootroot00000000000000.root *_easyjson.go *.iml .idea *.swp bin/* easyjson-0.7.6/.travis.yml000066400000000000000000000001741371475264500155100ustar00rootroot00000000000000language: go go: - tip - stable matrix: allow_failures: - go: tip install: - go get golang.org/x/lint/golint easyjson-0.7.6/LICENSE000066400000000000000000000020411371475264500143770ustar00rootroot00000000000000Copyright (c) 2016 Mail.Ru Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. easyjson-0.7.6/Makefile000066400000000000000000000034001371475264500150320ustar00rootroot00000000000000all: test clean: rm -rf bin rm -rf tests/*_easyjson.go rm -rf benchmark/*_easyjson.go build: go build -i -o ./bin/easyjson ./easyjson generate: build bin/easyjson -stubs \ ./tests/snake.go \ ./tests/data.go \ ./tests/omitempty.go \ ./tests/nothing.go \ ./tests/named_type.go \ ./tests/custom_map_key_type.go \ ./tests/embedded_type.go \ ./tests/reference_to_pointer.go \ ./tests/html.go \ ./tests/unknown_fields.go \ ./tests/type_declaration.go \ ./tests/type_declaration_skip.go \ ./tests/members_escaped.go \ ./tests/members_unescaped.go \ ./tests/intern.go \ ./tests/nocopy.go \ ./tests/escaping.go bin/easyjson -all \ ./tests/data.go \ ./tests/nothing.go \ ./tests/errors.go \ ./tests/html.go \ ./tests/type_declaration_skip.go bin/easyjson \ ./tests/nested_easy.go \ ./tests/named_type.go \ ./tests/custom_map_key_type.go \ ./tests/embedded_type.go \ ./tests/reference_to_pointer.go \ ./tests/key_marshaler_map.go \ ./tests/unknown_fields.go \ ./tests/type_declaration.go \ ./tests/members_escaped.go \ ./tests/intern.go \ ./tests/nocopy.go \ ./tests/escaping.go \ ./tests/nested_marshaler.go bin/easyjson -snake_case ./tests/snake.go bin/easyjson -omit_empty ./tests/omitempty.go bin/easyjson -build_tags=use_easyjson -disable_members_unescape ./benchmark/data.go bin/easyjson -disallow_unknown_fields ./tests/disallow_unknown.go bin/easyjson -disable_members_unescape ./tests/members_unescaped.go test: generate go test \ ./tests \ ./jlexer \ ./gen \ ./buffer cd benchmark && go test -benchmem -tags use_easyjson -bench . golint -set_exit_status ./tests/*_easyjson.go bench-other: generate cd benchmark && make bench-python: benchmark/ujson.sh .PHONY: clean generate test build easyjson-0.7.6/README.md000066400000000000000000000407731371475264500146670ustar00rootroot00000000000000# easyjson [![Build Status](https://travis-ci.org/mailru/easyjson.svg?branch=master)](https://travis-ci.org/mailru/easyjson) [![Go Report Card](https://goreportcard.com/badge/github.com/mailru/easyjson)](https://goreportcard.com/report/github.com/mailru/easyjson) Package easyjson provides a fast and easy way to marshal/unmarshal Go structs to/from JSON without the use of reflection. In performance tests, easyjson outperforms the standard `encoding/json` package by a factor of 4-5x, and other JSON encoding packages by a factor of 2-3x. easyjson aims to keep generated Go code simple enough so that it can be easily optimized or fixed. Another goal is to provide users with the ability to customize the generated code by providing options not available with the standard `encoding/json` package, such as generating "snake_case" names or enabling `omitempty` behavior by default. ## Usage ```sh # install go get -u github.com/mailru/easyjson/... # run easyjson -all .go ``` The above will generate `_easyjson.go` containing the appropriate marshaler and unmarshaler funcs for all structs contained in `.go`. Please note that easyjson requires a full Go build environment and the `GOPATH` environment variable to be set. This is because easyjson code generation invokes `go run` on a temporary file (an approach to code generation borrowed from [ffjson](https://github.com/pquerna/ffjson)). ## Options ```txt Usage of easyjson: -all generate marshaler/unmarshalers for all structs in a file -build_tags string build tags to add to generated file -gen_build_flags string build flags when running the generator while bootstrapping -byte use simple bytes instead of Base64Bytes for slice of bytes -leave_temps do not delete temporary files -no_std_marshalers don't generate MarshalJSON/UnmarshalJSON funcs -noformat do not run 'gofmt -w' on output file -omit_empty omit empty fields by default -output_filename string specify the filename of the output -pkg process the whole package instead of just the given file -snake_case use snake_case names instead of CamelCase by default -lower_camel_case use lowerCamelCase instead of CamelCase by default -stubs only generate stubs for marshaler/unmarshaler funcs -disallow_unknown_fields return error if some unknown field in json appeared -disable_members_unescape disable unescaping of \uXXXX string sequences in member names ``` Using `-all` will generate marshalers/unmarshalers for all Go structs in the file excluding those structs whose preceding comment starts with `easyjson:skip`. For example: ```go //easyjson:skip type A struct {} ``` If `-all` is not provided, then only those structs whose preceding comment starts with `easyjson:json` will have marshalers/unmarshalers generated. For example: ```go //easyjson:json type A struct {} ``` Additional option notes: * `-snake_case` tells easyjson to generate snake\_case field names by default (unless overridden by a field tag). The CamelCase to snake\_case conversion algorithm should work in most cases (ie, HTTPVersion will be converted to "http_version"). * `-build_tags` will add the specified build tags to generated Go sources. * `-gen_build_flags` will execute the easyjson bootstapping code to launch the actual generator command with provided flags. Multiple arguments should be separated by space e.g. `-gen_build_flags="-mod=mod -x"`. ## Structure json tag options Besides standart json tag options like 'omitempty' the following are supported: * 'nocopy' - disables allocation and copying of string values, making them refer to original json buffer memory. This works great for short lived objects which are not hold in memory after decoding and immediate usage. Note if string requires unescaping it will be processed as normally. * 'intern' - string "interning" (deduplication) to save memory when the very same string dictionary values are often met all over the structure. See below for more details. ## Generated Marshaler/Unmarshaler Funcs For Go struct types, easyjson generates the funcs `MarshalEasyJSON` / `UnmarshalEasyJSON` for marshaling/unmarshaling JSON. In turn, these satisfy the `easyjson.Marshaler` and `easyjson.Unmarshaler` interfaces and when used in conjunction with `easyjson.Marshal` / `easyjson.Unmarshal` avoid unnecessary reflection / type assertions during marshaling/unmarshaling to/from JSON for Go structs. easyjson also generates `MarshalJSON` and `UnmarshalJSON` funcs for Go struct types compatible with the standard `json.Marshaler` and `json.Unmarshaler` interfaces. Please be aware that using the standard `json.Marshal` / `json.Unmarshal` for marshaling/unmarshaling will incur a significant performance penalty when compared to using `easyjson.Marshal` / `easyjson.Unmarshal`. Additionally, easyjson exposes utility funcs that use the `MarshalEasyJSON` and `UnmarshalEasyJSON` for marshaling/unmarshaling to and from standard readers and writers. For example, easyjson provides `easyjson.MarshalToHTTPResponseWriter` which marshals to the standard `http.ResponseWriter`. Please see the [GoDoc listing](https://godoc.org/github.com/mailru/easyjson) for the full listing of utility funcs that are available. ## Controlling easyjson Marshaling and Unmarshaling Behavior Go types can provide their own `MarshalEasyJSON` and `UnmarshalEasyJSON` funcs that satisfy the `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces. These will be used by `easyjson.Marshal` and `easyjson.Unmarshal` when defined for a Go type. Go types can also satisfy the `easyjson.Optional` interface, which allows the type to define its own `omitempty` logic. ## Type Wrappers easyjson provides additional type wrappers defined in the `easyjson/opt` package. These wrap the standard Go primitives and in turn satisfy the easyjson interfaces. The `easyjson/opt` type wrappers are useful when needing to distinguish between a missing value and/or when needing to specifying a default value. Type wrappers allow easyjson to avoid additional pointers and heap allocations and can significantly increase performance when used properly. ## Memory Pooling easyjson uses a buffer pool that allocates data in increasing chunks from 128 to 32768 bytes. Chunks of 512 bytes and larger will be reused with the help of `sync.Pool`. The maximum size of a chunk is bounded to reduce redundant memory allocation and to allow larger reusable buffers. easyjson's custom allocation buffer pool is defined in the `easyjson/buffer` package, and the default behavior pool behavior can be modified (if necessary) through a call to `buffer.Init()` prior to any marshaling or unmarshaling. Please see the [GoDoc listing](https://godoc.org/github.com/mailru/easyjson/buffer) for more information. ## String interning During unmarshaling, `string` field values can be optionally [interned](https://en.wikipedia.org/wiki/String_interning) to reduce memory allocations and usage by deduplicating strings in memory, at the expense of slightly increased CPU usage. This will work effectively only for `string` fields being decoded that have frequently the same value (e.g. if you have a string field that can only assume a small number of possible values). To enable string interning, add the `intern` keyword tag to your `json` tag on `string` fields, e.g.: ```go type Foo struct { UUID string `json:"uuid"` // will not be interned during unmarshaling State string `json:"state,intern"` // will be interned during unmarshaling } ``` ## Issues, Notes, and Limitations * easyjson is still early in its development. As such, there are likely to be bugs and missing features when compared to `encoding/json`. In the case of a missing feature or bug, please create a GitHub issue. Pull requests are welcome! * Unlike `encoding/json`, object keys are case-sensitive. Case-insensitive matching is not currently provided due to the significant performance hit when doing case-insensitive key matching. In the future, case-insensitive object key matching may be provided via an option to the generator. * easyjson makes use of `unsafe`, which simplifies the code and provides significant performance benefits by allowing no-copy conversion from `[]byte` to `string`. That said, `unsafe` is used only when unmarshaling and parsing JSON, and any `unsafe` operations / memory allocations done will be safely deallocated by easyjson. Set the build tag `easyjson_nounsafe` to compile it without `unsafe`. * easyjson is compatible with Google App Engine. The `appengine` build tag (set by App Engine's environment) will automatically disable the use of `unsafe`, which is not allowed in App Engine's Standard Environment. Note that the use with App Engine is still experimental. * Floats are formatted using the default precision from Go's `strconv` package. As such, easyjson will not correctly handle high precision floats when marshaling/unmarshaling JSON. Note, however, that there are very few/limited uses where this behavior is not sufficient for general use. That said, a different package may be needed if precise marshaling/unmarshaling of high precision floats to/from JSON is required. * While unmarshaling, the JSON parser does the minimal amount of work needed to skip over unmatching parens, and as such full validation is not done for the entire JSON value being unmarshaled/parsed. * Currently there is no true streaming support for encoding/decoding as typically for many uses/protocols the final, marshaled length of the JSON needs to be known prior to sending the data. Currently this is not possible with easyjson's architecture. * easyjson parser and codegen based on reflection, so it won't work on `package main` files, because they cant be imported by parser. ## Benchmarks Most benchmarks were done using the example [13kB example JSON](https://dev.twitter.com/rest/reference/get/search/tweets) (9k after eliminating whitespace). This example is similar to real-world data, is well-structured, and contains a healthy variety of different types, making it ideal for JSON serialization benchmarks. Note: * For small request benchmarks, an 80 byte portion of the above example was used. * For large request marshaling benchmarks, a struct containing 50 regular samples was used, making a ~500kB output JSON. * Benchmarks are showing the results of easyjson's default behaviour, which makes use of `unsafe`. Benchmarks are available in the repository and can be run by invoking `make`. ### easyjson vs. encoding/json easyjson is roughly 5-6 times faster than the standard `encoding/json` for unmarshaling, and 3-4 times faster for non-concurrent marshaling. Concurrent marshaling is 6-7x faster if marshaling to a writer. ### easyjson vs. ffjson easyjson uses the same approach for JSON marshaling as [ffjson](https://github.com/pquerna/ffjson), but takes a significantly different approach to lexing and parsing JSON during unmarshaling. This means easyjson is roughly 2-3x faster for unmarshaling and 1.5-2x faster for non-concurrent unmarshaling. As of this writing, `ffjson` seems to have issues when used concurrently: specifically, large request pooling hurts `ffjson`'s performance and causes scalability issues. These issues with `ffjson` can likely be fixed, but as of writing remain outstanding/known issues with `ffjson`. easyjson and `ffjson` have similar performance for small requests, however easyjson outperforms `ffjson` by roughly 2-5x times for large requests when used with a writer. ### easyjson vs. go/codec [go/codec](https://github.com/ugorji/go) provides compile-time helpers for JSON generation. In this case, helpers do not work like marshalers as they are encoding-independent. easyjson is generally 2x faster than `go/codec` for non-concurrent benchmarks and about 3x faster for concurrent encoding (without marshaling to a writer). In an attempt to measure marshaling performance of `go/codec` (as opposed to allocations/memcpy/writer interface invocations), a benchmark was done with resetting length of a byte slice rather than resetting the whole slice to nil. However, the optimization in this exact form may not be applicable in practice, since the memory is not freed between marshaling operations. ### easyjson vs 'ujson' python module [ujson](https://github.com/esnme/ultrajson) is using C code for parsing, so it is interesting to see how plain golang compares to that. It is important to note that the resulting object for python is slower to access, since the library parses JSON object into dictionaries. easyjson is slightly faster for unmarshaling and 2-3x faster than `ujson` for marshaling. ### Benchmark Results `ffjson` results are from February 4th, 2016, using the latest `ffjson` and go1.6. `go/codec` results are from March 4th, 2016, using the latest `go/codec` and go1.6. #### Unmarshaling | lib | json size | MB/s | allocs/op | B/op | |:---------|:----------|-----:|----------:|------:| | standard | regular | 22 | 218 | 10229 | | standard | small | 9.7 | 14 | 720 | | | | | | | | easyjson | regular | 125 | 128 | 9794 | | easyjson | small | 67 | 3 | 128 | | | | | | | | ffjson | regular | 66 | 141 | 9985 | | ffjson | small | 17.6 | 10 | 488 | | | | | | | | codec | regular | 55 | 434 | 19299 | | codec | small | 29 | 7 | 336 | | | | | | | | ujson | regular | 103 | N/A | N/A | #### Marshaling, one goroutine. | lib | json size | MB/s | allocs/op | B/op | |:----------|:----------|-----:|----------:|------:| | standard | regular | 75 | 9 | 23256 | | standard | small | 32 | 3 | 328 | | standard | large | 80 | 17 | 1.2M | | | | | | | | easyjson | regular | 213 | 9 | 10260 | | easyjson* | regular | 263 | 8 | 742 | | easyjson | small | 125 | 1 | 128 | | easyjson | large | 212 | 33 | 490k | | easyjson* | large | 262 | 25 | 2879 | | | | | | | | ffjson | regular | 122 | 153 | 21340 | | ffjson** | regular | 146 | 152 | 4897 | | ffjson | small | 36 | 5 | 384 | | ffjson** | small | 64 | 4 | 128 | | ffjson | large | 134 | 7317 | 818k | | ffjson** | large | 125 | 7320 | 827k | | | | | | | | codec | regular | 80 | 17 | 33601 | | codec*** | regular | 108 | 9 | 1153 | | codec | small | 42 | 3 | 304 | | codec*** | small | 56 | 1 | 48 | | codec | large | 73 | 483 | 2.5M | | codec*** | large | 103 | 451 | 66007 | | | | | | | | ujson | regular | 92 | N/A | N/A | \* marshaling to a writer, \*\* using `ffjson.Pool()`, \*\*\* reusing output slice instead of resetting it to nil #### Marshaling, concurrent. | lib | json size | MB/s | allocs/op | B/op | |:----------|:----------|-----:|----------:|------:| | standard | regular | 252 | 9 | 23257 | | standard | small | 124 | 3 | 328 | | standard | large | 289 | 17 | 1.2M | | | | | | | | easyjson | regular | 792 | 9 | 10597 | | easyjson* | regular | 1748 | 8 | 779 | | easyjson | small | 333 | 1 | 128 | | easyjson | large | 718 | 36 | 548k | | easyjson* | large | 2134 | 25 | 4957 | | | | | | | | ffjson | regular | 301 | 153 | 21629 | | ffjson** | regular | 707 | 152 | 5148 | | ffjson | small | 62 | 5 | 384 | | ffjson** | small | 282 | 4 | 128 | | ffjson | large | 438 | 7330 | 1.0M | | ffjson** | large | 131 | 7319 | 820k | | | | | | | | codec | regular | 183 | 17 | 33603 | | codec*** | regular | 671 | 9 | 1157 | | codec | small | 147 | 3 | 304 | | codec*** | small | 299 | 1 | 48 | | codec | large | 190 | 483 | 2.5M | | codec*** | large | 752 | 451 | 77574 | \* marshaling to a writer, \*\* using `ffjson.Pool()`, \*\*\* reusing output slice instead of resetting it to nil easyjson-0.7.6/benchmark/000077500000000000000000000000001371475264500153275ustar00rootroot00000000000000easyjson-0.7.6/benchmark/Makefile000066400000000000000000000002511371475264500167650ustar00rootroot00000000000000all: go test -benchmem -bench . go test -benchmem -tags use_ffjson -bench . go test -benchmem -tags use_jsoniter -bench . go test -benchmem -tags use_codec -bench . easyjson-0.7.6/benchmark/codec_test.go000066400000000000000000000121131371475264500177700ustar00rootroot00000000000000// +build use_codec package benchmark import ( "testing" "github.com/ugorji/go/codec" ) func BenchmarkCodec_Unmarshal_M(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) dec := codec.NewDecoderBytes(nil, h) b.SetBytes(int64(len(largeStructText))) for i := 0; i < b.N; i++ { var s LargeStruct dec.ResetBytes(largeStructText) if err := dec.Decode(&s); err != nil { b.Error(err) } } } func BenchmarkCodec_Unmarshal_S(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) dec := codec.NewDecoderBytes(nil, h) b.SetBytes(int64(len(smallStructText))) for i := 0; i < b.N; i++ { var s LargeStruct dec.ResetBytes(smallStructText) if err := dec.Decode(&s); err != nil { b.Error(err) } } } func BenchmarkCodec_Marshal_S(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&smallStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } b.SetBytes(l) } func BenchmarkCodec_Marshal_M(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&largeStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } b.SetBytes(l) } func BenchmarkCodec_Marshal_L(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&xlStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } b.SetBytes(l) } func BenchmarkCodec_Marshal_S_Reuse(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&smallStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } b.SetBytes(l) } func BenchmarkCodec_Marshal_M_Reuse(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&largeStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } b.SetBytes(l) } func BenchmarkCodec_Marshal_L_Reuse(b *testing.B) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) var l int64 for i := 0; i < b.N; i++ { enc.ResetBytes(&out) if err := enc.Encode(&xlStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } b.SetBytes(l) } func BenchmarkCodec_Marshal_S_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var out []byte var h codec.Handle = new(codec.JsonHandle) enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&smallStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } }) b.SetBytes(l) } func BenchmarkCodec_Marshal_M_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&largeStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } }) b.SetBytes(l) } func BenchmarkCodec_Marshal_L_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&xlStructData); err != nil { b.Error(err) } l = int64(len(out)) out = nil } }) b.SetBytes(l) } func BenchmarkCodec_Marshal_S_Parallel_Reuse(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var out []byte var h codec.Handle = new(codec.JsonHandle) enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&smallStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } }) b.SetBytes(l) } func BenchmarkCodec_Marshal_M_Parallel_Reuse(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&largeStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } }) b.SetBytes(l) } func BenchmarkCodec_Marshal_L_Parallel_Reuse(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { var h codec.Handle = new(codec.JsonHandle) var out []byte enc := codec.NewEncoderBytes(&out, h) for pb.Next() { enc.ResetBytes(&out) if err := enc.Encode(&xlStructData); err != nil { b.Error(err) } l = int64(len(out)) out = out[:0] } }) b.SetBytes(l) } easyjson-0.7.6/benchmark/data.go000066400000000000000000000137051371475264500165750ustar00rootroot00000000000000// Package benchmark provides a simple benchmark for easyjson against default serialization and ffjson. // The data example is taken from https://dev.twitter.com/rest/reference/get/search/tweets package benchmark import ( "io/ioutil" ) var largeStructText, _ = ioutil.ReadFile("example.json") var xlStructData XLStruct func init() { for i := 0; i < 50; i++ { xlStructData.Data = append(xlStructData.Data, largeStructData) } } var smallStructText = []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`) var smallStructData = Entities{ Hashtags: []Hashtag{{Indices: []int{5, 10}, Text: "some-text"}}, Urls: []*string{}, UserMentions: []*string{}, } type SearchMetadata struct { CompletedIn float64 `json:"completed_in"` Count int `json:"count"` MaxID int64 `json:"max_id"` MaxIDStr string `json:"max_id_str"` NextResults string `json:"next_results"` Query string `json:"query"` RefreshURL string `json:"refresh_url"` SinceID int64 `json:"since_id"` SinceIDStr string `json:"since_id_str"` } type Hashtag struct { Indices []int `json:"indices"` Text string `json:"text"` } //easyjson:json type Entities struct { Hashtags []Hashtag `json:"hashtags"` Urls []*string `json:"urls"` UserMentions []*string `json:"user_mentions"` } type UserEntityDescription struct { Urls []*string `json:"urls"` } type URL struct { ExpandedURL *string `json:"expanded_url"` Indices []int `json:"indices"` URL string `json:"url"` } type UserEntityURL struct { Urls []URL `json:"urls"` } type UserEntities struct { Description UserEntityDescription `json:"description"` URL UserEntityURL `json:"url"` } type User struct { ContributorsEnabled bool `json:"contributors_enabled"` CreatedAt string `json:"created_at"` DefaultProfile bool `json:"default_profile"` DefaultProfileImage bool `json:"default_profile_image"` Description string `json:"description"` Entities UserEntities `json:"entities"` FavouritesCount int `json:"favourites_count"` FollowRequestSent *string `json:"follow_request_sent"` FollowersCount int `json:"followers_count"` Following *string `json:"following"` FriendsCount int `json:"friends_count"` GeoEnabled bool `json:"geo_enabled"` ID int `json:"id"` IDStr string `json:"id_str"` IsTranslator bool `json:"is_translator"` Lang string `json:"lang"` ListedCount int `json:"listed_count"` Location string `json:"location"` Name string `json:"name"` Notifications *string `json:"notifications"` ProfileBackgroundColor string `json:"profile_background_color"` ProfileBackgroundImageURL string `json:"profile_background_image_url"` ProfileBackgroundImageURLHTTPS string `json:"profile_background_image_url_https"` ProfileBackgroundTile bool `json:"profile_background_tile"` ProfileImageURL string `json:"profile_image_url"` ProfileImageURLHTTPS string `json:"profile_image_url_https"` ProfileLinkColor string `json:"profile_link_color"` ProfileSidebarBorderColor string `json:"profile_sidebar_border_color"` ProfileSidebarFillColor string `json:"profile_sidebar_fill_color"` ProfileTextColor string `json:"profile_text_color"` ProfileUseBackgroundImage bool `json:"profile_use_background_image"` Protected bool `json:"protected"` ScreenName string `json:"screen_name"` ShowAllInlineMedia bool `json:"show_all_inline_media"` StatusesCount int `json:"statuses_count"` TimeZone string `json:"time_zone"` URL *string `json:"url"` UtcOffset int `json:"utc_offset"` Verified bool `json:"verified"` } type StatusMetadata struct { IsoLanguageCode string `json:"iso_language_code"` ResultType string `json:"result_type"` } type Status struct { Contributors *string `json:"contributors"` Coordinates *string `json:"coordinates"` CreatedAt string `json:"created_at"` Entities Entities `json:"entities"` Favorited bool `json:"favorited"` Geo *string `json:"geo"` ID int64 `json:"id"` IDStr string `json:"id_str"` InReplyToScreenName *string `json:"in_reply_to_screen_name"` InReplyToStatusID *string `json:"in_reply_to_status_id"` InReplyToStatusIDStr *string `json:"in_reply_to_status_id_str"` InReplyToUserID *string `json:"in_reply_to_user_id"` InReplyToUserIDStr *string `json:"in_reply_to_user_id_str"` Metadata StatusMetadata `json:"metadata"` Place *string `json:"place"` RetweetCount int `json:"retweet_count"` Retweeted bool `json:"retweeted"` Source string `json:"source"` Text string `json:"text"` Truncated bool `json:"truncated"` User User `json:"user"` } //easyjson:json type LargeStruct struct { SearchMetadata SearchMetadata `json:"search_metadata"` Statuses []Status `json:"statuses"` } //easyjson:json type XLStruct struct { Data []LargeStruct } easyjson-0.7.6/benchmark/data_codec.go000066400000000000000000002562151371475264500177370ustar00rootroot00000000000000// +build go1.6 // +build use_codec // +build !easyjson_nounsafe // +build !appengine // Code generated by codecgen - DO NOT EDIT. package benchmark import ( "errors" codec1978 "github.com/ugorji/go/codec" "runtime" "strconv" ) const ( // ----- content types ---- codecSelferCcUTF82736 = 1 codecSelferCcRAW2736 = 255 // ----- value types used ---- codecSelferValueTypeArray2736 = 10 codecSelferValueTypeMap2736 = 9 codecSelferValueTypeString2736 = 6 codecSelferValueTypeInt2736 = 2 codecSelferValueTypeUint2736 = 3 codecSelferValueTypeFloat2736 = 4 codecSelferValueTypeNil2736 = 1 codecSelferBitsize2736 = uint8(32 << (^uint(0) >> 63)) codecSelferDecContainerLenNil2736 = -2147483648 ) var ( errCodecSelferOnlyMapOrArrayEncodeToStruct2736 = errors.New(`only encoded map or array can be decoded into a struct`) ) type codecSelfer2736 struct{} func codecSelfer2736False() bool { return false } func init() { if codec1978.GenVersion != 16 { _, file, _, _ := runtime.Caller(0) ver := strconv.FormatInt(int64(codec1978.GenVersion), 10) panic("codecgen version mismatch: current: 16, need " + ver + ". Re-generate file: " + file) } } func (x *SearchMetadata) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(9) z.EncWriteArrayElem() r.EncodeFloat64(float64(x.CompletedIn)) z.EncWriteArrayElem() r.EncodeInt(int64(x.Count)) z.EncWriteArrayElem() r.EncodeInt(int64(x.MaxID)) z.EncWriteArrayElem() r.EncodeString(string(x.MaxIDStr)) z.EncWriteArrayElem() r.EncodeString(string(x.NextResults)) z.EncWriteArrayElem() r.EncodeString(string(x.Query)) z.EncWriteArrayElem() r.EncodeString(string(x.RefreshURL)) z.EncWriteArrayElem() r.EncodeInt(int64(x.SinceID)) z.EncWriteArrayElem() r.EncodeString(string(x.SinceIDStr)) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(9) z.EncWriteMapElemKey() r.EncodeString(`completed_in`) z.EncWriteMapElemValue() r.EncodeFloat64(float64(x.CompletedIn)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"count\"") } else { r.EncodeString(`count`) } z.EncWriteMapElemValue() r.EncodeInt(int64(x.Count)) z.EncWriteMapElemKey() r.EncodeString(`max_id`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.MaxID)) z.EncWriteMapElemKey() r.EncodeString(`max_id_str`) z.EncWriteMapElemValue() r.EncodeString(string(x.MaxIDStr)) z.EncWriteMapElemKey() r.EncodeString(`next_results`) z.EncWriteMapElemValue() r.EncodeString(string(x.NextResults)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"query\"") } else { r.EncodeString(`query`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Query)) z.EncWriteMapElemKey() r.EncodeString(`refresh_url`) z.EncWriteMapElemValue() r.EncodeString(string(x.RefreshURL)) z.EncWriteMapElemKey() r.EncodeString(`since_id`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.SinceID)) z.EncWriteMapElemKey() r.EncodeString(`since_id_str`) z.EncWriteMapElemValue() r.EncodeString(string(x.SinceIDStr)) z.EncWriteMapEnd() } } } func (x *SearchMetadata) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = SearchMetadata{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *SearchMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "completed_in": x.CompletedIn = (float64)(r.DecodeFloat64()) case "count": x.Count = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "max_id": x.MaxID = (int64)(r.DecodeInt64()) case "max_id_str": x.MaxIDStr = (string)(string(r.DecodeStringAsBytes())) case "next_results": x.NextResults = (string)(string(r.DecodeStringAsBytes())) case "query": x.Query = (string)(string(r.DecodeStringAsBytes())) case "refresh_url": x.RefreshURL = (string)(string(r.DecodeStringAsBytes())) case "since_id": x.SinceID = (int64)(r.DecodeInt64()) case "since_id_str": x.SinceIDStr = (string)(string(r.DecodeStringAsBytes())) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *SearchMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj13 int var yyb13 bool var yyhl13 bool = l >= 0 yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.CompletedIn = (float64)(r.DecodeFloat64()) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Count = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.MaxID = (int64)(r.DecodeInt64()) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.MaxIDStr = (string)(string(r.DecodeStringAsBytes())) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.NextResults = (string)(string(r.DecodeStringAsBytes())) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Query = (string)(string(r.DecodeStringAsBytes())) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.RefreshURL = (string)(string(r.DecodeStringAsBytes())) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.SinceID = (int64)(r.DecodeInt64()) yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.SinceIDStr = (string)(string(r.DecodeStringAsBytes())) for { yyj13++ if yyhl13 { yyb13 = yyj13 > l } else { yyb13 = z.DecCheckBreak() } if yyb13 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj13-1, "") } } func (x *Hashtag) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(2) z.EncWriteArrayElem() if x.Indices == nil { r.EncodeNil() } else { z.F.EncSliceIntV(x.Indices, e) } // end block: if x.Indices slice == nil z.EncWriteArrayElem() r.EncodeString(string(x.Text)) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(2) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"indices\"") } else { r.EncodeString(`indices`) } z.EncWriteMapElemValue() if x.Indices == nil { r.EncodeNil() } else { z.F.EncSliceIntV(x.Indices, e) } // end block: if x.Indices slice == nil z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"text\"") } else { r.EncodeString(`text`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Text)) z.EncWriteMapEnd() } } } func (x *Hashtag) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = Hashtag{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *Hashtag) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "indices": z.F.DecSliceIntX(&x.Indices, d) case "text": x.Text = (string)(string(r.DecodeStringAsBytes())) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *Hashtag) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj7 int var yyb7 bool var yyhl7 bool = l >= 0 yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { z.DecReadArrayEnd() return } z.DecReadArrayElem() z.F.DecSliceIntX(&x.Indices, d) yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Text = (string)(string(r.DecodeStringAsBytes())) for { yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj7-1, "") } } func (x *Entities) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(3) z.EncWriteArrayElem() if x.Hashtags == nil { r.EncodeNil() } else { h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) } // end block: if x.Hashtags slice == nil z.EncWriteArrayElem() if x.Urls == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteArrayElem() if x.UserMentions == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.UserMentions), e) } // end block: if x.UserMentions slice == nil z.EncWriteArrayEnd() } else { z.EncWriteMapStart(3) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"hashtags\"") } else { r.EncodeString(`hashtags`) } z.EncWriteMapElemValue() if x.Hashtags == nil { r.EncodeNil() } else { h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) } // end block: if x.Hashtags slice == nil z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"urls\"") } else { r.EncodeString(`urls`) } z.EncWriteMapElemValue() if x.Urls == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteMapElemKey() r.EncodeString(`user_mentions`) z.EncWriteMapElemValue() if x.UserMentions == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.UserMentions), e) } // end block: if x.UserMentions slice == nil z.EncWriteMapEnd() } } } func (x *Entities) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = Entities{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *Entities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "hashtags": h.decSliceHashtag((*[]Hashtag)(&x.Hashtags), d) case "urls": h.decSlicePtrtostring((*[]*string)(&x.Urls), d) case "user_mentions": h.decSlicePtrtostring((*[]*string)(&x.UserMentions), d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *Entities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj10 int var yyb10 bool var yyhl10 bool = l >= 0 yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = z.DecCheckBreak() } if yyb10 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSliceHashtag((*[]Hashtag)(&x.Hashtags), d) yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = z.DecCheckBreak() } if yyb10 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSlicePtrtostring((*[]*string)(&x.Urls), d) yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = z.DecCheckBreak() } if yyb10 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSlicePtrtostring((*[]*string)(&x.UserMentions), d) for { yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = z.DecCheckBreak() } if yyb10 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj10-1, "") } } func (x *UserEntityDescription) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(1) z.EncWriteArrayElem() if x.Urls == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteArrayEnd() } else { z.EncWriteMapStart(1) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"urls\"") } else { r.EncodeString(`urls`) } z.EncWriteMapElemValue() if x.Urls == nil { r.EncodeNil() } else { h.encSlicePtrtostring(([]*string)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteMapEnd() } } } func (x *UserEntityDescription) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = UserEntityDescription{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *UserEntityDescription) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "urls": h.decSlicePtrtostring((*[]*string)(&x.Urls), d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *UserEntityDescription) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj6 int var yyb6 bool var yyhl6 bool = l >= 0 yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSlicePtrtostring((*[]*string)(&x.Urls), d) for { yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj6-1, "") } } func (x *URL) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' var yyn3 bool = x.ExpandedURL == nil if yyr2 || yy2arr2 { z.EncWriteArrayStart(3) if yyn3 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy6 := *x.ExpandedURL r.EncodeString(string(yy6)) } z.EncWriteArrayElem() if x.Indices == nil { r.EncodeNil() } else { z.F.EncSliceIntV(x.Indices, e) } // end block: if x.Indices slice == nil z.EncWriteArrayElem() r.EncodeString(string(x.URL)) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(3) z.EncWriteMapElemKey() r.EncodeString(`expanded_url`) z.EncWriteMapElemValue() if yyn3 { r.EncodeNil() } else { yy10 := *x.ExpandedURL r.EncodeString(string(yy10)) } z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"indices\"") } else { r.EncodeString(`indices`) } z.EncWriteMapElemValue() if x.Indices == nil { r.EncodeNil() } else { z.F.EncSliceIntV(x.Indices, e) } // end block: if x.Indices slice == nil z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"url\"") } else { r.EncodeString(`url`) } z.EncWriteMapElemValue() r.EncodeString(string(x.URL)) z.EncWriteMapEnd() } } } func (x *URL) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = URL{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *URL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "expanded_url": if r.TryNil() { if x.ExpandedURL != nil { // remove the if-true x.ExpandedURL = nil } } else { if x.ExpandedURL == nil { x.ExpandedURL = new(string) } *x.ExpandedURL = (string)(string(r.DecodeStringAsBytes())) } case "indices": z.F.DecSliceIntX(&x.Indices, d) case "url": x.URL = (string)(string(r.DecodeStringAsBytes())) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *URL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj9 int var yyb9 bool var yyhl9 bool = l >= 0 yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = z.DecCheckBreak() } if yyb9 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.ExpandedURL != nil { // remove the if-true x.ExpandedURL = nil } } else { if x.ExpandedURL == nil { x.ExpandedURL = new(string) } *x.ExpandedURL = (string)(string(r.DecodeStringAsBytes())) } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = z.DecCheckBreak() } if yyb9 { z.DecReadArrayEnd() return } z.DecReadArrayElem() z.F.DecSliceIntX(&x.Indices, d) yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = z.DecCheckBreak() } if yyb9 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.URL = (string)(string(r.DecodeStringAsBytes())) for { yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = z.DecCheckBreak() } if yyb9 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj9-1, "") } } func (x *UserEntityURL) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(1) z.EncWriteArrayElem() if x.Urls == nil { r.EncodeNil() } else { h.encSliceURL(([]URL)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteArrayEnd() } else { z.EncWriteMapStart(1) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"urls\"") } else { r.EncodeString(`urls`) } z.EncWriteMapElemValue() if x.Urls == nil { r.EncodeNil() } else { h.encSliceURL(([]URL)(x.Urls), e) } // end block: if x.Urls slice == nil z.EncWriteMapEnd() } } } func (x *UserEntityURL) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = UserEntityURL{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *UserEntityURL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "urls": h.decSliceURL((*[]URL)(&x.Urls), d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *UserEntityURL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj6 int var yyb6 bool var yyhl6 bool = l >= 0 yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSliceURL((*[]URL)(&x.Urls), d) for { yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj6-1, "") } } func (x *UserEntities) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(2) z.EncWriteArrayElem() yy5 := &x.Description yy5.CodecEncodeSelf(e) z.EncWriteArrayElem() yy7 := &x.URL yy7.CodecEncodeSelf(e) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(2) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"description\"") } else { r.EncodeString(`description`) } z.EncWriteMapElemValue() yy9 := &x.Description yy9.CodecEncodeSelf(e) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"url\"") } else { r.EncodeString(`url`) } z.EncWriteMapElemValue() yy11 := &x.URL yy11.CodecEncodeSelf(e) z.EncWriteMapEnd() } } } func (x *UserEntities) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = UserEntities{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *UserEntities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "description": x.Description.CodecDecodeSelf(d) case "url": x.URL.CodecDecodeSelf(d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *UserEntities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj6 int var yyb6 bool var yyhl6 bool = l >= 0 yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Description.CodecDecodeSelf(d) yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.URL.CodecDecodeSelf(d) for { yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj6-1, "") } } func (x *User) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' var yyn10 bool = x.FollowRequestSent == nil var yyn12 bool = x.Following == nil var yyn22 bool = x.Notifications == nil var yyn39 bool = x.URL == nil if yyr2 || yy2arr2 { z.EncWriteArrayStart(39) z.EncWriteArrayElem() r.EncodeBool(bool(x.ContributorsEnabled)) z.EncWriteArrayElem() r.EncodeString(string(x.CreatedAt)) z.EncWriteArrayElem() r.EncodeBool(bool(x.DefaultProfile)) z.EncWriteArrayElem() r.EncodeBool(bool(x.DefaultProfileImage)) z.EncWriteArrayElem() r.EncodeString(string(x.Description)) z.EncWriteArrayElem() yy47 := &x.Entities yy47.CodecEncodeSelf(e) z.EncWriteArrayElem() r.EncodeInt(int64(x.FavouritesCount)) if yyn10 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy50 := *x.FollowRequestSent r.EncodeString(string(yy50)) } z.EncWriteArrayElem() r.EncodeInt(int64(x.FollowersCount)) if yyn12 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy53 := *x.Following r.EncodeString(string(yy53)) } z.EncWriteArrayElem() r.EncodeInt(int64(x.FriendsCount)) z.EncWriteArrayElem() r.EncodeBool(bool(x.GeoEnabled)) z.EncWriteArrayElem() r.EncodeInt(int64(x.ID)) z.EncWriteArrayElem() r.EncodeString(string(x.IDStr)) z.EncWriteArrayElem() r.EncodeBool(bool(x.IsTranslator)) z.EncWriteArrayElem() r.EncodeString(string(x.Lang)) z.EncWriteArrayElem() r.EncodeInt(int64(x.ListedCount)) z.EncWriteArrayElem() r.EncodeString(string(x.Location)) z.EncWriteArrayElem() r.EncodeString(string(x.Name)) if yyn22 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy64 := *x.Notifications r.EncodeString(string(yy64)) } z.EncWriteArrayElem() r.EncodeString(string(x.ProfileBackgroundColor)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileBackgroundImageURL)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileBackgroundImageURLHTTPS)) z.EncWriteArrayElem() r.EncodeBool(bool(x.ProfileBackgroundTile)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileImageURL)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileImageURLHTTPS)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileLinkColor)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileSidebarBorderColor)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileSidebarFillColor)) z.EncWriteArrayElem() r.EncodeString(string(x.ProfileTextColor)) z.EncWriteArrayElem() r.EncodeBool(bool(x.ProfileUseBackgroundImage)) z.EncWriteArrayElem() r.EncodeBool(bool(x.Protected)) z.EncWriteArrayElem() r.EncodeString(string(x.ScreenName)) z.EncWriteArrayElem() r.EncodeBool(bool(x.ShowAllInlineMedia)) z.EncWriteArrayElem() r.EncodeInt(int64(x.StatusesCount)) z.EncWriteArrayElem() r.EncodeString(string(x.TimeZone)) if yyn39 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy82 := *x.URL r.EncodeString(string(yy82)) } z.EncWriteArrayElem() r.EncodeInt(int64(x.UtcOffset)) z.EncWriteArrayElem() r.EncodeBool(bool(x.Verified)) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(39) z.EncWriteMapElemKey() r.EncodeString(`contributors_enabled`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.ContributorsEnabled)) z.EncWriteMapElemKey() r.EncodeString(`created_at`) z.EncWriteMapElemValue() r.EncodeString(string(x.CreatedAt)) z.EncWriteMapElemKey() r.EncodeString(`default_profile`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.DefaultProfile)) z.EncWriteMapElemKey() r.EncodeString(`default_profile_image`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.DefaultProfileImage)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"description\"") } else { r.EncodeString(`description`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Description)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"entities\"") } else { r.EncodeString(`entities`) } z.EncWriteMapElemValue() yy91 := &x.Entities yy91.CodecEncodeSelf(e) z.EncWriteMapElemKey() r.EncodeString(`favourites_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.FavouritesCount)) z.EncWriteMapElemKey() r.EncodeString(`follow_request_sent`) z.EncWriteMapElemValue() if yyn10 { r.EncodeNil() } else { yy94 := *x.FollowRequestSent r.EncodeString(string(yy94)) } z.EncWriteMapElemKey() r.EncodeString(`followers_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.FollowersCount)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"following\"") } else { r.EncodeString(`following`) } z.EncWriteMapElemValue() if yyn12 { r.EncodeNil() } else { yy97 := *x.Following r.EncodeString(string(yy97)) } z.EncWriteMapElemKey() r.EncodeString(`friends_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.FriendsCount)) z.EncWriteMapElemKey() r.EncodeString(`geo_enabled`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.GeoEnabled)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"id\"") } else { r.EncodeString(`id`) } z.EncWriteMapElemValue() r.EncodeInt(int64(x.ID)) z.EncWriteMapElemKey() r.EncodeString(`id_str`) z.EncWriteMapElemValue() r.EncodeString(string(x.IDStr)) z.EncWriteMapElemKey() r.EncodeString(`is_translator`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.IsTranslator)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"lang\"") } else { r.EncodeString(`lang`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Lang)) z.EncWriteMapElemKey() r.EncodeString(`listed_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.ListedCount)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"location\"") } else { r.EncodeString(`location`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Location)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"name\"") } else { r.EncodeString(`name`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Name)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"notifications\"") } else { r.EncodeString(`notifications`) } z.EncWriteMapElemValue() if yyn22 { r.EncodeNil() } else { yy108 := *x.Notifications r.EncodeString(string(yy108)) } z.EncWriteMapElemKey() r.EncodeString(`profile_background_color`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileBackgroundColor)) z.EncWriteMapElemKey() r.EncodeString(`profile_background_image_url`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileBackgroundImageURL)) z.EncWriteMapElemKey() r.EncodeString(`profile_background_image_url_https`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileBackgroundImageURLHTTPS)) z.EncWriteMapElemKey() r.EncodeString(`profile_background_tile`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.ProfileBackgroundTile)) z.EncWriteMapElemKey() r.EncodeString(`profile_image_url`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileImageURL)) z.EncWriteMapElemKey() r.EncodeString(`profile_image_url_https`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileImageURLHTTPS)) z.EncWriteMapElemKey() r.EncodeString(`profile_link_color`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileLinkColor)) z.EncWriteMapElemKey() r.EncodeString(`profile_sidebar_border_color`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileSidebarBorderColor)) z.EncWriteMapElemKey() r.EncodeString(`profile_sidebar_fill_color`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileSidebarFillColor)) z.EncWriteMapElemKey() r.EncodeString(`profile_text_color`) z.EncWriteMapElemValue() r.EncodeString(string(x.ProfileTextColor)) z.EncWriteMapElemKey() r.EncodeString(`profile_use_background_image`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.ProfileUseBackgroundImage)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"protected\"") } else { r.EncodeString(`protected`) } z.EncWriteMapElemValue() r.EncodeBool(bool(x.Protected)) z.EncWriteMapElemKey() r.EncodeString(`screen_name`) z.EncWriteMapElemValue() r.EncodeString(string(x.ScreenName)) z.EncWriteMapElemKey() r.EncodeString(`show_all_inline_media`) z.EncWriteMapElemValue() r.EncodeBool(bool(x.ShowAllInlineMedia)) z.EncWriteMapElemKey() r.EncodeString(`statuses_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.StatusesCount)) z.EncWriteMapElemKey() r.EncodeString(`time_zone`) z.EncWriteMapElemValue() r.EncodeString(string(x.TimeZone)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"url\"") } else { r.EncodeString(`url`) } z.EncWriteMapElemValue() if yyn39 { r.EncodeNil() } else { yy126 := *x.URL r.EncodeString(string(yy126)) } z.EncWriteMapElemKey() r.EncodeString(`utc_offset`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.UtcOffset)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"verified\"") } else { r.EncodeString(`verified`) } z.EncWriteMapElemValue() r.EncodeBool(bool(x.Verified)) z.EncWriteMapEnd() } } } func (x *User) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = User{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *User) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "contributors_enabled": x.ContributorsEnabled = (bool)(r.DecodeBool()) case "created_at": x.CreatedAt = (string)(string(r.DecodeStringAsBytes())) case "default_profile": x.DefaultProfile = (bool)(r.DecodeBool()) case "default_profile_image": x.DefaultProfileImage = (bool)(r.DecodeBool()) case "description": x.Description = (string)(string(r.DecodeStringAsBytes())) case "entities": x.Entities.CodecDecodeSelf(d) case "favourites_count": x.FavouritesCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "follow_request_sent": if r.TryNil() { if x.FollowRequestSent != nil { // remove the if-true x.FollowRequestSent = nil } } else { if x.FollowRequestSent == nil { x.FollowRequestSent = new(string) } *x.FollowRequestSent = (string)(string(r.DecodeStringAsBytes())) } case "followers_count": x.FollowersCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "following": if r.TryNil() { if x.Following != nil { // remove the if-true x.Following = nil } } else { if x.Following == nil { x.Following = new(string) } *x.Following = (string)(string(r.DecodeStringAsBytes())) } case "friends_count": x.FriendsCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "geo_enabled": x.GeoEnabled = (bool)(r.DecodeBool()) case "id": x.ID = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "id_str": x.IDStr = (string)(string(r.DecodeStringAsBytes())) case "is_translator": x.IsTranslator = (bool)(r.DecodeBool()) case "lang": x.Lang = (string)(string(r.DecodeStringAsBytes())) case "listed_count": x.ListedCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "location": x.Location = (string)(string(r.DecodeStringAsBytes())) case "name": x.Name = (string)(string(r.DecodeStringAsBytes())) case "notifications": if r.TryNil() { if x.Notifications != nil { // remove the if-true x.Notifications = nil } } else { if x.Notifications == nil { x.Notifications = new(string) } *x.Notifications = (string)(string(r.DecodeStringAsBytes())) } case "profile_background_color": x.ProfileBackgroundColor = (string)(string(r.DecodeStringAsBytes())) case "profile_background_image_url": x.ProfileBackgroundImageURL = (string)(string(r.DecodeStringAsBytes())) case "profile_background_image_url_https": x.ProfileBackgroundImageURLHTTPS = (string)(string(r.DecodeStringAsBytes())) case "profile_background_tile": x.ProfileBackgroundTile = (bool)(r.DecodeBool()) case "profile_image_url": x.ProfileImageURL = (string)(string(r.DecodeStringAsBytes())) case "profile_image_url_https": x.ProfileImageURLHTTPS = (string)(string(r.DecodeStringAsBytes())) case "profile_link_color": x.ProfileLinkColor = (string)(string(r.DecodeStringAsBytes())) case "profile_sidebar_border_color": x.ProfileSidebarBorderColor = (string)(string(r.DecodeStringAsBytes())) case "profile_sidebar_fill_color": x.ProfileSidebarFillColor = (string)(string(r.DecodeStringAsBytes())) case "profile_text_color": x.ProfileTextColor = (string)(string(r.DecodeStringAsBytes())) case "profile_use_background_image": x.ProfileUseBackgroundImage = (bool)(r.DecodeBool()) case "protected": x.Protected = (bool)(r.DecodeBool()) case "screen_name": x.ScreenName = (string)(string(r.DecodeStringAsBytes())) case "show_all_inline_media": x.ShowAllInlineMedia = (bool)(r.DecodeBool()) case "statuses_count": x.StatusesCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "time_zone": x.TimeZone = (string)(string(r.DecodeStringAsBytes())) case "url": if r.TryNil() { if x.URL != nil { // remove the if-true x.URL = nil } } else { if x.URL == nil { x.URL = new(string) } *x.URL = (string)(string(r.DecodeStringAsBytes())) } case "utc_offset": x.UtcOffset = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "verified": x.Verified = (bool)(r.DecodeBool()) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *User) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj47 int var yyb47 bool var yyhl47 bool = l >= 0 yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ContributorsEnabled = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.CreatedAt = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.DefaultProfile = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.DefaultProfileImage = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Description = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Entities.CodecDecodeSelf(d) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.FavouritesCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.FollowRequestSent != nil { // remove the if-true x.FollowRequestSent = nil } } else { if x.FollowRequestSent == nil { x.FollowRequestSent = new(string) } *x.FollowRequestSent = (string)(string(r.DecodeStringAsBytes())) } yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.FollowersCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Following != nil { // remove the if-true x.Following = nil } } else { if x.Following == nil { x.Following = new(string) } *x.Following = (string)(string(r.DecodeStringAsBytes())) } yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.FriendsCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.GeoEnabled = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ID = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.IDStr = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.IsTranslator = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Lang = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ListedCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Location = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Name = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Notifications != nil { // remove the if-true x.Notifications = nil } } else { if x.Notifications == nil { x.Notifications = new(string) } *x.Notifications = (string)(string(r.DecodeStringAsBytes())) } yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileBackgroundColor = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileBackgroundImageURL = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileBackgroundImageURLHTTPS = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileBackgroundTile = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileImageURL = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileImageURLHTTPS = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileLinkColor = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileSidebarBorderColor = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileSidebarFillColor = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileTextColor = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ProfileUseBackgroundImage = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Protected = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ScreenName = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ShowAllInlineMedia = (bool)(r.DecodeBool()) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.StatusesCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.TimeZone = (string)(string(r.DecodeStringAsBytes())) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.URL != nil { // remove the if-true x.URL = nil } } else { if x.URL == nil { x.URL = new(string) } *x.URL = (string)(string(r.DecodeStringAsBytes())) } yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.UtcOffset = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Verified = (bool)(r.DecodeBool()) for { yyj47++ if yyhl47 { yyb47 = yyj47 > l } else { yyb47 = z.DecCheckBreak() } if yyb47 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj47-1, "") } } func (x *StatusMetadata) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(2) z.EncWriteArrayElem() r.EncodeString(string(x.IsoLanguageCode)) z.EncWriteArrayElem() r.EncodeString(string(x.ResultType)) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(2) z.EncWriteMapElemKey() r.EncodeString(`iso_language_code`) z.EncWriteMapElemValue() r.EncodeString(string(x.IsoLanguageCode)) z.EncWriteMapElemKey() r.EncodeString(`result_type`) z.EncWriteMapElemValue() r.EncodeString(string(x.ResultType)) z.EncWriteMapEnd() } } } func (x *StatusMetadata) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = StatusMetadata{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *StatusMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "iso_language_code": x.IsoLanguageCode = (string)(string(r.DecodeStringAsBytes())) case "result_type": x.ResultType = (string)(string(r.DecodeStringAsBytes())) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *StatusMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj6 int var yyb6 bool var yyhl6 bool = l >= 0 yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.IsoLanguageCode = (string)(string(r.DecodeStringAsBytes())) yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ResultType = (string)(string(r.DecodeStringAsBytes())) for { yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj6-1, "") } } func (x *Status) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' var yyn3 bool = x.Contributors == nil var yyn4 bool = x.Coordinates == nil var yyn8 bool = x.Geo == nil var yyn11 bool = x.InReplyToScreenName == nil var yyn12 bool = x.InReplyToStatusID == nil var yyn13 bool = x.InReplyToStatusIDStr == nil var yyn14 bool = x.InReplyToUserID == nil var yyn15 bool = x.InReplyToUserIDStr == nil var yyn17 bool = x.Place == nil if yyr2 || yy2arr2 { z.EncWriteArrayStart(21) if yyn3 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy24 := *x.Contributors r.EncodeString(string(yy24)) } if yyn4 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy26 := *x.Coordinates r.EncodeString(string(yy26)) } z.EncWriteArrayElem() r.EncodeString(string(x.CreatedAt)) z.EncWriteArrayElem() yy29 := &x.Entities yy29.CodecEncodeSelf(e) z.EncWriteArrayElem() r.EncodeBool(bool(x.Favorited)) if yyn8 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy32 := *x.Geo r.EncodeString(string(yy32)) } z.EncWriteArrayElem() r.EncodeInt(int64(x.ID)) z.EncWriteArrayElem() r.EncodeString(string(x.IDStr)) if yyn11 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy36 := *x.InReplyToScreenName r.EncodeString(string(yy36)) } if yyn12 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy38 := *x.InReplyToStatusID r.EncodeString(string(yy38)) } if yyn13 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy40 := *x.InReplyToStatusIDStr r.EncodeString(string(yy40)) } if yyn14 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy42 := *x.InReplyToUserID r.EncodeString(string(yy42)) } if yyn15 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy44 := *x.InReplyToUserIDStr r.EncodeString(string(yy44)) } z.EncWriteArrayElem() yy46 := &x.Metadata yy46.CodecEncodeSelf(e) if yyn17 { z.EncWriteArrayElem() r.EncodeNil() } else { z.EncWriteArrayElem() yy48 := *x.Place r.EncodeString(string(yy48)) } z.EncWriteArrayElem() r.EncodeInt(int64(x.RetweetCount)) z.EncWriteArrayElem() r.EncodeBool(bool(x.Retweeted)) z.EncWriteArrayElem() r.EncodeString(string(x.Source)) z.EncWriteArrayElem() r.EncodeString(string(x.Text)) z.EncWriteArrayElem() r.EncodeBool(bool(x.Truncated)) z.EncWriteArrayElem() yy55 := &x.User yy55.CodecEncodeSelf(e) z.EncWriteArrayEnd() } else { z.EncWriteMapStart(21) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"contributors\"") } else { r.EncodeString(`contributors`) } z.EncWriteMapElemValue() if yyn3 { r.EncodeNil() } else { yy57 := *x.Contributors r.EncodeString(string(yy57)) } z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"coordinates\"") } else { r.EncodeString(`coordinates`) } z.EncWriteMapElemValue() if yyn4 { r.EncodeNil() } else { yy59 := *x.Coordinates r.EncodeString(string(yy59)) } z.EncWriteMapElemKey() r.EncodeString(`created_at`) z.EncWriteMapElemValue() r.EncodeString(string(x.CreatedAt)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"entities\"") } else { r.EncodeString(`entities`) } z.EncWriteMapElemValue() yy62 := &x.Entities yy62.CodecEncodeSelf(e) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"favorited\"") } else { r.EncodeString(`favorited`) } z.EncWriteMapElemValue() r.EncodeBool(bool(x.Favorited)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"geo\"") } else { r.EncodeString(`geo`) } z.EncWriteMapElemValue() if yyn8 { r.EncodeNil() } else { yy65 := *x.Geo r.EncodeString(string(yy65)) } z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"id\"") } else { r.EncodeString(`id`) } z.EncWriteMapElemValue() r.EncodeInt(int64(x.ID)) z.EncWriteMapElemKey() r.EncodeString(`id_str`) z.EncWriteMapElemValue() r.EncodeString(string(x.IDStr)) z.EncWriteMapElemKey() r.EncodeString(`in_reply_to_screen_name`) z.EncWriteMapElemValue() if yyn11 { r.EncodeNil() } else { yy69 := *x.InReplyToScreenName r.EncodeString(string(yy69)) } z.EncWriteMapElemKey() r.EncodeString(`in_reply_to_status_id`) z.EncWriteMapElemValue() if yyn12 { r.EncodeNil() } else { yy71 := *x.InReplyToStatusID r.EncodeString(string(yy71)) } z.EncWriteMapElemKey() r.EncodeString(`in_reply_to_status_id_str`) z.EncWriteMapElemValue() if yyn13 { r.EncodeNil() } else { yy73 := *x.InReplyToStatusIDStr r.EncodeString(string(yy73)) } z.EncWriteMapElemKey() r.EncodeString(`in_reply_to_user_id`) z.EncWriteMapElemValue() if yyn14 { r.EncodeNil() } else { yy75 := *x.InReplyToUserID r.EncodeString(string(yy75)) } z.EncWriteMapElemKey() r.EncodeString(`in_reply_to_user_id_str`) z.EncWriteMapElemValue() if yyn15 { r.EncodeNil() } else { yy77 := *x.InReplyToUserIDStr r.EncodeString(string(yy77)) } z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"metadata\"") } else { r.EncodeString(`metadata`) } z.EncWriteMapElemValue() yy79 := &x.Metadata yy79.CodecEncodeSelf(e) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"place\"") } else { r.EncodeString(`place`) } z.EncWriteMapElemValue() if yyn17 { r.EncodeNil() } else { yy81 := *x.Place r.EncodeString(string(yy81)) } z.EncWriteMapElemKey() r.EncodeString(`retweet_count`) z.EncWriteMapElemValue() r.EncodeInt(int64(x.RetweetCount)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"retweeted\"") } else { r.EncodeString(`retweeted`) } z.EncWriteMapElemValue() r.EncodeBool(bool(x.Retweeted)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"source\"") } else { r.EncodeString(`source`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Source)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"text\"") } else { r.EncodeString(`text`) } z.EncWriteMapElemValue() r.EncodeString(string(x.Text)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"truncated\"") } else { r.EncodeString(`truncated`) } z.EncWriteMapElemValue() r.EncodeBool(bool(x.Truncated)) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"user\"") } else { r.EncodeString(`user`) } z.EncWriteMapElemValue() yy88 := &x.User yy88.CodecEncodeSelf(e) z.EncWriteMapEnd() } } } func (x *Status) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = Status{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *Status) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "contributors": if r.TryNil() { if x.Contributors != nil { // remove the if-true x.Contributors = nil } } else { if x.Contributors == nil { x.Contributors = new(string) } *x.Contributors = (string)(string(r.DecodeStringAsBytes())) } case "coordinates": if r.TryNil() { if x.Coordinates != nil { // remove the if-true x.Coordinates = nil } } else { if x.Coordinates == nil { x.Coordinates = new(string) } *x.Coordinates = (string)(string(r.DecodeStringAsBytes())) } case "created_at": x.CreatedAt = (string)(string(r.DecodeStringAsBytes())) case "entities": x.Entities.CodecDecodeSelf(d) case "favorited": x.Favorited = (bool)(r.DecodeBool()) case "geo": if r.TryNil() { if x.Geo != nil { // remove the if-true x.Geo = nil } } else { if x.Geo == nil { x.Geo = new(string) } *x.Geo = (string)(string(r.DecodeStringAsBytes())) } case "id": x.ID = (int64)(r.DecodeInt64()) case "id_str": x.IDStr = (string)(string(r.DecodeStringAsBytes())) case "in_reply_to_screen_name": if r.TryNil() { if x.InReplyToScreenName != nil { // remove the if-true x.InReplyToScreenName = nil } } else { if x.InReplyToScreenName == nil { x.InReplyToScreenName = new(string) } *x.InReplyToScreenName = (string)(string(r.DecodeStringAsBytes())) } case "in_reply_to_status_id": if r.TryNil() { if x.InReplyToStatusID != nil { // remove the if-true x.InReplyToStatusID = nil } } else { if x.InReplyToStatusID == nil { x.InReplyToStatusID = new(string) } *x.InReplyToStatusID = (string)(string(r.DecodeStringAsBytes())) } case "in_reply_to_status_id_str": if r.TryNil() { if x.InReplyToStatusIDStr != nil { // remove the if-true x.InReplyToStatusIDStr = nil } } else { if x.InReplyToStatusIDStr == nil { x.InReplyToStatusIDStr = new(string) } *x.InReplyToStatusIDStr = (string)(string(r.DecodeStringAsBytes())) } case "in_reply_to_user_id": if r.TryNil() { if x.InReplyToUserID != nil { // remove the if-true x.InReplyToUserID = nil } } else { if x.InReplyToUserID == nil { x.InReplyToUserID = new(string) } *x.InReplyToUserID = (string)(string(r.DecodeStringAsBytes())) } case "in_reply_to_user_id_str": if r.TryNil() { if x.InReplyToUserIDStr != nil { // remove the if-true x.InReplyToUserIDStr = nil } } else { if x.InReplyToUserIDStr == nil { x.InReplyToUserIDStr = new(string) } *x.InReplyToUserIDStr = (string)(string(r.DecodeStringAsBytes())) } case "metadata": x.Metadata.CodecDecodeSelf(d) case "place": if r.TryNil() { if x.Place != nil { // remove the if-true x.Place = nil } } else { if x.Place == nil { x.Place = new(string) } *x.Place = (string)(string(r.DecodeStringAsBytes())) } case "retweet_count": x.RetweetCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) case "retweeted": x.Retweeted = (bool)(r.DecodeBool()) case "source": x.Source = (string)(string(r.DecodeStringAsBytes())) case "text": x.Text = (string)(string(r.DecodeStringAsBytes())) case "truncated": x.Truncated = (bool)(r.DecodeBool()) case "user": x.User.CodecDecodeSelf(d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *Status) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj34 int var yyb34 bool var yyhl34 bool = l >= 0 yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Contributors != nil { // remove the if-true x.Contributors = nil } } else { if x.Contributors == nil { x.Contributors = new(string) } *x.Contributors = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Coordinates != nil { // remove the if-true x.Coordinates = nil } } else { if x.Coordinates == nil { x.Coordinates = new(string) } *x.Coordinates = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.CreatedAt = (string)(string(r.DecodeStringAsBytes())) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Entities.CodecDecodeSelf(d) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Favorited = (bool)(r.DecodeBool()) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Geo != nil { // remove the if-true x.Geo = nil } } else { if x.Geo == nil { x.Geo = new(string) } *x.Geo = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.ID = (int64)(r.DecodeInt64()) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.IDStr = (string)(string(r.DecodeStringAsBytes())) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.InReplyToScreenName != nil { // remove the if-true x.InReplyToScreenName = nil } } else { if x.InReplyToScreenName == nil { x.InReplyToScreenName = new(string) } *x.InReplyToScreenName = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.InReplyToStatusID != nil { // remove the if-true x.InReplyToStatusID = nil } } else { if x.InReplyToStatusID == nil { x.InReplyToStatusID = new(string) } *x.InReplyToStatusID = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.InReplyToStatusIDStr != nil { // remove the if-true x.InReplyToStatusIDStr = nil } } else { if x.InReplyToStatusIDStr == nil { x.InReplyToStatusIDStr = new(string) } *x.InReplyToStatusIDStr = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.InReplyToUserID != nil { // remove the if-true x.InReplyToUserID = nil } } else { if x.InReplyToUserID == nil { x.InReplyToUserID = new(string) } *x.InReplyToUserID = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.InReplyToUserIDStr != nil { // remove the if-true x.InReplyToUserIDStr = nil } } else { if x.InReplyToUserIDStr == nil { x.InReplyToUserIDStr = new(string) } *x.InReplyToUserIDStr = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Metadata.CodecDecodeSelf(d) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() if r.TryNil() { if x.Place != nil { // remove the if-true x.Place = nil } } else { if x.Place == nil { x.Place = new(string) } *x.Place = (string)(string(r.DecodeStringAsBytes())) } yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.RetweetCount = (int)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize2736)) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Retweeted = (bool)(r.DecodeBool()) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Source = (string)(string(r.DecodeStringAsBytes())) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Text = (string)(string(r.DecodeStringAsBytes())) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.Truncated = (bool)(r.DecodeBool()) yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.User.CodecDecodeSelf(d) for { yyj34++ if yyhl34 { yyb34 = yyj34 > l } else { yyb34 = z.DecCheckBreak() } if yyb34 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj34-1, "") } } func (x *LargeStruct) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(2) z.EncWriteArrayElem() yy5 := &x.SearchMetadata yy5.CodecEncodeSelf(e) z.EncWriteArrayElem() if x.Statuses == nil { r.EncodeNil() } else { h.encSliceStatus(([]Status)(x.Statuses), e) } // end block: if x.Statuses slice == nil z.EncWriteArrayEnd() } else { z.EncWriteMapStart(2) z.EncWriteMapElemKey() r.EncodeString(`search_metadata`) z.EncWriteMapElemValue() yy8 := &x.SearchMetadata yy8.CodecEncodeSelf(e) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"statuses\"") } else { r.EncodeString(`statuses`) } z.EncWriteMapElemValue() if x.Statuses == nil { r.EncodeNil() } else { h.encSliceStatus(([]Status)(x.Statuses), e) } // end block: if x.Statuses slice == nil z.EncWriteMapEnd() } } } func (x *LargeStruct) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = LargeStruct{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *LargeStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "search_metadata": x.SearchMetadata.CodecDecodeSelf(d) case "statuses": h.decSliceStatus((*[]Status)(&x.Statuses), d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *LargeStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj7 int var yyb7 bool var yyhl7 bool = l >= 0 yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { z.DecReadArrayEnd() return } z.DecReadArrayElem() x.SearchMetadata.CodecDecodeSelf(d) yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSliceStatus((*[]Status)(&x.Statuses), d) for { yyj7++ if yyhl7 { yyb7 = yyj7 > l } else { yyb7 = z.DecCheckBreak() } if yyb7 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj7-1, "") } } func (x *XLStruct) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray _, _ = yysep2, yy2arr2 const yyr2 bool = false // struct tag has 'toArray' if yyr2 || yy2arr2 { z.EncWriteArrayStart(1) z.EncWriteArrayElem() if x.Data == nil { r.EncodeNil() } else { h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) } // end block: if x.Data slice == nil z.EncWriteArrayEnd() } else { z.EncWriteMapStart(1) z.EncWriteMapElemKey() if z.IsJSONHandle() { z.WriteStr("\"Data\"") } else { r.EncodeString(`Data`) } z.EncWriteMapElemValue() if x.Data == nil { r.EncodeNil() } else { h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) } // end block: if x.Data slice == nil z.EncWriteMapEnd() } } } func (x *XLStruct) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeNil2736 { *(x) = XLStruct{} } else if yyct2 == codecSelferValueTypeMap2736 { yyl2 := z.DecReadMapStart() if yyl2 == 0 { } else { x.codecDecodeSelfFromMap(yyl2, d) } z.DecReadMapEnd() } else if yyct2 == codecSelferValueTypeArray2736 { yyl2 := z.DecReadArrayStart() if yyl2 != 0 { x.codecDecodeSelfFromArray(yyl2, d) } z.DecReadArrayEnd() } else { panic(errCodecSelferOnlyMapOrArrayEncodeToStruct2736) } } func (x *XLStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if z.DecCheckBreak() { break } } z.DecReadMapElemKey() yys3 := z.StringView(r.DecodeStringAsBytes()) z.DecReadMapElemValue() switch yys3 { case "Data": h.decSliceLargeStruct((*[]LargeStruct)(&x.Data), d) default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 } func (x *XLStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj6 int var yyb6 bool var yyhl6 bool = l >= 0 yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { z.DecReadArrayEnd() return } z.DecReadArrayElem() h.decSliceLargeStruct((*[]LargeStruct)(&x.Data), d) for { yyj6++ if yyhl6 { yyb6 = yyj6 > l } else { yyb6 = z.DecCheckBreak() } if yyb6 { break } z.DecReadArrayElem() z.DecStructFieldNotFound(yyj6-1, "") } } func (x codecSelfer2736) encSliceHashtag(v []Hashtag, e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if v == nil { r.EncodeNil() return } z.EncWriteArrayStart(len(v)) for _, yyv1 := range v { z.EncWriteArrayElem() yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncWriteArrayEnd() } func (x codecSelfer2736) decSliceHashtag(v *[]Hashtag, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyh1.IsNil { if yyv1 != nil { yyv1 = nil yyc1 = true } } else if yyl1 == 0 { if yyv1 == nil { yyv1 = []Hashtag{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else { yyhl1 := yyl1 > 0 var yyrl1 int _ = yyrl1 if yyhl1 { if yyl1 > cap(yyv1) { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]Hashtag, yyrl1) } yyc1 = true } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } } var yyj1 int for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination if yyj1 == 0 && yyv1 == nil { if yyhl1 { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) } else { yyrl1 = 8 } yyv1 = make([]Hashtag, yyrl1) yyc1 = true } yyh1.ElemContainerState(yyj1) var yydb1 bool if yyj1 >= len(yyv1) { yyv1 = append(yyv1, Hashtag{}) yyc1 = true } if yydb1 { z.DecSwallow() } else { yyv1[yyj1].CodecDecodeSelf(d) } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = make([]Hashtag, 0) yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer2736) encSlicePtrtostring(v []*string, e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if v == nil { r.EncodeNil() return } z.EncWriteArrayStart(len(v)) for _, yyv1 := range v { z.EncWriteArrayElem() if yyv1 == nil { r.EncodeNil() } else { yy2 := *yyv1 r.EncodeString(string(yy2)) } } z.EncWriteArrayEnd() } func (x codecSelfer2736) decSlicePtrtostring(v *[]*string, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyh1.IsNil { if yyv1 != nil { yyv1 = nil yyc1 = true } } else if yyl1 == 0 { if yyv1 == nil { yyv1 = []*string{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else { yyhl1 := yyl1 > 0 var yyrl1 int _ = yyrl1 if yyhl1 { if yyl1 > cap(yyv1) { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]*string, yyrl1) } yyc1 = true } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } } var yyj1 int for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination if yyj1 == 0 && yyv1 == nil { if yyhl1 { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) } else { yyrl1 = 8 } yyv1 = make([]*string, yyrl1) yyc1 = true } yyh1.ElemContainerState(yyj1) var yydb1 bool if yyj1 >= len(yyv1) { yyv1 = append(yyv1, nil) yyc1 = true } if yydb1 { z.DecSwallow() } else { if r.TryNil() { yyv1[yyj1] = nil } else { if yyv1[yyj1] == nil { yyv1[yyj1] = new(string) } *yyv1[yyj1] = (string)(string(r.DecodeStringAsBytes())) } } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = make([]*string, 0) yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer2736) encSliceURL(v []URL, e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if v == nil { r.EncodeNil() return } z.EncWriteArrayStart(len(v)) for _, yyv1 := range v { z.EncWriteArrayElem() yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncWriteArrayEnd() } func (x codecSelfer2736) decSliceURL(v *[]URL, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyh1.IsNil { if yyv1 != nil { yyv1 = nil yyc1 = true } } else if yyl1 == 0 { if yyv1 == nil { yyv1 = []URL{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else { yyhl1 := yyl1 > 0 var yyrl1 int _ = yyrl1 if yyhl1 { if yyl1 > cap(yyv1) { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 48) if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]URL, yyrl1) } yyc1 = true } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } } var yyj1 int for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination if yyj1 == 0 && yyv1 == nil { if yyhl1 { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 48) } else { yyrl1 = 8 } yyv1 = make([]URL, yyrl1) yyc1 = true } yyh1.ElemContainerState(yyj1) var yydb1 bool if yyj1 >= len(yyv1) { yyv1 = append(yyv1, URL{}) yyc1 = true } if yydb1 { z.DecSwallow() } else { yyv1[yyj1].CodecDecodeSelf(d) } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = make([]URL, 0) yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer2736) encSliceStatus(v []Status, e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if v == nil { r.EncodeNil() return } z.EncWriteArrayStart(len(v)) for _, yyv1 := range v { z.EncWriteArrayElem() yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncWriteArrayEnd() } func (x codecSelfer2736) decSliceStatus(v *[]Status, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyh1.IsNil { if yyv1 != nil { yyv1 = nil yyc1 = true } } else if yyl1 == 0 { if yyv1 == nil { yyv1 = []Status{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else { yyhl1 := yyl1 > 0 var yyrl1 int _ = yyrl1 if yyhl1 { if yyl1 > cap(yyv1) { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 752) if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]Status, yyrl1) } yyc1 = true } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } } var yyj1 int for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination if yyj1 == 0 && yyv1 == nil { if yyhl1 { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 752) } else { yyrl1 = 8 } yyv1 = make([]Status, yyrl1) yyc1 = true } yyh1.ElemContainerState(yyj1) var yydb1 bool if yyj1 >= len(yyv1) { yyv1 = append(yyv1, Status{}) yyc1 = true } if yydb1 { z.DecSwallow() } else { yyv1[yyj1].CodecDecodeSelf(d) } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = make([]Status, 0) yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer2736) encSliceLargeStruct(v []LargeStruct, e *codec1978.Encoder) { var h codecSelfer2736 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if v == nil { r.EncodeNil() return } z.EncWriteArrayStart(len(v)) for _, yyv1 := range v { z.EncWriteArrayElem() yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncWriteArrayEnd() } func (x codecSelfer2736) decSliceLargeStruct(v *[]LargeStruct, d *codec1978.Decoder) { var h codecSelfer2736 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyh1.IsNil { if yyv1 != nil { yyv1 = nil yyc1 = true } } else if yyl1 == 0 { if yyv1 == nil { yyv1 = []LargeStruct{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else { yyhl1 := yyl1 > 0 var yyrl1 int _ = yyrl1 if yyhl1 { if yyl1 > cap(yyv1) { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 136) if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]LargeStruct, yyrl1) } yyc1 = true } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } } var yyj1 int for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination if yyj1 == 0 && yyv1 == nil { if yyhl1 { yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 136) } else { yyrl1 = 8 } yyv1 = make([]LargeStruct, yyrl1) yyc1 = true } yyh1.ElemContainerState(yyj1) var yydb1 bool if yyj1 >= len(yyv1) { yyv1 = append(yyv1, LargeStruct{}) yyc1 = true } if yydb1 { z.DecSwallow() } else { yyv1[yyj1].CodecDecodeSelf(d) } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = make([]LargeStruct, 0) yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } easyjson-0.7.6/benchmark/data_ffjson.go000066400000000000000000004317751371475264500201550ustar00rootroot00000000000000// +build use_ffjson // DO NOT EDIT! // Code generated by ffjson // source: .root/src/github.com/mailru/easyjson/benchmark/data.go // DO NOT EDIT! package benchmark import ( "bytes" "errors" "fmt" fflib "github.com/pquerna/ffjson/fflib/v1" ) // MarshalJSON marshal bytes to json - template func (j *Entities) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *Entities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"hashtags":`) if j.Hashtags != nil { buf.WriteString(`[`) for i, v := range j.Hashtags { if i != 0 { buf.WriteString(`,`) } { err = v.MarshalJSONBuf(buf) if err != nil { return err } } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteString(`,"urls":`) if j.Urls != nil { buf.WriteString(`[`) for i, v := range j.Urls { if i != 0 { buf.WriteString(`,`) } if v != nil { fflib.WriteJsonString(buf, string(*v)) } else { buf.WriteString(`null`) } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteString(`,"user_mentions":`) if j.UserMentions != nil { buf.WriteString(`[`) for i, v := range j.UserMentions { if i != 0 { buf.WriteString(`,`) } if v != nil { fflib.WriteJsonString(buf, string(*v)) } else { buf.WriteString(`null`) } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteByte('}') return nil } const ( ffjtEntitiesbase = iota ffjtEntitiesnosuchkey ffjtEntitiesHashtags ffjtEntitiesUrls ffjtEntitiesUserMentions ) var ffjKeyEntitiesHashtags = []byte("hashtags") var ffjKeyEntitiesUrls = []byte("urls") var ffjKeyEntitiesUserMentions = []byte("user_mentions") // UnmarshalJSON umarshall json - template of ffjson func (j *Entities) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *Entities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtEntitiesbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtEntitiesnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'h': if bytes.Equal(ffjKeyEntitiesHashtags, kn) { currentKey = ffjtEntitiesHashtags state = fflib.FFParse_want_colon goto mainparse } case 'u': if bytes.Equal(ffjKeyEntitiesUrls, kn) { currentKey = ffjtEntitiesUrls state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyEntitiesUserMentions, kn) { currentKey = ffjtEntitiesUserMentions state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyEntitiesUserMentions, kn) { currentKey = ffjtEntitiesUserMentions state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyEntitiesUrls, kn) { currentKey = ffjtEntitiesUrls state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyEntitiesHashtags, kn) { currentKey = ffjtEntitiesHashtags state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtEntitiesnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtEntitiesHashtags: goto handle_Hashtags case ffjtEntitiesUrls: goto handle_Urls case ffjtEntitiesUserMentions: goto handle_UserMentions case ffjtEntitiesnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Hashtags: /* handler: j.Hashtags type=[]benchmark.Hashtag kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Hashtags = nil } else { j.Hashtags = []Hashtag{} wantVal := true for { var tmpJHashtags Hashtag tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJHashtags type=benchmark.Hashtag kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = tmpJHashtags.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } j.Hashtags = append(j.Hashtags, tmpJHashtags) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse handle_Urls: /* handler: j.Urls type=[]*string kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Urls = nil } else { j.Urls = []*string{} wantVal := true for { var tmpJUrls *string tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJUrls type=*string kind=ptr quoted=false*/ { if tok == fflib.FFTok_null { tmpJUrls = nil } else { if tmpJUrls == nil { tmpJUrls = new(string) } /* handler: tmpJUrls type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { tmpJUrls = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) tmpJUrls = &tval } } } } j.Urls = append(j.Urls, tmpJUrls) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse handle_UserMentions: /* handler: j.UserMentions type=[]*string kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.UserMentions = nil } else { j.UserMentions = []*string{} wantVal := true for { var tmpJUserMentions *string tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJUserMentions type=*string kind=ptr quoted=false*/ { if tok == fflib.FFTok_null { tmpJUserMentions = nil } else { if tmpJUserMentions == nil { tmpJUserMentions = new(string) } /* handler: tmpJUserMentions type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { tmpJUserMentions = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) tmpJUserMentions = &tval } } } } j.UserMentions = append(j.UserMentions, tmpJUserMentions) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *Hashtag) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *Hashtag) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"indices":`) if j.Indices != nil { buf.WriteString(`[`) for i, v := range j.Indices { if i != 0 { buf.WriteString(`,`) } fflib.FormatBits2(buf, uint64(v), 10, v < 0) } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteString(`,"text":`) fflib.WriteJsonString(buf, string(j.Text)) buf.WriteByte('}') return nil } const ( ffjtHashtagbase = iota ffjtHashtagnosuchkey ffjtHashtagIndices ffjtHashtagText ) var ffjKeyHashtagIndices = []byte("indices") var ffjKeyHashtagText = []byte("text") // UnmarshalJSON umarshall json - template of ffjson func (j *Hashtag) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *Hashtag) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtHashtagbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtHashtagnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'i': if bytes.Equal(ffjKeyHashtagIndices, kn) { currentKey = ffjtHashtagIndices state = fflib.FFParse_want_colon goto mainparse } case 't': if bytes.Equal(ffjKeyHashtagText, kn) { currentKey = ffjtHashtagText state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyHashtagText, kn) { currentKey = ffjtHashtagText state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyHashtagIndices, kn) { currentKey = ffjtHashtagIndices state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtHashtagnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtHashtagIndices: goto handle_Indices case ffjtHashtagText: goto handle_Text case ffjtHashtagnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Indices: /* handler: j.Indices type=[]int kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Indices = nil } else { j.Indices = []int{} wantVal := true for { var tmpJIndices int tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJIndices type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } tmpJIndices = int(tval) } } j.Indices = append(j.Indices, tmpJIndices) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse handle_Text: /* handler: j.Text type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Text = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *LargeStruct) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *LargeStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"search_metadata":`) { err = j.SearchMetadata.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteString(`,"statuses":`) if j.Statuses != nil { buf.WriteString(`[`) for i, v := range j.Statuses { if i != 0 { buf.WriteString(`,`) } { err = v.MarshalJSONBuf(buf) if err != nil { return err } } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteByte('}') return nil } const ( ffjtLargeStructbase = iota ffjtLargeStructnosuchkey ffjtLargeStructSearchMetadata ffjtLargeStructStatuses ) var ffjKeyLargeStructSearchMetadata = []byte("search_metadata") var ffjKeyLargeStructStatuses = []byte("statuses") // UnmarshalJSON umarshall json - template of ffjson func (j *LargeStruct) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *LargeStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtLargeStructbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtLargeStructnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 's': if bytes.Equal(ffjKeyLargeStructSearchMetadata, kn) { currentKey = ffjtLargeStructSearchMetadata state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyLargeStructStatuses, kn) { currentKey = ffjtLargeStructStatuses state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyLargeStructStatuses, kn) { currentKey = ffjtLargeStructStatuses state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyLargeStructSearchMetadata, kn) { currentKey = ffjtLargeStructSearchMetadata state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtLargeStructnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtLargeStructSearchMetadata: goto handle_SearchMetadata case ffjtLargeStructStatuses: goto handle_Statuses case ffjtLargeStructnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_SearchMetadata: /* handler: j.SearchMetadata type=benchmark.SearchMetadata kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.SearchMetadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Statuses: /* handler: j.Statuses type=[]benchmark.Status kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Statuses = nil } else { j.Statuses = []Status{} wantVal := true for { var tmpJStatuses Status tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJStatuses type=benchmark.Status kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = tmpJStatuses.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } j.Statuses = append(j.Statuses, tmpJStatuses) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *SearchMetadata) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *SearchMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"completed_in":`) fflib.AppendFloat(buf, float64(j.CompletedIn), 'g', -1, 64) buf.WriteString(`,"count":`) fflib.FormatBits2(buf, uint64(j.Count), 10, j.Count < 0) buf.WriteString(`,"max_id":`) fflib.FormatBits2(buf, uint64(j.MaxID), 10, j.MaxID < 0) buf.WriteString(`,"max_id_str":`) fflib.WriteJsonString(buf, string(j.MaxIDStr)) buf.WriteString(`,"next_results":`) fflib.WriteJsonString(buf, string(j.NextResults)) buf.WriteString(`,"query":`) fflib.WriteJsonString(buf, string(j.Query)) buf.WriteString(`,"refresh_url":`) fflib.WriteJsonString(buf, string(j.RefreshURL)) buf.WriteString(`,"since_id":`) fflib.FormatBits2(buf, uint64(j.SinceID), 10, j.SinceID < 0) buf.WriteString(`,"since_id_str":`) fflib.WriteJsonString(buf, string(j.SinceIDStr)) buf.WriteByte('}') return nil } const ( ffjtSearchMetadatabase = iota ffjtSearchMetadatanosuchkey ffjtSearchMetadataCompletedIn ffjtSearchMetadataCount ffjtSearchMetadataMaxID ffjtSearchMetadataMaxIDStr ffjtSearchMetadataNextResults ffjtSearchMetadataQuery ffjtSearchMetadataRefreshURL ffjtSearchMetadataSinceID ffjtSearchMetadataSinceIDStr ) var ffjKeySearchMetadataCompletedIn = []byte("completed_in") var ffjKeySearchMetadataCount = []byte("count") var ffjKeySearchMetadataMaxID = []byte("max_id") var ffjKeySearchMetadataMaxIDStr = []byte("max_id_str") var ffjKeySearchMetadataNextResults = []byte("next_results") var ffjKeySearchMetadataQuery = []byte("query") var ffjKeySearchMetadataRefreshURL = []byte("refresh_url") var ffjKeySearchMetadataSinceID = []byte("since_id") var ffjKeySearchMetadataSinceIDStr = []byte("since_id_str") // UnmarshalJSON umarshall json - template of ffjson func (j *SearchMetadata) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *SearchMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtSearchMetadatabase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtSearchMetadatanosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'c': if bytes.Equal(ffjKeySearchMetadataCompletedIn, kn) { currentKey = ffjtSearchMetadataCompletedIn state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeySearchMetadataCount, kn) { currentKey = ffjtSearchMetadataCount state = fflib.FFParse_want_colon goto mainparse } case 'm': if bytes.Equal(ffjKeySearchMetadataMaxID, kn) { currentKey = ffjtSearchMetadataMaxID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeySearchMetadataMaxIDStr, kn) { currentKey = ffjtSearchMetadataMaxIDStr state = fflib.FFParse_want_colon goto mainparse } case 'n': if bytes.Equal(ffjKeySearchMetadataNextResults, kn) { currentKey = ffjtSearchMetadataNextResults state = fflib.FFParse_want_colon goto mainparse } case 'q': if bytes.Equal(ffjKeySearchMetadataQuery, kn) { currentKey = ffjtSearchMetadataQuery state = fflib.FFParse_want_colon goto mainparse } case 'r': if bytes.Equal(ffjKeySearchMetadataRefreshURL, kn) { currentKey = ffjtSearchMetadataRefreshURL state = fflib.FFParse_want_colon goto mainparse } case 's': if bytes.Equal(ffjKeySearchMetadataSinceID, kn) { currentKey = ffjtSearchMetadataSinceID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeySearchMetadataSinceIDStr, kn) { currentKey = ffjtSearchMetadataSinceIDStr state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeySearchMetadataSinceIDStr, kn) { currentKey = ffjtSearchMetadataSinceIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeySearchMetadataSinceID, kn) { currentKey = ffjtSearchMetadataSinceID state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeySearchMetadataRefreshURL, kn) { currentKey = ffjtSearchMetadataRefreshURL state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeySearchMetadataQuery, kn) { currentKey = ffjtSearchMetadataQuery state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeySearchMetadataNextResults, kn) { currentKey = ffjtSearchMetadataNextResults state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeySearchMetadataMaxIDStr, kn) { currentKey = ffjtSearchMetadataMaxIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeySearchMetadataMaxID, kn) { currentKey = ffjtSearchMetadataMaxID state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeySearchMetadataCount, kn) { currentKey = ffjtSearchMetadataCount state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeySearchMetadataCompletedIn, kn) { currentKey = ffjtSearchMetadataCompletedIn state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtSearchMetadatanosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtSearchMetadataCompletedIn: goto handle_CompletedIn case ffjtSearchMetadataCount: goto handle_Count case ffjtSearchMetadataMaxID: goto handle_MaxID case ffjtSearchMetadataMaxIDStr: goto handle_MaxIDStr case ffjtSearchMetadataNextResults: goto handle_NextResults case ffjtSearchMetadataQuery: goto handle_Query case ffjtSearchMetadataRefreshURL: goto handle_RefreshURL case ffjtSearchMetadataSinceID: goto handle_SinceID case ffjtSearchMetadataSinceIDStr: goto handle_SinceIDStr case ffjtSearchMetadatanosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_CompletedIn: /* handler: j.CompletedIn type=float64 kind=float64 quoted=false*/ { if tok != fflib.FFTok_double && tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for float64", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseFloat(fs.Output.Bytes(), 64) if err != nil { return fs.WrapErr(err) } j.CompletedIn = float64(tval) } } state = fflib.FFParse_after_value goto mainparse handle_Count: /* handler: j.Count type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.Count = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_MaxID: /* handler: j.MaxID type=int64 kind=int64 quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int64", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.MaxID = int64(tval) } } state = fflib.FFParse_after_value goto mainparse handle_MaxIDStr: /* handler: j.MaxIDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.MaxIDStr = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_NextResults: /* handler: j.NextResults type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.NextResults = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Query: /* handler: j.Query type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Query = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_RefreshURL: /* handler: j.RefreshURL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.RefreshURL = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_SinceID: /* handler: j.SinceID type=int64 kind=int64 quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int64", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.SinceID = int64(tval) } } state = fflib.FFParse_after_value goto mainparse handle_SinceIDStr: /* handler: j.SinceIDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.SinceIDStr = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *Status) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *Status) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err if j.Contributors != nil { buf.WriteString(`{"contributors":`) fflib.WriteJsonString(buf, string(*j.Contributors)) } else { buf.WriteString(`{"contributors":null`) } if j.Coordinates != nil { buf.WriteString(`,"coordinates":`) fflib.WriteJsonString(buf, string(*j.Coordinates)) } else { buf.WriteString(`,"coordinates":null`) } buf.WriteString(`,"created_at":`) fflib.WriteJsonString(buf, string(j.CreatedAt)) buf.WriteString(`,"entities":`) { err = j.Entities.MarshalJSONBuf(buf) if err != nil { return err } } if j.Favorited { buf.WriteString(`,"favorited":true`) } else { buf.WriteString(`,"favorited":false`) } if j.Geo != nil { buf.WriteString(`,"geo":`) fflib.WriteJsonString(buf, string(*j.Geo)) } else { buf.WriteString(`,"geo":null`) } buf.WriteString(`,"id":`) fflib.FormatBits2(buf, uint64(j.ID), 10, j.ID < 0) buf.WriteString(`,"id_str":`) fflib.WriteJsonString(buf, string(j.IDStr)) if j.InReplyToScreenName != nil { buf.WriteString(`,"in_reply_to_screen_name":`) fflib.WriteJsonString(buf, string(*j.InReplyToScreenName)) } else { buf.WriteString(`,"in_reply_to_screen_name":null`) } if j.InReplyToStatusID != nil { buf.WriteString(`,"in_reply_to_status_id":`) fflib.WriteJsonString(buf, string(*j.InReplyToStatusID)) } else { buf.WriteString(`,"in_reply_to_status_id":null`) } if j.InReplyToStatusIDStr != nil { buf.WriteString(`,"in_reply_to_status_id_str":`) fflib.WriteJsonString(buf, string(*j.InReplyToStatusIDStr)) } else { buf.WriteString(`,"in_reply_to_status_id_str":null`) } if j.InReplyToUserID != nil { buf.WriteString(`,"in_reply_to_user_id":`) fflib.WriteJsonString(buf, string(*j.InReplyToUserID)) } else { buf.WriteString(`,"in_reply_to_user_id":null`) } if j.InReplyToUserIDStr != nil { buf.WriteString(`,"in_reply_to_user_id_str":`) fflib.WriteJsonString(buf, string(*j.InReplyToUserIDStr)) } else { buf.WriteString(`,"in_reply_to_user_id_str":null`) } buf.WriteString(`,"metadata":`) { err = j.Metadata.MarshalJSONBuf(buf) if err != nil { return err } } if j.Place != nil { buf.WriteString(`,"place":`) fflib.WriteJsonString(buf, string(*j.Place)) } else { buf.WriteString(`,"place":null`) } buf.WriteString(`,"retweet_count":`) fflib.FormatBits2(buf, uint64(j.RetweetCount), 10, j.RetweetCount < 0) if j.Retweeted { buf.WriteString(`,"retweeted":true`) } else { buf.WriteString(`,"retweeted":false`) } buf.WriteString(`,"source":`) fflib.WriteJsonString(buf, string(j.Source)) buf.WriteString(`,"text":`) fflib.WriteJsonString(buf, string(j.Text)) if j.Truncated { buf.WriteString(`,"truncated":true`) } else { buf.WriteString(`,"truncated":false`) } buf.WriteString(`,"user":`) { err = j.User.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteByte('}') return nil } const ( ffjtStatusbase = iota ffjtStatusnosuchkey ffjtStatusContributors ffjtStatusCoordinates ffjtStatusCreatedAt ffjtStatusEntities ffjtStatusFavorited ffjtStatusGeo ffjtStatusID ffjtStatusIDStr ffjtStatusInReplyToScreenName ffjtStatusInReplyToStatusID ffjtStatusInReplyToStatusIDStr ffjtStatusInReplyToUserID ffjtStatusInReplyToUserIDStr ffjtStatusMetadata ffjtStatusPlace ffjtStatusRetweetCount ffjtStatusRetweeted ffjtStatusSource ffjtStatusText ffjtStatusTruncated ffjtStatusUser ) var ffjKeyStatusContributors = []byte("contributors") var ffjKeyStatusCoordinates = []byte("coordinates") var ffjKeyStatusCreatedAt = []byte("created_at") var ffjKeyStatusEntities = []byte("entities") var ffjKeyStatusFavorited = []byte("favorited") var ffjKeyStatusGeo = []byte("geo") var ffjKeyStatusID = []byte("id") var ffjKeyStatusIDStr = []byte("id_str") var ffjKeyStatusInReplyToScreenName = []byte("in_reply_to_screen_name") var ffjKeyStatusInReplyToStatusID = []byte("in_reply_to_status_id") var ffjKeyStatusInReplyToStatusIDStr = []byte("in_reply_to_status_id_str") var ffjKeyStatusInReplyToUserID = []byte("in_reply_to_user_id") var ffjKeyStatusInReplyToUserIDStr = []byte("in_reply_to_user_id_str") var ffjKeyStatusMetadata = []byte("metadata") var ffjKeyStatusPlace = []byte("place") var ffjKeyStatusRetweetCount = []byte("retweet_count") var ffjKeyStatusRetweeted = []byte("retweeted") var ffjKeyStatusSource = []byte("source") var ffjKeyStatusText = []byte("text") var ffjKeyStatusTruncated = []byte("truncated") var ffjKeyStatusUser = []byte("user") // UnmarshalJSON umarshall json - template of ffjson func (j *Status) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *Status) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtStatusbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtStatusnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'c': if bytes.Equal(ffjKeyStatusContributors, kn) { currentKey = ffjtStatusContributors state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusCoordinates, kn) { currentKey = ffjtStatusCoordinates state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusCreatedAt, kn) { currentKey = ffjtStatusCreatedAt state = fflib.FFParse_want_colon goto mainparse } case 'e': if bytes.Equal(ffjKeyStatusEntities, kn) { currentKey = ffjtStatusEntities state = fflib.FFParse_want_colon goto mainparse } case 'f': if bytes.Equal(ffjKeyStatusFavorited, kn) { currentKey = ffjtStatusFavorited state = fflib.FFParse_want_colon goto mainparse } case 'g': if bytes.Equal(ffjKeyStatusGeo, kn) { currentKey = ffjtStatusGeo state = fflib.FFParse_want_colon goto mainparse } case 'i': if bytes.Equal(ffjKeyStatusID, kn) { currentKey = ffjtStatusID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusIDStr, kn) { currentKey = ffjtStatusIDStr state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusInReplyToScreenName, kn) { currentKey = ffjtStatusInReplyToScreenName state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusInReplyToStatusID, kn) { currentKey = ffjtStatusInReplyToStatusID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusInReplyToStatusIDStr, kn) { currentKey = ffjtStatusInReplyToStatusIDStr state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusInReplyToUserID, kn) { currentKey = ffjtStatusInReplyToUserID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusInReplyToUserIDStr, kn) { currentKey = ffjtStatusInReplyToUserIDStr state = fflib.FFParse_want_colon goto mainparse } case 'm': if bytes.Equal(ffjKeyStatusMetadata, kn) { currentKey = ffjtStatusMetadata state = fflib.FFParse_want_colon goto mainparse } case 'p': if bytes.Equal(ffjKeyStatusPlace, kn) { currentKey = ffjtStatusPlace state = fflib.FFParse_want_colon goto mainparse } case 'r': if bytes.Equal(ffjKeyStatusRetweetCount, kn) { currentKey = ffjtStatusRetweetCount state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusRetweeted, kn) { currentKey = ffjtStatusRetweeted state = fflib.FFParse_want_colon goto mainparse } case 's': if bytes.Equal(ffjKeyStatusSource, kn) { currentKey = ffjtStatusSource state = fflib.FFParse_want_colon goto mainparse } case 't': if bytes.Equal(ffjKeyStatusText, kn) { currentKey = ffjtStatusText state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyStatusTruncated, kn) { currentKey = ffjtStatusTruncated state = fflib.FFParse_want_colon goto mainparse } case 'u': if bytes.Equal(ffjKeyStatusUser, kn) { currentKey = ffjtStatusUser state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyStatusUser, kn) { currentKey = ffjtStatusUser state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusTruncated, kn) { currentKey = ffjtStatusTruncated state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusText, kn) { currentKey = ffjtStatusText state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusSource, kn) { currentKey = ffjtStatusSource state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusRetweeted, kn) { currentKey = ffjtStatusRetweeted state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyStatusRetweetCount, kn) { currentKey = ffjtStatusRetweetCount state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusPlace, kn) { currentKey = ffjtStatusPlace state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusMetadata, kn) { currentKey = ffjtStatusMetadata state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusInReplyToUserIDStr, kn) { currentKey = ffjtStatusInReplyToUserIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusInReplyToUserID, kn) { currentKey = ffjtStatusInReplyToUserID state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusInReplyToStatusIDStr, kn) { currentKey = ffjtStatusInReplyToStatusIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusInReplyToStatusID, kn) { currentKey = ffjtStatusInReplyToStatusID state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusInReplyToScreenName, kn) { currentKey = ffjtStatusInReplyToScreenName state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusIDStr, kn) { currentKey = ffjtStatusIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusID, kn) { currentKey = ffjtStatusID state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusGeo, kn) { currentKey = ffjtStatusGeo state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyStatusFavorited, kn) { currentKey = ffjtStatusFavorited state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusEntities, kn) { currentKey = ffjtStatusEntities state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyStatusCreatedAt, kn) { currentKey = ffjtStatusCreatedAt state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusCoordinates, kn) { currentKey = ffjtStatusCoordinates state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusContributors, kn) { currentKey = ffjtStatusContributors state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtStatusnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtStatusContributors: goto handle_Contributors case ffjtStatusCoordinates: goto handle_Coordinates case ffjtStatusCreatedAt: goto handle_CreatedAt case ffjtStatusEntities: goto handle_Entities case ffjtStatusFavorited: goto handle_Favorited case ffjtStatusGeo: goto handle_Geo case ffjtStatusID: goto handle_ID case ffjtStatusIDStr: goto handle_IDStr case ffjtStatusInReplyToScreenName: goto handle_InReplyToScreenName case ffjtStatusInReplyToStatusID: goto handle_InReplyToStatusID case ffjtStatusInReplyToStatusIDStr: goto handle_InReplyToStatusIDStr case ffjtStatusInReplyToUserID: goto handle_InReplyToUserID case ffjtStatusInReplyToUserIDStr: goto handle_InReplyToUserIDStr case ffjtStatusMetadata: goto handle_Metadata case ffjtStatusPlace: goto handle_Place case ffjtStatusRetweetCount: goto handle_RetweetCount case ffjtStatusRetweeted: goto handle_Retweeted case ffjtStatusSource: goto handle_Source case ffjtStatusText: goto handle_Text case ffjtStatusTruncated: goto handle_Truncated case ffjtStatusUser: goto handle_User case ffjtStatusnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Contributors: /* handler: j.Contributors type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Contributors = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Contributors = &tval } } state = fflib.FFParse_after_value goto mainparse handle_Coordinates: /* handler: j.Coordinates type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Coordinates = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Coordinates = &tval } } state = fflib.FFParse_after_value goto mainparse handle_CreatedAt: /* handler: j.CreatedAt type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.CreatedAt = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Entities: /* handler: j.Entities type=benchmark.Entities kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Favorited: /* handler: j.Favorited type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.Favorited = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.Favorited = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_Geo: /* handler: j.Geo type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Geo = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Geo = &tval } } state = fflib.FFParse_after_value goto mainparse handle_ID: /* handler: j.ID type=int64 kind=int64 quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int64", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.ID = int64(tval) } } state = fflib.FFParse_after_value goto mainparse handle_IDStr: /* handler: j.IDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.IDStr = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_InReplyToScreenName: /* handler: j.InReplyToScreenName type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.InReplyToScreenName = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.InReplyToScreenName = &tval } } state = fflib.FFParse_after_value goto mainparse handle_InReplyToStatusID: /* handler: j.InReplyToStatusID type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.InReplyToStatusID = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.InReplyToStatusID = &tval } } state = fflib.FFParse_after_value goto mainparse handle_InReplyToStatusIDStr: /* handler: j.InReplyToStatusIDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.InReplyToStatusIDStr = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.InReplyToStatusIDStr = &tval } } state = fflib.FFParse_after_value goto mainparse handle_InReplyToUserID: /* handler: j.InReplyToUserID type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.InReplyToUserID = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.InReplyToUserID = &tval } } state = fflib.FFParse_after_value goto mainparse handle_InReplyToUserIDStr: /* handler: j.InReplyToUserIDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.InReplyToUserIDStr = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.InReplyToUserIDStr = &tval } } state = fflib.FFParse_after_value goto mainparse handle_Metadata: /* handler: j.Metadata type=benchmark.StatusMetadata kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Metadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Place: /* handler: j.Place type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Place = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Place = &tval } } state = fflib.FFParse_after_value goto mainparse handle_RetweetCount: /* handler: j.RetweetCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.RetweetCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_Retweeted: /* handler: j.Retweeted type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.Retweeted = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.Retweeted = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_Source: /* handler: j.Source type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Source = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Text: /* handler: j.Text type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Text = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Truncated: /* handler: j.Truncated type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.Truncated = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.Truncated = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_User: /* handler: j.User type=benchmark.User kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.User.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *StatusMetadata) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *StatusMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"iso_language_code":`) fflib.WriteJsonString(buf, string(j.IsoLanguageCode)) buf.WriteString(`,"result_type":`) fflib.WriteJsonString(buf, string(j.ResultType)) buf.WriteByte('}') return nil } const ( ffjtStatusMetadatabase = iota ffjtStatusMetadatanosuchkey ffjtStatusMetadataIsoLanguageCode ffjtStatusMetadataResultType ) var ffjKeyStatusMetadataIsoLanguageCode = []byte("iso_language_code") var ffjKeyStatusMetadataResultType = []byte("result_type") // UnmarshalJSON umarshall json - template of ffjson func (j *StatusMetadata) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *StatusMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtStatusMetadatabase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtStatusMetadatanosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'i': if bytes.Equal(ffjKeyStatusMetadataIsoLanguageCode, kn) { currentKey = ffjtStatusMetadataIsoLanguageCode state = fflib.FFParse_want_colon goto mainparse } case 'r': if bytes.Equal(ffjKeyStatusMetadataResultType, kn) { currentKey = ffjtStatusMetadataResultType state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyStatusMetadataResultType, kn) { currentKey = ffjtStatusMetadataResultType state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyStatusMetadataIsoLanguageCode, kn) { currentKey = ffjtStatusMetadataIsoLanguageCode state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtStatusMetadatanosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtStatusMetadataIsoLanguageCode: goto handle_IsoLanguageCode case ffjtStatusMetadataResultType: goto handle_ResultType case ffjtStatusMetadatanosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_IsoLanguageCode: /* handler: j.IsoLanguageCode type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.IsoLanguageCode = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ResultType: /* handler: j.ResultType type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ResultType = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *URL) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *URL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err if j.ExpandedURL != nil { buf.WriteString(`{"expanded_url":`) fflib.WriteJsonString(buf, string(*j.ExpandedURL)) } else { buf.WriteString(`{"expanded_url":null`) } buf.WriteString(`,"indices":`) if j.Indices != nil { buf.WriteString(`[`) for i, v := range j.Indices { if i != 0 { buf.WriteString(`,`) } fflib.FormatBits2(buf, uint64(v), 10, v < 0) } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteString(`,"url":`) fflib.WriteJsonString(buf, string(j.URL)) buf.WriteByte('}') return nil } const ( ffjtURLbase = iota ffjtURLnosuchkey ffjtURLExpandedURL ffjtURLIndices ffjtURLURL ) var ffjKeyURLExpandedURL = []byte("expanded_url") var ffjKeyURLIndices = []byte("indices") var ffjKeyURLURL = []byte("url") // UnmarshalJSON umarshall json - template of ffjson func (j *URL) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *URL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtURLbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtURLnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'e': if bytes.Equal(ffjKeyURLExpandedURL, kn) { currentKey = ffjtURLExpandedURL state = fflib.FFParse_want_colon goto mainparse } case 'i': if bytes.Equal(ffjKeyURLIndices, kn) { currentKey = ffjtURLIndices state = fflib.FFParse_want_colon goto mainparse } case 'u': if bytes.Equal(ffjKeyURLURL, kn) { currentKey = ffjtURLURL state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyURLURL, kn) { currentKey = ffjtURLURL state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyURLIndices, kn) { currentKey = ffjtURLIndices state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyURLExpandedURL, kn) { currentKey = ffjtURLExpandedURL state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtURLnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtURLExpandedURL: goto handle_ExpandedURL case ffjtURLIndices: goto handle_Indices case ffjtURLURL: goto handle_URL case ffjtURLnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_ExpandedURL: /* handler: j.ExpandedURL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.ExpandedURL = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.ExpandedURL = &tval } } state = fflib.FFParse_after_value goto mainparse handle_Indices: /* handler: j.Indices type=[]int kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Indices = nil } else { j.Indices = []int{} wantVal := true for { var tmpJIndices int tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJIndices type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } tmpJIndices = int(tval) } } j.Indices = append(j.Indices, tmpJIndices) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse handle_URL: /* handler: j.URL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.URL = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *User) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *User) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err if j.ContributorsEnabled { buf.WriteString(`{"contributors_enabled":true`) } else { buf.WriteString(`{"contributors_enabled":false`) } buf.WriteString(`,"created_at":`) fflib.WriteJsonString(buf, string(j.CreatedAt)) if j.DefaultProfile { buf.WriteString(`,"default_profile":true`) } else { buf.WriteString(`,"default_profile":false`) } if j.DefaultProfileImage { buf.WriteString(`,"default_profile_image":true`) } else { buf.WriteString(`,"default_profile_image":false`) } buf.WriteString(`,"description":`) fflib.WriteJsonString(buf, string(j.Description)) buf.WriteString(`,"entities":`) { err = j.Entities.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteString(`,"favourites_count":`) fflib.FormatBits2(buf, uint64(j.FavouritesCount), 10, j.FavouritesCount < 0) if j.FollowRequestSent != nil { buf.WriteString(`,"follow_request_sent":`) fflib.WriteJsonString(buf, string(*j.FollowRequestSent)) } else { buf.WriteString(`,"follow_request_sent":null`) } buf.WriteString(`,"followers_count":`) fflib.FormatBits2(buf, uint64(j.FollowersCount), 10, j.FollowersCount < 0) if j.Following != nil { buf.WriteString(`,"following":`) fflib.WriteJsonString(buf, string(*j.Following)) } else { buf.WriteString(`,"following":null`) } buf.WriteString(`,"friends_count":`) fflib.FormatBits2(buf, uint64(j.FriendsCount), 10, j.FriendsCount < 0) if j.GeoEnabled { buf.WriteString(`,"geo_enabled":true`) } else { buf.WriteString(`,"geo_enabled":false`) } buf.WriteString(`,"id":`) fflib.FormatBits2(buf, uint64(j.ID), 10, j.ID < 0) buf.WriteString(`,"id_str":`) fflib.WriteJsonString(buf, string(j.IDStr)) if j.IsTranslator { buf.WriteString(`,"is_translator":true`) } else { buf.WriteString(`,"is_translator":false`) } buf.WriteString(`,"lang":`) fflib.WriteJsonString(buf, string(j.Lang)) buf.WriteString(`,"listed_count":`) fflib.FormatBits2(buf, uint64(j.ListedCount), 10, j.ListedCount < 0) buf.WriteString(`,"location":`) fflib.WriteJsonString(buf, string(j.Location)) buf.WriteString(`,"name":`) fflib.WriteJsonString(buf, string(j.Name)) if j.Notifications != nil { buf.WriteString(`,"notifications":`) fflib.WriteJsonString(buf, string(*j.Notifications)) } else { buf.WriteString(`,"notifications":null`) } buf.WriteString(`,"profile_background_color":`) fflib.WriteJsonString(buf, string(j.ProfileBackgroundColor)) buf.WriteString(`,"profile_background_image_url":`) fflib.WriteJsonString(buf, string(j.ProfileBackgroundImageURL)) buf.WriteString(`,"profile_background_image_url_https":`) fflib.WriteJsonString(buf, string(j.ProfileBackgroundImageURLHTTPS)) if j.ProfileBackgroundTile { buf.WriteString(`,"profile_background_tile":true`) } else { buf.WriteString(`,"profile_background_tile":false`) } buf.WriteString(`,"profile_image_url":`) fflib.WriteJsonString(buf, string(j.ProfileImageURL)) buf.WriteString(`,"profile_image_url_https":`) fflib.WriteJsonString(buf, string(j.ProfileImageURLHTTPS)) buf.WriteString(`,"profile_link_color":`) fflib.WriteJsonString(buf, string(j.ProfileLinkColor)) buf.WriteString(`,"profile_sidebar_border_color":`) fflib.WriteJsonString(buf, string(j.ProfileSidebarBorderColor)) buf.WriteString(`,"profile_sidebar_fill_color":`) fflib.WriteJsonString(buf, string(j.ProfileSidebarFillColor)) buf.WriteString(`,"profile_text_color":`) fflib.WriteJsonString(buf, string(j.ProfileTextColor)) if j.ProfileUseBackgroundImage { buf.WriteString(`,"profile_use_background_image":true`) } else { buf.WriteString(`,"profile_use_background_image":false`) } if j.Protected { buf.WriteString(`,"protected":true`) } else { buf.WriteString(`,"protected":false`) } buf.WriteString(`,"screen_name":`) fflib.WriteJsonString(buf, string(j.ScreenName)) if j.ShowAllInlineMedia { buf.WriteString(`,"show_all_inline_media":true`) } else { buf.WriteString(`,"show_all_inline_media":false`) } buf.WriteString(`,"statuses_count":`) fflib.FormatBits2(buf, uint64(j.StatusesCount), 10, j.StatusesCount < 0) buf.WriteString(`,"time_zone":`) fflib.WriteJsonString(buf, string(j.TimeZone)) if j.URL != nil { buf.WriteString(`,"url":`) fflib.WriteJsonString(buf, string(*j.URL)) } else { buf.WriteString(`,"url":null`) } buf.WriteString(`,"utc_offset":`) fflib.FormatBits2(buf, uint64(j.UtcOffset), 10, j.UtcOffset < 0) if j.Verified { buf.WriteString(`,"verified":true`) } else { buf.WriteString(`,"verified":false`) } buf.WriteByte('}') return nil } const ( ffjtUserbase = iota ffjtUsernosuchkey ffjtUserContributorsEnabled ffjtUserCreatedAt ffjtUserDefaultProfile ffjtUserDefaultProfileImage ffjtUserDescription ffjtUserEntities ffjtUserFavouritesCount ffjtUserFollowRequestSent ffjtUserFollowersCount ffjtUserFollowing ffjtUserFriendsCount ffjtUserGeoEnabled ffjtUserID ffjtUserIDStr ffjtUserIsTranslator ffjtUserLang ffjtUserListedCount ffjtUserLocation ffjtUserName ffjtUserNotifications ffjtUserProfileBackgroundColor ffjtUserProfileBackgroundImageURL ffjtUserProfileBackgroundImageURLHTTPS ffjtUserProfileBackgroundTile ffjtUserProfileImageURL ffjtUserProfileImageURLHTTPS ffjtUserProfileLinkColor ffjtUserProfileSidebarBorderColor ffjtUserProfileSidebarFillColor ffjtUserProfileTextColor ffjtUserProfileUseBackgroundImage ffjtUserProtected ffjtUserScreenName ffjtUserShowAllInlineMedia ffjtUserStatusesCount ffjtUserTimeZone ffjtUserURL ffjtUserUtcOffset ffjtUserVerified ) var ffjKeyUserContributorsEnabled = []byte("contributors_enabled") var ffjKeyUserCreatedAt = []byte("created_at") var ffjKeyUserDefaultProfile = []byte("default_profile") var ffjKeyUserDefaultProfileImage = []byte("default_profile_image") var ffjKeyUserDescription = []byte("description") var ffjKeyUserEntities = []byte("entities") var ffjKeyUserFavouritesCount = []byte("favourites_count") var ffjKeyUserFollowRequestSent = []byte("follow_request_sent") var ffjKeyUserFollowersCount = []byte("followers_count") var ffjKeyUserFollowing = []byte("following") var ffjKeyUserFriendsCount = []byte("friends_count") var ffjKeyUserGeoEnabled = []byte("geo_enabled") var ffjKeyUserID = []byte("id") var ffjKeyUserIDStr = []byte("id_str") var ffjKeyUserIsTranslator = []byte("is_translator") var ffjKeyUserLang = []byte("lang") var ffjKeyUserListedCount = []byte("listed_count") var ffjKeyUserLocation = []byte("location") var ffjKeyUserName = []byte("name") var ffjKeyUserNotifications = []byte("notifications") var ffjKeyUserProfileBackgroundColor = []byte("profile_background_color") var ffjKeyUserProfileBackgroundImageURL = []byte("profile_background_image_url") var ffjKeyUserProfileBackgroundImageURLHTTPS = []byte("profile_background_image_url_https") var ffjKeyUserProfileBackgroundTile = []byte("profile_background_tile") var ffjKeyUserProfileImageURL = []byte("profile_image_url") var ffjKeyUserProfileImageURLHTTPS = []byte("profile_image_url_https") var ffjKeyUserProfileLinkColor = []byte("profile_link_color") var ffjKeyUserProfileSidebarBorderColor = []byte("profile_sidebar_border_color") var ffjKeyUserProfileSidebarFillColor = []byte("profile_sidebar_fill_color") var ffjKeyUserProfileTextColor = []byte("profile_text_color") var ffjKeyUserProfileUseBackgroundImage = []byte("profile_use_background_image") var ffjKeyUserProtected = []byte("protected") var ffjKeyUserScreenName = []byte("screen_name") var ffjKeyUserShowAllInlineMedia = []byte("show_all_inline_media") var ffjKeyUserStatusesCount = []byte("statuses_count") var ffjKeyUserTimeZone = []byte("time_zone") var ffjKeyUserURL = []byte("url") var ffjKeyUserUtcOffset = []byte("utc_offset") var ffjKeyUserVerified = []byte("verified") // UnmarshalJSON umarshall json - template of ffjson func (j *User) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *User) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtUserbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtUsernosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'c': if bytes.Equal(ffjKeyUserContributorsEnabled, kn) { currentKey = ffjtUserContributorsEnabled state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserCreatedAt, kn) { currentKey = ffjtUserCreatedAt state = fflib.FFParse_want_colon goto mainparse } case 'd': if bytes.Equal(ffjKeyUserDefaultProfile, kn) { currentKey = ffjtUserDefaultProfile state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserDefaultProfileImage, kn) { currentKey = ffjtUserDefaultProfileImage state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserDescription, kn) { currentKey = ffjtUserDescription state = fflib.FFParse_want_colon goto mainparse } case 'e': if bytes.Equal(ffjKeyUserEntities, kn) { currentKey = ffjtUserEntities state = fflib.FFParse_want_colon goto mainparse } case 'f': if bytes.Equal(ffjKeyUserFavouritesCount, kn) { currentKey = ffjtUserFavouritesCount state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserFollowRequestSent, kn) { currentKey = ffjtUserFollowRequestSent state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserFollowersCount, kn) { currentKey = ffjtUserFollowersCount state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserFollowing, kn) { currentKey = ffjtUserFollowing state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserFriendsCount, kn) { currentKey = ffjtUserFriendsCount state = fflib.FFParse_want_colon goto mainparse } case 'g': if bytes.Equal(ffjKeyUserGeoEnabled, kn) { currentKey = ffjtUserGeoEnabled state = fflib.FFParse_want_colon goto mainparse } case 'i': if bytes.Equal(ffjKeyUserID, kn) { currentKey = ffjtUserID state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserIDStr, kn) { currentKey = ffjtUserIDStr state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserIsTranslator, kn) { currentKey = ffjtUserIsTranslator state = fflib.FFParse_want_colon goto mainparse } case 'l': if bytes.Equal(ffjKeyUserLang, kn) { currentKey = ffjtUserLang state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserListedCount, kn) { currentKey = ffjtUserListedCount state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserLocation, kn) { currentKey = ffjtUserLocation state = fflib.FFParse_want_colon goto mainparse } case 'n': if bytes.Equal(ffjKeyUserName, kn) { currentKey = ffjtUserName state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserNotifications, kn) { currentKey = ffjtUserNotifications state = fflib.FFParse_want_colon goto mainparse } case 'p': if bytes.Equal(ffjKeyUserProfileBackgroundColor, kn) { currentKey = ffjtUserProfileBackgroundColor state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileBackgroundImageURL, kn) { currentKey = ffjtUserProfileBackgroundImageURL state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileBackgroundImageURLHTTPS, kn) { currentKey = ffjtUserProfileBackgroundImageURLHTTPS state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileBackgroundTile, kn) { currentKey = ffjtUserProfileBackgroundTile state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileImageURL, kn) { currentKey = ffjtUserProfileImageURL state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileImageURLHTTPS, kn) { currentKey = ffjtUserProfileImageURLHTTPS state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileLinkColor, kn) { currentKey = ffjtUserProfileLinkColor state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileSidebarBorderColor, kn) { currentKey = ffjtUserProfileSidebarBorderColor state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileSidebarFillColor, kn) { currentKey = ffjtUserProfileSidebarFillColor state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileTextColor, kn) { currentKey = ffjtUserProfileTextColor state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProfileUseBackgroundImage, kn) { currentKey = ffjtUserProfileUseBackgroundImage state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserProtected, kn) { currentKey = ffjtUserProtected state = fflib.FFParse_want_colon goto mainparse } case 's': if bytes.Equal(ffjKeyUserScreenName, kn) { currentKey = ffjtUserScreenName state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserShowAllInlineMedia, kn) { currentKey = ffjtUserShowAllInlineMedia state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserStatusesCount, kn) { currentKey = ffjtUserStatusesCount state = fflib.FFParse_want_colon goto mainparse } case 't': if bytes.Equal(ffjKeyUserTimeZone, kn) { currentKey = ffjtUserTimeZone state = fflib.FFParse_want_colon goto mainparse } case 'u': if bytes.Equal(ffjKeyUserURL, kn) { currentKey = ffjtUserURL state = fflib.FFParse_want_colon goto mainparse } else if bytes.Equal(ffjKeyUserUtcOffset, kn) { currentKey = ffjtUserUtcOffset state = fflib.FFParse_want_colon goto mainparse } case 'v': if bytes.Equal(ffjKeyUserVerified, kn) { currentKey = ffjtUserVerified state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyUserVerified, kn) { currentKey = ffjtUserVerified state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserUtcOffset, kn) { currentKey = ffjtUserUtcOffset state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserURL, kn) { currentKey = ffjtUserURL state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserTimeZone, kn) { currentKey = ffjtUserTimeZone state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserStatusesCount, kn) { currentKey = ffjtUserStatusesCount state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserShowAllInlineMedia, kn) { currentKey = ffjtUserShowAllInlineMedia state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserScreenName, kn) { currentKey = ffjtUserScreenName state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserProtected, kn) { currentKey = ffjtUserProtected state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileUseBackgroundImage, kn) { currentKey = ffjtUserProfileUseBackgroundImage state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserProfileTextColor, kn) { currentKey = ffjtUserProfileTextColor state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileSidebarFillColor, kn) { currentKey = ffjtUserProfileSidebarFillColor state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileSidebarBorderColor, kn) { currentKey = ffjtUserProfileSidebarBorderColor state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileLinkColor, kn) { currentKey = ffjtUserProfileLinkColor state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileImageURLHTTPS, kn) { currentKey = ffjtUserProfileImageURLHTTPS state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserProfileImageURL, kn) { currentKey = ffjtUserProfileImageURL state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileBackgroundTile, kn) { currentKey = ffjtUserProfileBackgroundTile state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileBackgroundImageURLHTTPS, kn) { currentKey = ffjtUserProfileBackgroundImageURLHTTPS state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileBackgroundImageURL, kn) { currentKey = ffjtUserProfileBackgroundImageURL state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserProfileBackgroundColor, kn) { currentKey = ffjtUserProfileBackgroundColor state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserNotifications, kn) { currentKey = ffjtUserNotifications state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserName, kn) { currentKey = ffjtUserName state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserLocation, kn) { currentKey = ffjtUserLocation state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserListedCount, kn) { currentKey = ffjtUserListedCount state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserLang, kn) { currentKey = ffjtUserLang state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserIsTranslator, kn) { currentKey = ffjtUserIsTranslator state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserIDStr, kn) { currentKey = ffjtUserIDStr state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserID, kn) { currentKey = ffjtUserID state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserGeoEnabled, kn) { currentKey = ffjtUserGeoEnabled state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserFriendsCount, kn) { currentKey = ffjtUserFriendsCount state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyUserFollowing, kn) { currentKey = ffjtUserFollowing state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserFollowersCount, kn) { currentKey = ffjtUserFollowersCount state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserFollowRequestSent, kn) { currentKey = ffjtUserFollowRequestSent state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserFavouritesCount, kn) { currentKey = ffjtUserFavouritesCount state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserEntities, kn) { currentKey = ffjtUserEntities state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserDescription, kn) { currentKey = ffjtUserDescription state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserDefaultProfileImage, kn) { currentKey = ffjtUserDefaultProfileImage state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserDefaultProfile, kn) { currentKey = ffjtUserDefaultProfile state = fflib.FFParse_want_colon goto mainparse } if fflib.AsciiEqualFold(ffjKeyUserCreatedAt, kn) { currentKey = ffjtUserCreatedAt state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserContributorsEnabled, kn) { currentKey = ffjtUserContributorsEnabled state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtUsernosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtUserContributorsEnabled: goto handle_ContributorsEnabled case ffjtUserCreatedAt: goto handle_CreatedAt case ffjtUserDefaultProfile: goto handle_DefaultProfile case ffjtUserDefaultProfileImage: goto handle_DefaultProfileImage case ffjtUserDescription: goto handle_Description case ffjtUserEntities: goto handle_Entities case ffjtUserFavouritesCount: goto handle_FavouritesCount case ffjtUserFollowRequestSent: goto handle_FollowRequestSent case ffjtUserFollowersCount: goto handle_FollowersCount case ffjtUserFollowing: goto handle_Following case ffjtUserFriendsCount: goto handle_FriendsCount case ffjtUserGeoEnabled: goto handle_GeoEnabled case ffjtUserID: goto handle_ID case ffjtUserIDStr: goto handle_IDStr case ffjtUserIsTranslator: goto handle_IsTranslator case ffjtUserLang: goto handle_Lang case ffjtUserListedCount: goto handle_ListedCount case ffjtUserLocation: goto handle_Location case ffjtUserName: goto handle_Name case ffjtUserNotifications: goto handle_Notifications case ffjtUserProfileBackgroundColor: goto handle_ProfileBackgroundColor case ffjtUserProfileBackgroundImageURL: goto handle_ProfileBackgroundImageURL case ffjtUserProfileBackgroundImageURLHTTPS: goto handle_ProfileBackgroundImageURLHTTPS case ffjtUserProfileBackgroundTile: goto handle_ProfileBackgroundTile case ffjtUserProfileImageURL: goto handle_ProfileImageURL case ffjtUserProfileImageURLHTTPS: goto handle_ProfileImageURLHTTPS case ffjtUserProfileLinkColor: goto handle_ProfileLinkColor case ffjtUserProfileSidebarBorderColor: goto handle_ProfileSidebarBorderColor case ffjtUserProfileSidebarFillColor: goto handle_ProfileSidebarFillColor case ffjtUserProfileTextColor: goto handle_ProfileTextColor case ffjtUserProfileUseBackgroundImage: goto handle_ProfileUseBackgroundImage case ffjtUserProtected: goto handle_Protected case ffjtUserScreenName: goto handle_ScreenName case ffjtUserShowAllInlineMedia: goto handle_ShowAllInlineMedia case ffjtUserStatusesCount: goto handle_StatusesCount case ffjtUserTimeZone: goto handle_TimeZone case ffjtUserURL: goto handle_URL case ffjtUserUtcOffset: goto handle_UtcOffset case ffjtUserVerified: goto handle_Verified case ffjtUsernosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_ContributorsEnabled: /* handler: j.ContributorsEnabled type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.ContributorsEnabled = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.ContributorsEnabled = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_CreatedAt: /* handler: j.CreatedAt type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.CreatedAt = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_DefaultProfile: /* handler: j.DefaultProfile type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.DefaultProfile = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.DefaultProfile = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_DefaultProfileImage: /* handler: j.DefaultProfileImage type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.DefaultProfileImage = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.DefaultProfileImage = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_Description: /* handler: j.Description type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Description = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Entities: /* handler: j.Entities type=benchmark.UserEntities kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_FavouritesCount: /* handler: j.FavouritesCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.FavouritesCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_FollowRequestSent: /* handler: j.FollowRequestSent type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.FollowRequestSent = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.FollowRequestSent = &tval } } state = fflib.FFParse_after_value goto mainparse handle_FollowersCount: /* handler: j.FollowersCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.FollowersCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_Following: /* handler: j.Following type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Following = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Following = &tval } } state = fflib.FFParse_after_value goto mainparse handle_FriendsCount: /* handler: j.FriendsCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.FriendsCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_GeoEnabled: /* handler: j.GeoEnabled type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.GeoEnabled = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.GeoEnabled = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_ID: /* handler: j.ID type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.ID = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_IDStr: /* handler: j.IDStr type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.IDStr = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_IsTranslator: /* handler: j.IsTranslator type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.IsTranslator = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.IsTranslator = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_Lang: /* handler: j.Lang type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Lang = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ListedCount: /* handler: j.ListedCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.ListedCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_Location: /* handler: j.Location type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Location = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Name: /* handler: j.Name type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.Name = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_Notifications: /* handler: j.Notifications type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.Notifications = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.Notifications = &tval } } state = fflib.FFParse_after_value goto mainparse handle_ProfileBackgroundColor: /* handler: j.ProfileBackgroundColor type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileBackgroundColor = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileBackgroundImageURL: /* handler: j.ProfileBackgroundImageURL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileBackgroundImageURL = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileBackgroundImageURLHTTPS: /* handler: j.ProfileBackgroundImageURLHTTPS type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileBackgroundImageURLHTTPS = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileBackgroundTile: /* handler: j.ProfileBackgroundTile type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.ProfileBackgroundTile = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.ProfileBackgroundTile = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_ProfileImageURL: /* handler: j.ProfileImageURL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileImageURL = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileImageURLHTTPS: /* handler: j.ProfileImageURLHTTPS type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileImageURLHTTPS = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileLinkColor: /* handler: j.ProfileLinkColor type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileLinkColor = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileSidebarBorderColor: /* handler: j.ProfileSidebarBorderColor type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileSidebarBorderColor = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileSidebarFillColor: /* handler: j.ProfileSidebarFillColor type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileSidebarFillColor = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileTextColor: /* handler: j.ProfileTextColor type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ProfileTextColor = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ProfileUseBackgroundImage: /* handler: j.ProfileUseBackgroundImage type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.ProfileUseBackgroundImage = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.ProfileUseBackgroundImage = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_Protected: /* handler: j.Protected type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.Protected = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.Protected = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_ScreenName: /* handler: j.ScreenName type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.ScreenName = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_ShowAllInlineMedia: /* handler: j.ShowAllInlineMedia type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.ShowAllInlineMedia = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.ShowAllInlineMedia = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse handle_StatusesCount: /* handler: j.StatusesCount type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.StatusesCount = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_TimeZone: /* handler: j.TimeZone type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { } else { outBuf := fs.Output.Bytes() j.TimeZone = string(string(outBuf)) } } state = fflib.FFParse_after_value goto mainparse handle_URL: /* handler: j.URL type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { j.URL = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) j.URL = &tval } } state = fflib.FFParse_after_value goto mainparse handle_UtcOffset: /* handler: j.UtcOffset type=int kind=int quoted=false*/ { if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) } } { if tok == fflib.FFTok_null { } else { tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) if err != nil { return fs.WrapErr(err) } j.UtcOffset = int(tval) } } state = fflib.FFParse_after_value goto mainparse handle_Verified: /* handler: j.Verified type=bool kind=bool quoted=false*/ { if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) } } { if tok == fflib.FFTok_null { } else { tmpb := fs.Output.Bytes() if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { j.Verified = true } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { j.Verified = false } else { err = errors.New("unexpected bytes for true/false value") return fs.WrapErr(err) } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *UserEntities) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *UserEntities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"description":`) { err = j.Description.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteString(`,"url":`) { err = j.URL.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteByte('}') return nil } const ( ffjtUserEntitiesbase = iota ffjtUserEntitiesnosuchkey ffjtUserEntitiesDescription ffjtUserEntitiesURL ) var ffjKeyUserEntitiesDescription = []byte("description") var ffjKeyUserEntitiesURL = []byte("url") // UnmarshalJSON umarshall json - template of ffjson func (j *UserEntities) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *UserEntities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtUserEntitiesbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtUserEntitiesnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'd': if bytes.Equal(ffjKeyUserEntitiesDescription, kn) { currentKey = ffjtUserEntitiesDescription state = fflib.FFParse_want_colon goto mainparse } case 'u': if bytes.Equal(ffjKeyUserEntitiesURL, kn) { currentKey = ffjtUserEntitiesURL state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyUserEntitiesURL, kn) { currentKey = ffjtUserEntitiesURL state = fflib.FFParse_want_colon goto mainparse } if fflib.EqualFoldRight(ffjKeyUserEntitiesDescription, kn) { currentKey = ffjtUserEntitiesDescription state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtUserEntitiesnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtUserEntitiesDescription: goto handle_Description case ffjtUserEntitiesURL: goto handle_URL case ffjtUserEntitiesnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Description: /* handler: j.Description type=benchmark.UserEntityDescription kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Description.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_URL: /* handler: j.URL type=benchmark.UserEntityURL kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.URL.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *UserEntityDescription) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *UserEntityDescription) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"urls":`) if j.Urls != nil { buf.WriteString(`[`) for i, v := range j.Urls { if i != 0 { buf.WriteString(`,`) } if v != nil { fflib.WriteJsonString(buf, string(*v)) } else { buf.WriteString(`null`) } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteByte('}') return nil } const ( ffjtUserEntityDescriptionbase = iota ffjtUserEntityDescriptionnosuchkey ffjtUserEntityDescriptionUrls ) var ffjKeyUserEntityDescriptionUrls = []byte("urls") // UnmarshalJSON umarshall json - template of ffjson func (j *UserEntityDescription) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *UserEntityDescription) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtUserEntityDescriptionbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtUserEntityDescriptionnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'u': if bytes.Equal(ffjKeyUserEntityDescriptionUrls, kn) { currentKey = ffjtUserEntityDescriptionUrls state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyUserEntityDescriptionUrls, kn) { currentKey = ffjtUserEntityDescriptionUrls state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtUserEntityDescriptionnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtUserEntityDescriptionUrls: goto handle_Urls case ffjtUserEntityDescriptionnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Urls: /* handler: j.Urls type=[]*string kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Urls = nil } else { j.Urls = []*string{} wantVal := true for { var tmpJUrls *string tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJUrls type=*string kind=ptr quoted=false*/ { if tok == fflib.FFTok_null { tmpJUrls = nil } else { if tmpJUrls == nil { tmpJUrls = new(string) } /* handler: tmpJUrls type=string kind=string quoted=false*/ { { if tok != fflib.FFTok_string && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) } } if tok == fflib.FFTok_null { tmpJUrls = nil } else { var tval string outBuf := fs.Output.Bytes() tval = string(string(outBuf)) tmpJUrls = &tval } } } } j.Urls = append(j.Urls, tmpJUrls) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *UserEntityURL) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *UserEntityURL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"urls":`) if j.Urls != nil { buf.WriteString(`[`) for i, v := range j.Urls { if i != 0 { buf.WriteString(`,`) } { err = v.MarshalJSONBuf(buf) if err != nil { return err } } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteByte('}') return nil } const ( ffjtUserEntityURLbase = iota ffjtUserEntityURLnosuchkey ffjtUserEntityURLUrls ) var ffjKeyUserEntityURLUrls = []byte("urls") // UnmarshalJSON umarshall json - template of ffjson func (j *UserEntityURL) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *UserEntityURL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtUserEntityURLbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtUserEntityURLnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'u': if bytes.Equal(ffjKeyUserEntityURLUrls, kn) { currentKey = ffjtUserEntityURLUrls state = fflib.FFParse_want_colon goto mainparse } } if fflib.EqualFoldRight(ffjKeyUserEntityURLUrls, kn) { currentKey = ffjtUserEntityURLUrls state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtUserEntityURLnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtUserEntityURLUrls: goto handle_Urls case ffjtUserEntityURLnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Urls: /* handler: j.Urls type=[]benchmark.URL kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Urls = nil } else { j.Urls = []URL{} wantVal := true for { var tmpJUrls URL tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJUrls type=benchmark.URL kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = tmpJUrls.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } j.Urls = append(j.Urls, tmpJUrls) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } // MarshalJSON marshal bytes to json - template func (j *XLStruct) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *XLStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"Data":`) if j.Data != nil { buf.WriteString(`[`) for i, v := range j.Data { if i != 0 { buf.WriteString(`,`) } { err = v.MarshalJSONBuf(buf) if err != nil { return err } } } buf.WriteString(`]`) } else { buf.WriteString(`null`) } buf.WriteByte('}') return nil } const ( ffjtXLStructbase = iota ffjtXLStructnosuchkey ffjtXLStructData ) var ffjKeyXLStructData = []byte("Data") // UnmarshalJSON umarshall json - template of ffjson func (j *XLStruct) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *XLStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtXLStructbase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtXLStructnosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'D': if bytes.Equal(ffjKeyXLStructData, kn) { currentKey = ffjtXLStructData state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyXLStructData, kn) { currentKey = ffjtXLStructData state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtXLStructnosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtXLStructData: goto handle_Data case ffjtXLStructnosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_Data: /* handler: j.Data type=[]benchmark.LargeStruct kind=slice quoted=false*/ { { if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) } } if tok == fflib.FFTok_null { j.Data = nil } else { j.Data = []LargeStruct{} wantVal := true for { var tmpJData LargeStruct tok = fs.Scan() if tok == fflib.FFTok_error { goto tokerror } if tok == fflib.FFTok_right_brace { break } if tok == fflib.FFTok_comma { if wantVal == true { // TODO(pquerna): this isn't an ideal error message, this handles // things like [,,,] as an array value. return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) } continue } else { wantVal = true } /* handler: tmpJData type=benchmark.LargeStruct kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = tmpJData.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } j.Data = append(j.Data, tmpJData) wantVal = false } } } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil } easyjson-0.7.6/benchmark/data_var.go000066400000000000000000000316501371475264500174440ustar00rootroot00000000000000package benchmark var largeStructData = LargeStruct{ SearchMetadata: SearchMetadata{ CompletedIn: 0.035, Count: 4, MaxID: 250126199840518145, MaxIDStr: "250126199840518145", NextResults: "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", Query: "%23freebandnames", RefreshURL: "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", SinceID: 24012619984051000, SinceIDStr: "24012619984051000", }, Statuses: []Status{ { Contributors: nil, Coordinates: nil, CreatedAt: "Mon Sep 24 03:35:21 +0000 2012", Entities: Entities{ Hashtags: []Hashtag{{ Indices: []int{20, 34}, Text: "freebandnames"}, }, Urls: []*string{}, UserMentions: []*string{}, }, Favorited: false, Geo: nil, ID: 250075927172759552, IDStr: "250075927172759552", InReplyToScreenName: nil, InReplyToStatusID: nil, InReplyToStatusIDStr: nil, InReplyToUserID: nil, InReplyToUserIDStr: nil, Metadata: StatusMetadata{ IsoLanguageCode: "en", ResultType: "recent", }, Place: nil, RetweetCount: 0, Retweeted: false, Source: "Twitter for Mac", Text: "Aggressive Ponytail #freebandnames", Truncated: false, User: User{ ContributorsEnabled: false, CreatedAt: "Mon Apr 26 06:01:55 +0000 2010", DefaultProfile: true, DefaultProfileImage: false, Description: "Born 330 Live 310", Entities: UserEntities{ Description: UserEntityDescription{ Urls: []*string{}, }, URL: UserEntityURL{ Urls: []URL{{ ExpandedURL: nil, Indices: []int{0, 0}, URL: "", }}, }, }, FavouritesCount: 0, FollowRequestSent: nil, FollowersCount: 70, Following: nil, FriendsCount: 110, GeoEnabled: true, ID: 137238150, IDStr: "137238150", IsTranslator: false, Lang: "en", ListedCount: 2, Location: "LA, CA", Name: "Sean Cummings", Notifications: nil, ProfileBackgroundColor: "C0DEED", ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme1/bg.png", ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme1/bg.png", ProfileBackgroundTile: false, ProfileImageURL: "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", ProfileLinkColor: "0084B4", ProfileSidebarBorderColor: "C0DEED", ProfileSidebarFillColor: "DDEEF6", ProfileTextColor: "333333", ProfileUseBackgroundImage: true, Protected: false, ScreenName: "sean_cummings", ShowAllInlineMedia: false, StatusesCount: 579, TimeZone: "Pacific Time (US & Canada)", URL: nil, UtcOffset: -28800, Verified: false, }, }, { Contributors: nil, Coordinates: nil, CreatedAt: "Fri Sep 21 23:40:54 +0000 2012", Entities: Entities{ Hashtags: []Hashtag{{ Indices: []int{20, 34}, Text: "FreeBandNames", }}, Urls: []*string{}, UserMentions: []*string{}, }, Favorited: false, Geo: nil, ID: 249292149810667520, IDStr: "249292149810667520", InReplyToScreenName: nil, InReplyToStatusID: nil, InReplyToStatusIDStr: nil, InReplyToUserID: nil, InReplyToUserIDStr: nil, Metadata: StatusMetadata{ IsoLanguageCode: "pl", ResultType: "recent", }, Place: nil, RetweetCount: 0, Retweeted: false, Source: "web", Text: "Thee Namaste Nerdz. #FreeBandNames", Truncated: false, User: User{ ContributorsEnabled: false, CreatedAt: "Tue Apr 07 19:05:07 +0000 2009", DefaultProfile: false, DefaultProfileImage: false, Description: "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", Entities: UserEntities{ Description: UserEntityDescription{Urls: []*string{}}, URL: UserEntityURL{ Urls: []URL{{ ExpandedURL: nil, Indices: []int{0, 32}, URL: "http://bullcityrecords.com/wnng/"}}, }, }, FavouritesCount: 8, FollowRequestSent: nil, FollowersCount: 2052, Following: nil, FriendsCount: 348, GeoEnabled: false, ID: 29516238, IDStr: "29516238", IsTranslator: false, Lang: "en", ListedCount: 118, Location: "Durham, NC", Name: "Chaz Martenstein", Notifications: nil, ProfileBackgroundColor: "9AE4E8", ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", ProfileBackgroundTile: true, ProfileImageURL: "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", ProfileLinkColor: "0084B4", ProfileSidebarBorderColor: "BDDCAD", ProfileSidebarFillColor: "DDFFCC", ProfileTextColor: "333333", ProfileUseBackgroundImage: true, Protected: false, ScreenName: "bullcityrecords", ShowAllInlineMedia: true, StatusesCount: 7579, TimeZone: "Eastern Time (US & Canada)", URL: nil, UtcOffset: -18000, Verified: false, }, }, { Contributors: nil, Coordinates: nil, CreatedAt: "Fri Sep 21 23:30:20 +0000 2012", Entities: Entities{ Hashtags: []Hashtag{{ Indices: []int{29, 43}, Text: "freebandnames", }}, Urls: []*string{}, UserMentions: []*string{}, }, Favorited: false, Geo: nil, ID: 249289491129438208, IDStr: "249289491129438208", InReplyToScreenName: nil, InReplyToStatusID: nil, InReplyToStatusIDStr: nil, InReplyToUserID: nil, InReplyToUserIDStr: nil, Metadata: StatusMetadata{ IsoLanguageCode: "en", ResultType: "recent", }, Place: nil, RetweetCount: 0, Retweeted: false, Source: "web", Text: "Mexican Heaven, Mexican Hell #freebandnames", Truncated: false, User: User{ ContributorsEnabled: false, CreatedAt: "Tue Sep 01 21:21:35 +0000 2009", DefaultProfile: false, DefaultProfileImage: false, Description: "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", Entities: UserEntities{ Description: UserEntityDescription{ Urls: nil, }, URL: UserEntityURL{ Urls: []URL{{ ExpandedURL: nil, Indices: []int{0, 0}, URL: "", }}, }, }, FavouritesCount: 19, FollowRequestSent: nil, FollowersCount: 63, Following: nil, FriendsCount: 63, GeoEnabled: false, ID: 70789458, IDStr: "70789458", IsTranslator: false, Lang: "en", ListedCount: 1, Location: "Kingston New York", Name: "Thomas John Wakeman", Notifications: nil, ProfileBackgroundColor: "352726", ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme5/bg.gif", ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme5/bg.gif", ProfileBackgroundTile: false, ProfileImageURL: "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", ProfileLinkColor: "D02B55", ProfileSidebarBorderColor: "829D5E", ProfileSidebarFillColor: "99CC33", ProfileTextColor: "3E4415", ProfileUseBackgroundImage: true, Protected: false, ScreenName: "MonkiesFist", ShowAllInlineMedia: false, StatusesCount: 1048, TimeZone: "Eastern Time (US & Canada)", URL: nil, UtcOffset: -18000, Verified: false, }, }, { Contributors: nil, Coordinates: nil, CreatedAt: "Fri Sep 21 22:51:18 +0000 2012", Entities: Entities{ Hashtags: []Hashtag{{ Indices: []int{20, 34}, Text: "freebandnames", }}, Urls: []*string{}, UserMentions: []*string{}, }, Favorited: false, Geo: nil, ID: 249279667666817024, IDStr: "249279667666817024", InReplyToScreenName: nil, InReplyToStatusID: nil, InReplyToStatusIDStr: nil, InReplyToUserID: nil, InReplyToUserIDStr: nil, Metadata: StatusMetadata{ IsoLanguageCode: "en", ResultType: "recent", }, Place: nil, RetweetCount: 0, Retweeted: false, Source: "Twitter for iPhone", Text: "The Foolish Mortals #freebandnames", Truncated: false, User: User{ ContributorsEnabled: false, CreatedAt: "Mon May 04 00:05:00 +0000 2009", DefaultProfile: false, DefaultProfileImage: false, Description: "Cartoonist, Illustrator, and T-Shirt connoisseur", Entities: UserEntities{ Description: UserEntityDescription{ Urls: []*string{}, }, URL: UserEntityURL{ Urls: []URL{{ ExpandedURL: nil, Indices: []int{0, 24}, URL: "http://www.omnitarian.me", }}, }, }, FavouritesCount: 647, FollowRequestSent: nil, FollowersCount: 608, Following: nil, FriendsCount: 249, GeoEnabled: false, ID: 37539828, IDStr: "37539828", IsTranslator: false, Lang: "en", ListedCount: 52, Location: "Wisconsin, USA", Name: "Marty Elmer", Notifications: nil, ProfileBackgroundColor: "EEE3C4", ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", ProfileBackgroundTile: true, ProfileImageURL: "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", ProfileLinkColor: "3B2A26", ProfileSidebarBorderColor: "615A44", ProfileSidebarFillColor: "BFAC83", ProfileTextColor: "000000", ProfileUseBackgroundImage: true, Protected: false, ScreenName: "Omnitarian", ShowAllInlineMedia: true, StatusesCount: 3575, TimeZone: "Central Time (US & Canada)", URL: nil, UtcOffset: -21600, Verified: false, }, }, }, } easyjson-0.7.6/benchmark/default_test.go000066400000000000000000000042051371475264500203420ustar00rootroot00000000000000// +build !use_easyjson,!use_ffjson,!use_codec,!use_jsoniter package benchmark import ( "encoding/json" "testing" ) func BenchmarkStd_Unmarshal_M(b *testing.B) { b.SetBytes(int64(len(largeStructText))) for i := 0; i < b.N; i++ { var s LargeStruct err := json.Unmarshal(largeStructText, &s) if err != nil { b.Error(err) } } } func BenchmarkStd_Unmarshal_S(b *testing.B) { for i := 0; i < b.N; i++ { var s Entities err := json.Unmarshal(smallStructText, &s) if err != nil { b.Error(err) } } b.SetBytes(int64(len(smallStructText))) } func BenchmarkStd_Marshal_M(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := json.Marshal(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkStd_Marshal_L(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := json.Marshal(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkStd_Marshal_M_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := json.Marshal(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkStd_Marshal_L_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := json.Marshal(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkStd_Marshal_S(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := json.Marshal(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkStd_Marshal_S_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := json.Marshal(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkStd_Marshal_M_ToWriter(b *testing.B) { enc := json.NewEncoder(&DummyWriter{}) for i := 0; i < b.N; i++ { err := enc.Encode(&largeStructData) if err != nil { b.Error(err) } } } easyjson-0.7.6/benchmark/dummy_test.go000066400000000000000000000003101371475264500200420ustar00rootroot00000000000000package benchmark import ( "testing" ) type DummyWriter struct{} func (w DummyWriter) Write(data []byte) (int, error) { return len(data), nil } func TestToSuppressNoTestsWarning(t *testing.T) {} easyjson-0.7.6/benchmark/easyjson_test.go000066400000000000000000000062501371475264500205530ustar00rootroot00000000000000// +build use_easyjson package benchmark import ( "testing" "github.com/mailru/easyjson" "github.com/mailru/easyjson/jwriter" ) func BenchmarkEJ_Unmarshal_M(b *testing.B) { b.SetBytes(int64(len(largeStructText))) for i := 0; i < b.N; i++ { var s LargeStruct err := s.UnmarshalJSON(largeStructText) if err != nil { b.Error(err) } } } func BenchmarkEJ_Unmarshal_S(b *testing.B) { b.SetBytes(int64(len(smallStructText))) for i := 0; i < b.N; i++ { var s Entities err := s.UnmarshalJSON(smallStructText) if err != nil { b.Error(err) } } } func BenchmarkEJ_Marshal_M(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := easyjson.Marshal(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkEJ_Marshal_L(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := easyjson.Marshal(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkEJ_Marshal_L_ToWriter(b *testing.B) { var l int64 out := &DummyWriter{} for i := 0; i < b.N; i++ { w := jwriter.Writer{} xlStructData.MarshalEasyJSON(&w) if w.Error != nil { b.Error(w.Error) } l = int64(w.Size()) w.DumpTo(out) } b.SetBytes(l) } func BenchmarkEJ_Marshal_M_Parallel(b *testing.B) { b.SetBytes(int64(len(largeStructText))) b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := largeStructData.MarshalJSON() if err != nil { b.Error(err) } } }) } func BenchmarkEJ_Marshal_M_ToWriter(b *testing.B) { var l int64 out := &DummyWriter{} for i := 0; i < b.N; i++ { w := jwriter.Writer{} largeStructData.MarshalEasyJSON(&w) if w.Error != nil { b.Error(w.Error) } l = int64(w.Size()) w.DumpTo(out) } b.SetBytes(l) } func BenchmarkEJ_Marshal_M_ToWriter_Parallel(b *testing.B) { out := &DummyWriter{} b.RunParallel(func(pb *testing.PB) { var l int64 for pb.Next() { w := jwriter.Writer{} largeStructData.MarshalEasyJSON(&w) if w.Error != nil { b.Error(w.Error) } l = int64(w.Size()) w.DumpTo(out) } if l > 0 { b.SetBytes(l) } }) } func BenchmarkEJ_Marshal_L_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := xlStructData.MarshalJSON() if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkEJ_Marshal_L_ToWriter_Parallel(b *testing.B) { out := &DummyWriter{} b.RunParallel(func(pb *testing.PB) { var l int64 for pb.Next() { w := jwriter.Writer{} xlStructData.MarshalEasyJSON(&w) if w.Error != nil { b.Error(w.Error) } l = int64(w.Size()) w.DumpTo(out) } if l > 0 { b.SetBytes(l) } }) } func BenchmarkEJ_Marshal_S(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := smallStructData.MarshalJSON() if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkEJ_Marshal_S_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := smallStructData.MarshalJSON() if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } easyjson-0.7.6/benchmark/example.json000066400000000000000000000313401371475264500176560ustar00rootroot00000000000000{ "statuses": [ { "coordinates": null, "favorited": false, "truncated": false, "created_at": "Mon Sep 24 03:35:21 +0000 2012", "id_str": "250075927172759552", "entities": { "urls": [ ], "hashtags": [ { "text": "freebandnames", "indices": [ 20, 34 ] } ], "user_mentions": [ ] }, "in_reply_to_user_id_str": null, "contributors": null, "text": "Aggressive Ponytail #freebandnames", "metadata": { "iso_language_code": "en", "result_type": "recent" }, "retweet_count": 0, "in_reply_to_status_id_str": null, "id": 250075927172759552, "geo": null, "retweeted": false, "in_reply_to_user_id": null, "place": null, "user": { "profile_sidebar_fill_color": "DDEEF6", "profile_sidebar_border_color": "C0DEED", "profile_background_tile": false, "name": "Sean Cummings", "profile_image_url": "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", "created_at": "Mon Apr 26 06:01:55 +0000 2010", "location": "LA, CA", "follow_request_sent": null, "profile_link_color": "0084B4", "is_translator": false, "id_str": "137238150", "entities": { "url": { "urls": [ { "expanded_url": null, "url": "", "indices": [ 0, 0 ] } ] }, "description": { "urls": [ ] } }, "default_profile": true, "contributors_enabled": false, "favourites_count": 0, "url": null, "profile_image_url_https": "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", "utc_offset": -28800, "id": 137238150, "profile_use_background_image": true, "listed_count": 2, "profile_text_color": "333333", "lang": "en", "followers_count": 70, "protected": false, "notifications": null, "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png", "profile_background_color": "C0DEED", "verified": false, "geo_enabled": true, "time_zone": "Pacific Time (US & Canada)", "description": "Born 330 Live 310", "default_profile_image": false, "profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png", "statuses_count": 579, "friends_count": 110, "following": null, "show_all_inline_media": false, "screen_name": "sean_cummings" }, "in_reply_to_screen_name": null, "source": "Twitter for Mac", "in_reply_to_status_id": null }, { "coordinates": null, "favorited": false, "truncated": false, "created_at": "Fri Sep 21 23:40:54 +0000 2012", "id_str": "249292149810667520", "entities": { "urls": [ ], "hashtags": [ { "text": "FreeBandNames", "indices": [ 20, 34 ] } ], "user_mentions": [ ] }, "in_reply_to_user_id_str": null, "contributors": null, "text": "Thee Namaste Nerdz. #FreeBandNames", "metadata": { "iso_language_code": "pl", "result_type": "recent" }, "retweet_count": 0, "in_reply_to_status_id_str": null, "id": 249292149810667520, "geo": null, "retweeted": false, "in_reply_to_user_id": null, "place": null, "user": { "profile_sidebar_fill_color": "DDFFCC", "profile_sidebar_border_color": "BDDCAD", "profile_background_tile": true, "name": "Chaz Martenstein", "profile_image_url": "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", "created_at": "Tue Apr 07 19:05:07 +0000 2009", "location": "Durham, NC", "follow_request_sent": null, "profile_link_color": "0084B4", "is_translator": false, "id_str": "29516238", "entities": { "url": { "urls": [ { "expanded_url": null, "url": "http://bullcityrecords.com/wnng/", "indices": [ 0, 32 ] } ] }, "description": { "urls": [ ] } }, "default_profile": false, "contributors_enabled": false, "favourites_count": 8, "url": "http://bullcityrecords.com/wnng/", "profile_image_url_https": "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", "utc_offset": -18000, "id": 29516238, "profile_use_background_image": true, "listed_count": 118, "profile_text_color": "333333", "lang": "en", "followers_count": 2052, "protected": false, "notifications": null, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", "profile_background_color": "9AE4E8", "verified": false, "geo_enabled": false, "time_zone": "Eastern Time (US & Canada)", "description": "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", "default_profile_image": false, "profile_background_image_url": "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", "statuses_count": 7579, "friends_count": 348, "following": null, "show_all_inline_media": true, "screen_name": "bullcityrecords" }, "in_reply_to_screen_name": null, "source": "web", "in_reply_to_status_id": null }, { "coordinates": null, "favorited": false, "truncated": false, "created_at": "Fri Sep 21 23:30:20 +0000 2012", "id_str": "249289491129438208", "entities": { "urls": [ ], "hashtags": [ { "text": "freebandnames", "indices": [ 29, 43 ] } ], "user_mentions": [ ] }, "in_reply_to_user_id_str": null, "contributors": null, "text": "Mexican Heaven, Mexican Hell #freebandnames", "metadata": { "iso_language_code": "en", "result_type": "recent" }, "retweet_count": 0, "in_reply_to_status_id_str": null, "id": 249289491129438208, "geo": null, "retweeted": false, "in_reply_to_user_id": null, "place": null, "user": { "profile_sidebar_fill_color": "99CC33", "profile_sidebar_border_color": "829D5E", "profile_background_tile": false, "name": "Thomas John Wakeman", "profile_image_url": "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", "created_at": "Tue Sep 01 21:21:35 +0000 2009", "location": "Kingston New York", "follow_request_sent": null, "profile_link_color": "D02B55", "is_translator": false, "id_str": "70789458", "entities": { "url": { "urls": [ { "expanded_url": null, "url": "", "indices": [ 0, 0 ] } ] }, "description": { "urls": [ ] } }, "default_profile": false, "contributors_enabled": false, "favourites_count": 19, "url": null, "profile_image_url_https": "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", "utc_offset": -18000, "id": 70789458, "profile_use_background_image": true, "listed_count": 1, "profile_text_color": "3E4415", "lang": "en", "followers_count": 63, "protected": false, "notifications": null, "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme5/bg.gif", "profile_background_color": "352726", "verified": false, "geo_enabled": false, "time_zone": "Eastern Time (US & Canada)", "description": "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", "default_profile_image": false, "profile_background_image_url": "http://a0.twimg.com/images/themes/theme5/bg.gif", "statuses_count": 1048, "friends_count": 63, "following": null, "show_all_inline_media": false, "screen_name": "MonkiesFist" }, "in_reply_to_screen_name": null, "source": "web", "in_reply_to_status_id": null }, { "coordinates": null, "favorited": false, "truncated": false, "created_at": "Fri Sep 21 22:51:18 +0000 2012", "id_str": "249279667666817024", "entities": { "urls": [ ], "hashtags": [ { "text": "freebandnames", "indices": [ 20, 34 ] } ], "user_mentions": [ ] }, "in_reply_to_user_id_str": null, "contributors": null, "text": "The Foolish Mortals #freebandnames", "metadata": { "iso_language_code": "en", "result_type": "recent" }, "retweet_count": 0, "in_reply_to_status_id_str": null, "id": 249279667666817024, "geo": null, "retweeted": false, "in_reply_to_user_id": null, "place": null, "user": { "profile_sidebar_fill_color": "BFAC83", "profile_sidebar_border_color": "615A44", "profile_background_tile": true, "name": "Marty Elmer", "profile_image_url": "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", "created_at": "Mon May 04 00:05:00 +0000 2009", "location": "Wisconsin, USA", "follow_request_sent": null, "profile_link_color": "3B2A26", "is_translator": false, "id_str": "37539828", "entities": { "url": { "urls": [ { "expanded_url": null, "url": "http://www.omnitarian.me", "indices": [ 0, 24 ] } ] }, "description": { "urls": [ ] } }, "default_profile": false, "contributors_enabled": false, "favourites_count": 647, "url": "http://www.omnitarian.me", "profile_image_url_https": "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", "utc_offset": -21600, "id": 37539828, "profile_use_background_image": true, "listed_count": 52, "profile_text_color": "000000", "lang": "en", "followers_count": 608, "protected": false, "notifications": null, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", "profile_background_color": "EEE3C4", "verified": false, "geo_enabled": false, "time_zone": "Central Time (US & Canada)", "description": "Cartoonist, Illustrator, and T-Shirt connoisseur", "default_profile_image": false, "profile_background_image_url": "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", "statuses_count": 3575, "friends_count": 249, "following": null, "show_all_inline_media": true, "screen_name": "Omnitarian" }, "in_reply_to_screen_name": null, "source": "Twitter for iPhone", "in_reply_to_status_id": null } ], "search_metadata": { "max_id": 250126199840518145, "since_id": 24012619984051000, "refresh_url": "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", "next_results": "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", "count": 4, "completed_in": 0.035, "since_id_str": "24012619984051000", "query": "%23freebandnames", "max_id_str": "250126199840518145" } } easyjson-0.7.6/benchmark/ffjson_test.go000066400000000000000000000067421371475264500202130ustar00rootroot00000000000000// +build use_ffjson package benchmark import ( "testing" "github.com/pquerna/ffjson/ffjson" ) func BenchmarkFF_Unmarshal_M(b *testing.B) { b.SetBytes(int64(len(largeStructText))) for i := 0; i < b.N; i++ { var s LargeStruct err := ffjson.UnmarshalFast(largeStructText, &s) if err != nil { b.Error(err) } } } func BenchmarkFF_Unmarshal_S(b *testing.B) { for i := 0; i < b.N; i++ { var s Entities err := ffjson.UnmarshalFast(smallStructText, &s) if err != nil { b.Error(err) } } b.SetBytes(int64(len(smallStructText))) } func BenchmarkFF_Marshal_M(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkFF_Marshal_S(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkFF_Marshal_M_Pool(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } b.SetBytes(l) } func BenchmarkFF_Marshal_L(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkFF_Marshal_L_Pool(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } b.SetBytes(l) } func BenchmarkFF_Marshal_L_Pool_Parallel(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } b.SetBytes(l) } func BenchmarkFF_Marshal_M_Pool_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := ffjson.MarshalFast(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } }) b.SetBytes(l) } func BenchmarkFF_Marshal_S_Pool(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := ffjson.MarshalFast(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } b.SetBytes(l) } func BenchmarkFF_Marshal_S_Pool_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := ffjson.MarshalFast(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) ffjson.Pool(data) } }) b.SetBytes(l) } func BenchmarkFF_Marshal_S_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := ffjson.MarshalFast(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkFF_Marshal_M_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := ffjson.MarshalFast(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkFF_Marshal_L_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := ffjson.MarshalFast(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } easyjson-0.7.6/benchmark/go.mod000066400000000000000000000006041371475264500164350ustar00rootroot00000000000000module github.com/mailru/easyjson/benchmark go 1.12 require ( github.com/json-iterator/go v1.1.7 github.com/mailru/easyjson v0.0.0 github.com/pquerna/ffjson v0.0.0-20190813045741-dac163c6c0a9 github.com/ugorji/go/codec v1.1.7 github.com/ugorji/go/codec/codecgen v1.1.7 golang.org/x/tools v0.0.0-20190829051458-42f498d34c4d // indirect ) replace github.com/mailru/easyjson => ../ easyjson-0.7.6/benchmark/go.sum000066400000000000000000000061521371475264500164660ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pquerna/ffjson v0.0.0-20190813045741-dac163c6c0a9 h1:kyf9snWXHvQc+yxE9imhdI8YAm4oKeZISlaAR+x73zs= github.com/pquerna/ffjson v0.0.0-20190813045741-dac163c6c0a9/go.mod h1:YARuvh7BUWHNhzDq2OM5tzR2RiCcN2D7sapiKyCel/M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ugorji/go/codec/codecgen v1.1.7 h1:6BU4y9NIgvVMNetSGxkH9lOOa2UB5b8sCHC6+8m5lVc= github.com/ugorji/go/codec/codecgen v1.1.7/go.mod h1:FMgcDIjFRtjQPUVM3GN592ic8epl2qsvfNPhezMgP8Y= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20190829051458-42f498d34c4d h1:yqT69RdmShXXRtsT9jS6Iy0FFLWGLCe3IqGE0vsP0m4= golang.org/x/tools v0.0.0-20190829051458-42f498d34c4d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= easyjson-0.7.6/benchmark/jsoniter_test.go000066400000000000000000000042221371475264500205520ustar00rootroot00000000000000// +build use_jsoniter package benchmark import ( "testing" jsoniter "github.com/json-iterator/go" ) func BenchmarkJI_Unmarshal_M(b *testing.B) { b.SetBytes(int64(len(largeStructText))) for i := 0; i < b.N; i++ { var s LargeStruct err := jsoniter.Unmarshal(largeStructText, &s) if err != nil { b.Error(err) } } } func BenchmarkJI_Unmarshal_S(b *testing.B) { for i := 0; i < b.N; i++ { var s Entities err := jsoniter.Unmarshal(smallStructText, &s) if err != nil { b.Error(err) } } b.SetBytes(int64(len(smallStructText))) } func BenchmarkJI_Marshal_M(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := jsoniter.Marshal(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkJI_Marshal_L(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := jsoniter.Marshal(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkJI_Marshal_M_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := jsoniter.Marshal(&largeStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkJI_Marshal_L_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := jsoniter.Marshal(&xlStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkJI_Marshal_S(b *testing.B) { var l int64 for i := 0; i < b.N; i++ { data, err := jsoniter.Marshal(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } b.SetBytes(l) } func BenchmarkJI_Marshal_S_Parallel(b *testing.B) { var l int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { data, err := jsoniter.Marshal(&smallStructData) if err != nil { b.Error(err) } l = int64(len(data)) } }) b.SetBytes(l) } func BenchmarkJI_Marshal_M_ToWriter(b *testing.B) { enc := jsoniter.NewEncoder(&DummyWriter{}) for i := 0; i < b.N; i++ { err := enc.Encode(&largeStructData) if err != nil { b.Error(err) } } } easyjson-0.7.6/benchmark/tools.go000066400000000000000000000004121371475264500170130ustar00rootroot00000000000000//+build tools // Package tools tracks dependencies on binaries not otherwise referenced in the codebase. // https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module package tools import ( _ "github.com/ugorji/go/codec/codecgen" ) easyjson-0.7.6/benchmark/ujson.sh000077500000000000000000000005171371475264500170270ustar00rootroot00000000000000#/bin/bash echo -n "Python ujson module, DECODE: " python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read()" 'ujson.loads(data)' echo -n "Python ujson module, ENCODE: " python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read(); obj = ujson.loads(data)" 'ujson.dumps(obj)' easyjson-0.7.6/bootstrap/000077500000000000000000000000001371475264500154125ustar00rootroot00000000000000easyjson-0.7.6/bootstrap/bootstrap.go000066400000000000000000000123731371475264500177640ustar00rootroot00000000000000// Package bootstrap implements the bootstrapping logic: generation of a .go file to // launch the actual generator and launching the generator itself. // // The package may be preferred to a command-line utility if generating the serializers // from golang code is required. package bootstrap import ( "fmt" "go/format" "io/ioutil" "os" "os/exec" "path/filepath" "regexp" "sort" ) const genPackage = "github.com/mailru/easyjson/gen" const pkgWriter = "github.com/mailru/easyjson/jwriter" const pkgLexer = "github.com/mailru/easyjson/jlexer" var buildFlagsRegexp = regexp.MustCompile("'.+'|\".+\"|\\S+") type Generator struct { PkgPath, PkgName string Types []string NoStdMarshalers bool SnakeCase bool LowerCamelCase bool OmitEmpty bool DisallowUnknownFields bool SkipMemberNameUnescaping bool OutName string BuildTags string GenBuildFlags string StubsOnly bool LeaveTemps bool NoFormat bool SimpleBytes bool } // writeStub outputs an initial stub for marshalers/unmarshalers so that the package // using marshalers/unmarshales compiles correctly for boostrapping code. func (g *Generator) writeStub() error { f, err := os.Create(g.OutName) if err != nil { return err } defer f.Close() if g.BuildTags != "" { fmt.Fprintln(f, "// +build ", g.BuildTags) fmt.Fprintln(f) } fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson stub code to make the package") fmt.Fprintln(f, "// compilable during generation.") fmt.Fprintln(f) fmt.Fprintln(f, "package ", g.PkgName) if len(g.Types) > 0 { fmt.Fprintln(f) fmt.Fprintln(f, "import (") fmt.Fprintln(f, ` "`+pkgWriter+`"`) fmt.Fprintln(f, ` "`+pkgLexer+`"`) fmt.Fprintln(f, ")") } sort.Strings(g.Types) for _, t := range g.Types { fmt.Fprintln(f) if !g.NoStdMarshalers { fmt.Fprintln(f, "func (", t, ") MarshalJSON() ([]byte, error) { return nil, nil }") fmt.Fprintln(f, "func (*", t, ") UnmarshalJSON([]byte) error { return nil }") } fmt.Fprintln(f, "func (", t, ") MarshalEasyJSON(w *jwriter.Writer) {}") fmt.Fprintln(f, "func (*", t, ") UnmarshalEasyJSON(l *jlexer.Lexer) {}") fmt.Fprintln(f) fmt.Fprintln(f, "type EasyJSON_exporter_"+t+" *"+t) } return nil } // writeMain creates a .go file that launches the generator if 'go run'. func (g *Generator) writeMain() (path string, err error) { f, err := ioutil.TempFile(filepath.Dir(g.OutName), "easyjson-bootstrap") if err != nil { return "", err } fmt.Fprintln(f, "// +build ignore") fmt.Fprintln(f) fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch") fmt.Fprintln(f, "// the actual generator.") fmt.Fprintln(f) fmt.Fprintln(f, "package main") fmt.Fprintln(f) fmt.Fprintln(f, "import (") fmt.Fprintln(f, ` "fmt"`) fmt.Fprintln(f, ` "os"`) fmt.Fprintln(f) fmt.Fprintf(f, " %q\n", genPackage) if len(g.Types) > 0 { fmt.Fprintln(f) fmt.Fprintf(f, " pkg %q\n", g.PkgPath) } fmt.Fprintln(f, ")") fmt.Fprintln(f) fmt.Fprintln(f, "func main() {") fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName)) fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath) if g.BuildTags != "" { fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags) } if g.SnakeCase { fmt.Fprintln(f, " g.UseSnakeCase()") } if g.LowerCamelCase { fmt.Fprintln(f, " g.UseLowerCamelCase()") } if g.OmitEmpty { fmt.Fprintln(f, " g.OmitEmpty()") } if g.NoStdMarshalers { fmt.Fprintln(f, " g.NoStdMarshalers()") } if g.DisallowUnknownFields { fmt.Fprintln(f, " g.DisallowUnknownFields()") } if g.SimpleBytes { fmt.Fprintln(f, " g.SimpleBytes()") } if g.SkipMemberNameUnescaping { fmt.Fprintln(f, " g.SkipMemberNameUnescaping()") } sort.Strings(g.Types) for _, v := range g.Types { fmt.Fprintln(f, " g.Add(pkg.EasyJSON_exporter_"+v+"(nil))") } fmt.Fprintln(f, " if err := g.Run(os.Stdout); err != nil {") fmt.Fprintln(f, " fmt.Fprintln(os.Stderr, err)") fmt.Fprintln(f, " os.Exit(1)") fmt.Fprintln(f, " }") fmt.Fprintln(f, "}") src := f.Name() if err := f.Close(); err != nil { return src, err } dest := src + ".go" return dest, os.Rename(src, dest) } func (g *Generator) Run() error { if err := g.writeStub(); err != nil { return err } if g.StubsOnly { return nil } path, err := g.writeMain() if err != nil { return err } if !g.LeaveTemps { defer os.Remove(path) } f, err := os.Create(g.OutName + ".tmp") if err != nil { return err } if !g.LeaveTemps { defer os.Remove(f.Name()) // will not remove after rename } execArgs := []string{"run"} if g.GenBuildFlags != "" { buildFlags := buildFlagsRegexp.FindAllString(g.GenBuildFlags, -1) execArgs = append(execArgs, buildFlags...) } execArgs = append(execArgs, "-tags", g.BuildTags, filepath.Base(path)) cmd := exec.Command("go", execArgs...) cmd.Stdout = f cmd.Stderr = os.Stderr cmd.Dir = filepath.Dir(path) if err = cmd.Run(); err != nil { return err } f.Close() // move unformatted file to out path if g.NoFormat { return os.Rename(f.Name(), g.OutName) } // format file and write to out path in, err := ioutil.ReadFile(f.Name()) if err != nil { return err } out, err := format.Source(in) if err != nil { return err } return ioutil.WriteFile(g.OutName, out, 0644) } easyjson-0.7.6/buffer/000077500000000000000000000000001371475264500146465ustar00rootroot00000000000000easyjson-0.7.6/buffer/pool.go000066400000000000000000000131071371475264500161500ustar00rootroot00000000000000// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to // reduce copying and to allow reuse of individual chunks. package buffer import ( "io" "net" "sync" ) // PoolConfig contains configuration for the allocation and reuse strategy. type PoolConfig struct { StartSize int // Minimum chunk size that is allocated. PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. MaxSize int // Maximum chunk size that will be allocated. } var config = PoolConfig{ StartSize: 128, PooledSize: 512, MaxSize: 32768, } // Reuse pool: chunk size -> pool. var buffers = map[int]*sync.Pool{} func initBuffers() { for l := config.PooledSize; l <= config.MaxSize; l *= 2 { buffers[l] = new(sync.Pool) } } func init() { initBuffers() } // Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. func Init(cfg PoolConfig) { config = cfg initBuffers() } // putBuf puts a chunk to reuse pool if it can be reused. func putBuf(buf []byte) { size := cap(buf) if size < config.PooledSize { return } if c := buffers[size]; c != nil { c.Put(buf[:0]) } } // getBuf gets a chunk from reuse pool or creates a new one if reuse failed. func getBuf(size int) []byte { if size >= config.PooledSize { if c := buffers[size]; c != nil { v := c.Get() if v != nil { return v.([]byte) } } } return make([]byte, 0, size) } // Buffer is a buffer optimized for serialization without extra copying. type Buffer struct { // Buf is the current chunk that can be used for serialization. Buf []byte toPool []byte bufs [][]byte } // EnsureSpace makes sure that the current chunk contains at least s free bytes, // possibly creating a new chunk. func (b *Buffer) EnsureSpace(s int) { if cap(b.Buf)-len(b.Buf) < s { b.ensureSpaceSlow(s) } } func (b *Buffer) ensureSpaceSlow(s int) { l := len(b.Buf) if l > 0 { if cap(b.toPool) != cap(b.Buf) { // Chunk was reallocated, toPool can be pooled. putBuf(b.toPool) } if cap(b.bufs) == 0 { b.bufs = make([][]byte, 0, 8) } b.bufs = append(b.bufs, b.Buf) l = cap(b.toPool) * 2 } else { l = config.StartSize } if l > config.MaxSize { l = config.MaxSize } b.Buf = getBuf(l) b.toPool = b.Buf } // AppendByte appends a single byte to buffer. func (b *Buffer) AppendByte(data byte) { b.EnsureSpace(1) b.Buf = append(b.Buf, data) } // AppendBytes appends a byte slice to buffer. func (b *Buffer) AppendBytes(data []byte) { if len(data) <= cap(b.Buf)-len(b.Buf) { b.Buf = append(b.Buf, data...) // fast path } else { b.appendBytesSlow(data) } } func (b *Buffer) appendBytesSlow(data []byte) { for len(data) > 0 { b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) { sz = len(data) } b.Buf = append(b.Buf, data[:sz]...) data = data[sz:] } } // AppendString appends a string to buffer. func (b *Buffer) AppendString(data string) { if len(data) <= cap(b.Buf)-len(b.Buf) { b.Buf = append(b.Buf, data...) // fast path } else { b.appendStringSlow(data) } } func (b *Buffer) appendStringSlow(data string) { for len(data) > 0 { b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) { sz = len(data) } b.Buf = append(b.Buf, data[:sz]...) data = data[sz:] } } // Size computes the size of a buffer by adding sizes of every chunk. func (b *Buffer) Size() int { size := len(b.Buf) for _, buf := range b.bufs { size += len(buf) } return size } // DumpTo outputs the contents of a buffer to a writer and resets the buffer. func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { bufs := net.Buffers(b.bufs) if len(b.Buf) > 0 { bufs = append(bufs, b.Buf) } n, err := bufs.WriteTo(w) for _, buf := range b.bufs { putBuf(buf) } putBuf(b.toPool) b.bufs = nil b.Buf = nil b.toPool = nil return int(n), err } // BuildBytes creates a single byte slice with all the contents of the buffer. Data is // copied if it does not fit in a single chunk. You can optionally provide one byte // slice as argument that it will try to reuse. func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { if len(b.bufs) == 0 { ret := b.Buf b.toPool = nil b.Buf = nil return ret } var ret []byte size := b.Size() // If we got a buffer as argument and it is big enough, reuse it. if len(reuse) == 1 && cap(reuse[0]) >= size { ret = reuse[0][:0] } else { ret = make([]byte, 0, size) } for _, buf := range b.bufs { ret = append(ret, buf...) putBuf(buf) } ret = append(ret, b.Buf...) putBuf(b.toPool) b.bufs = nil b.toPool = nil b.Buf = nil return ret } type readCloser struct { offset int bufs [][]byte } func (r *readCloser) Read(p []byte) (n int, err error) { for _, buf := range r.bufs { // Copy as much as we can. x := copy(p[n:], buf[r.offset:]) n += x // Increment how much we filled. // Did we empty the whole buffer? if r.offset+x == len(buf) { // On to the next buffer. r.offset = 0 r.bufs = r.bufs[1:] // We can release this buffer. putBuf(buf) } else { r.offset += x } if n == len(p) { break } } // No buffers left or nothing read? if len(r.bufs) == 0 { err = io.EOF } return } func (r *readCloser) Close() error { // Release all remaining buffers. for _, buf := range r.bufs { putBuf(buf) } // In case Close gets called multiple times. r.bufs = nil return nil } // ReadCloser creates an io.ReadCloser with all the contents of the buffer. func (b *Buffer) ReadCloser() io.ReadCloser { ret := &readCloser{0, append(b.bufs, b.Buf)} b.bufs = nil b.toPool = nil b.Buf = nil return ret } easyjson-0.7.6/buffer/pool_test.go000066400000000000000000000035031371475264500172060ustar00rootroot00000000000000package buffer import ( "bytes" "testing" ) func TestAppendByte(t *testing.T) { var b Buffer var want []byte for i := 0; i < 1000; i++ { b.AppendByte(1) b.AppendByte(2) want = append(want, 1, 2) } got := b.BuildBytes() if !bytes.Equal(got, want) { t.Errorf("BuildBytes() = %v; want %v", got, want) } } func TestAppendBytes(t *testing.T) { var b Buffer var want []byte for i := 0; i < 1000; i++ { b.AppendBytes([]byte{1, 2}) want = append(want, 1, 2) } got := b.BuildBytes() if !bytes.Equal(got, want) { t.Errorf("BuildBytes() = %v; want %v", got, want) } } func TestAppendString(t *testing.T) { var b Buffer var want []byte s := "test" for i := 0; i < 1000; i++ { b.AppendString(s) want = append(want, s...) } got := b.BuildBytes() if !bytes.Equal(got, want) { t.Errorf("BuildBytes() = %v; want %v", got, want) } } func TestDumpTo(t *testing.T) { var b Buffer var want []byte s := "test" for i := 0; i < 1000; i++ { b.AppendBytes([]byte(s)) want = append(want, s...) } out := &bytes.Buffer{} n, err := b.DumpTo(out) if err != nil { t.Errorf("DumpTo() error: %v", err) } got := out.Bytes() if !bytes.Equal(got, want) { t.Errorf("DumpTo(): got %v; want %v", got, want) } if n != len(want) { t.Errorf("DumpTo() = %v; want %v", n, len(want)) } } func TestReadCloser(t *testing.T) { var b Buffer var want []byte s := "test" for i := 0; i < 1000; i++ { b.AppendBytes([]byte(s)) want = append(want, s...) } out := &bytes.Buffer{} rc := b.ReadCloser() n, err := out.ReadFrom(rc) if err != nil { t.Errorf("ReadCloser() error: %v", err) } rc.Close() // Will always return nil got := out.Bytes() if !bytes.Equal(got, want) { t.Errorf("DumpTo(): got %v; want %v", got, want) } if n != int64(len(want)) { t.Errorf("DumpTo() = %v; want %v", n, len(want)) } } easyjson-0.7.6/easyjson/000077500000000000000000000000001371475264500152305ustar00rootroot00000000000000easyjson-0.7.6/easyjson/main.go000066400000000000000000000075251371475264500165140ustar00rootroot00000000000000package main import ( "errors" "flag" "fmt" "os" "path/filepath" "strings" "github.com/mailru/easyjson/bootstrap" // Reference the gen package to be friendly to vendoring tools, // as it is an indirect dependency. // (The temporary bootstrapping code uses it.) _ "github.com/mailru/easyjson/gen" "github.com/mailru/easyjson/parser" ) var buildTags = flag.String("build_tags", "", "build tags to add to generated file") var genBuildFlags = flag.String("gen_build_flags", "", "build flags when running the generator while bootstrapping") var snakeCase = flag.Bool("snake_case", false, "use snake_case names instead of CamelCase by default") var lowerCamelCase = flag.Bool("lower_camel_case", false, "use lowerCamelCase names instead of CamelCase by default") var noStdMarshalers = flag.Bool("no_std_marshalers", false, "don't generate MarshalJSON/UnmarshalJSON funcs") var omitEmpty = flag.Bool("omit_empty", false, "omit empty fields by default") var allStructs = flag.Bool("all", false, "generate marshaler/unmarshalers for all structs in a file") var simpleBytes = flag.Bool("byte", false, "use simple bytes instead of Base64Bytes for slice of bytes") var leaveTemps = flag.Bool("leave_temps", false, "do not delete temporary files") var stubs = flag.Bool("stubs", false, "only generate stubs for marshaler/unmarshaler funcs") var noformat = flag.Bool("noformat", false, "do not run 'gofmt -w' on output file") var specifiedName = flag.String("output_filename", "", "specify the filename of the output") var processPkg = flag.Bool("pkg", false, "process the whole package instead of just the given file") var disallowUnknownFields = flag.Bool("disallow_unknown_fields", false, "return error if any unknown field in json appeared") var skipMemberNameUnescaping = flag.Bool("disable_members_unescape", false, "don't perform unescaping of member names to improve performance") func generate(fname string) (err error) { fInfo, err := os.Stat(fname) if err != nil { return err } p := parser.Parser{AllStructs: *allStructs} if err := p.Parse(fname, fInfo.IsDir()); err != nil { return fmt.Errorf("Error parsing %v: %v", fname, err) } var outName string if fInfo.IsDir() { outName = filepath.Join(fname, p.PkgName+"_easyjson.go") } else { if s := strings.TrimSuffix(fname, ".go"); s == fname { return errors.New("Filename must end in '.go'") } else { outName = s + "_easyjson.go" } } if *specifiedName != "" { outName = *specifiedName } var trimmedBuildTags string if *buildTags != "" { trimmedBuildTags = strings.TrimSpace(*buildTags) } var trimmedGenBuildFlags string if *genBuildFlags != "" { trimmedGenBuildFlags = strings.TrimSpace(*genBuildFlags) } g := bootstrap.Generator{ BuildTags: trimmedBuildTags, GenBuildFlags: trimmedGenBuildFlags, PkgPath: p.PkgPath, PkgName: p.PkgName, Types: p.StructNames, SnakeCase: *snakeCase, LowerCamelCase: *lowerCamelCase, NoStdMarshalers: *noStdMarshalers, DisallowUnknownFields: *disallowUnknownFields, SkipMemberNameUnescaping: *skipMemberNameUnescaping, OmitEmpty: *omitEmpty, LeaveTemps: *leaveTemps, OutName: outName, StubsOnly: *stubs, NoFormat: *noformat, SimpleBytes: *simpleBytes, } if err := g.Run(); err != nil { return fmt.Errorf("Bootstrap failed: %v", err) } return nil } func main() { flag.Parse() files := flag.Args() gofile := os.Getenv("GOFILE") if *processPkg { gofile = filepath.Dir(gofile) } if len(files) == 0 && gofile != "" { files = []string{gofile} } else if len(files) == 0 { flag.Usage() os.Exit(1) } for _, fname := range files { if err := generate(fname); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } } easyjson-0.7.6/gen/000077500000000000000000000000001371475264500141465ustar00rootroot00000000000000easyjson-0.7.6/gen/decoder.go000066400000000000000000000430311371475264500161030ustar00rootroot00000000000000package gen import ( "encoding" "encoding/json" "errors" "fmt" "reflect" "strings" "unicode" "github.com/mailru/easyjson" ) // Target this byte size for initial slice allocation to reduce garbage collection. const minSliceBytes = 64 func (g *Generator) getDecoderName(t reflect.Type) string { return g.functionName("decode", t) } var primitiveDecoders = map[reflect.Kind]string{ reflect.String: "in.String()", reflect.Bool: "in.Bool()", reflect.Int: "in.Int()", reflect.Int8: "in.Int8()", reflect.Int16: "in.Int16()", reflect.Int32: "in.Int32()", reflect.Int64: "in.Int64()", reflect.Uint: "in.Uint()", reflect.Uint8: "in.Uint8()", reflect.Uint16: "in.Uint16()", reflect.Uint32: "in.Uint32()", reflect.Uint64: "in.Uint64()", reflect.Float32: "in.Float32()", reflect.Float64: "in.Float64()", } var primitiveStringDecoders = map[reflect.Kind]string{ reflect.String: "in.String()", reflect.Int: "in.IntStr()", reflect.Int8: "in.Int8Str()", reflect.Int16: "in.Int16Str()", reflect.Int32: "in.Int32Str()", reflect.Int64: "in.Int64Str()", reflect.Uint: "in.UintStr()", reflect.Uint8: "in.Uint8Str()", reflect.Uint16: "in.Uint16Str()", reflect.Uint32: "in.Uint32Str()", reflect.Uint64: "in.Uint64Str()", reflect.Uintptr: "in.UintptrStr()", reflect.Float32: "in.Float32Str()", reflect.Float64: "in.Float64Str()", } var customDecoders = map[string]string{ "json.Number": "in.JsonNumber()", } // genTypeDecoder generates decoding code for the type t, but uses unmarshaler interface if implemented by t. func (g *Generator) genTypeDecoder(t reflect.Type, out string, tags fieldTags, indent int) error { ws := strings.Repeat(" ", indent) unmarshalerIface := reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"("+out+").UnmarshalEasyJSON(in)") return nil } unmarshalerIface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.Raw(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalJSON(data) )") fmt.Fprintln(g.out, ws+"}") return nil } unmarshalerIface = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.UnsafeBytes(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalText(data) )") fmt.Fprintln(g.out, ws+"}") return nil } err := g.genTypeDecoderNoCheck(t, out, tags, indent) return err } // returns true if the type t implements one of the custom unmarshaler interfaces func hasCustomUnmarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()) } func hasUnknownsUnmarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.UnknownsUnmarshaler)(nil)).Elem()) } func hasUnknownsMarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.UnknownsMarshaler)(nil)).Elem()) } // genTypeDecoderNoCheck generates decoding code for the type t. func (g *Generator) genTypeDecoderNoCheck(t reflect.Type, out string, tags fieldTags, indent int) error { ws := strings.Repeat(" ", indent) // Check whether type is primitive, needs to be done after interface check. if dec := customDecoders[t.String()]; dec != "" { fmt.Fprintln(g.out, ws+out+" = "+dec) return nil } else if dec := primitiveStringDecoders[t.Kind()]; dec != "" && tags.asString { if tags.intern && t.Kind() == reflect.String { dec = "in.StringIntern()" } fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") return nil } else if dec := primitiveDecoders[t.Kind()]; dec != "" { if tags.intern && t.Kind() == reflect.String { dec = "in.StringIntern()" } if tags.noCopy && t.Kind() == reflect.String { dec = "in.UnsafeString()" } fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") return nil } switch t.Kind() { case reflect.Slice: tmpVar := g.uniqueVarName() elem := t.Elem() if elem.Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+" "+out+" = nil") fmt.Fprintln(g.out, ws+"} else {") if g.simpleBytes { fmt.Fprintln(g.out, ws+" "+out+" = []byte(in.String())") } else { fmt.Fprintln(g.out, ws+" "+out+" = in.Bytes()") } fmt.Fprintln(g.out, ws+"}") } else { capacity := 1 if elem.Size() > 0 { capacity = minSliceBytes / int(elem.Size()) } fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+" "+out+" = nil") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" in.Delim('[')") fmt.Fprintln(g.out, ws+" if "+out+" == nil {") fmt.Fprintln(g.out, ws+" if !in.IsDelim(']') {") fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+", 0, "+fmt.Sprint(capacity)+")") fmt.Fprintln(g.out, ws+" } else {") fmt.Fprintln(g.out, ws+" "+out+" = "+g.getType(t)+"{}") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" } else { ") fmt.Fprintln(g.out, ws+" "+out+" = ("+out+")[:0]") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) if err := g.genTypeDecoder(elem, tmpVar, tags, indent+2); err != nil { return err } fmt.Fprintln(g.out, ws+" "+out+" = append("+out+", "+tmpVar+")") fmt.Fprintln(g.out, ws+" in.WantComma()") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" in.Delim(']')") fmt.Fprintln(g.out, ws+"}") } case reflect.Array: iterVar := g.uniqueVarName() elem := t.Elem() if elem.Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" copy("+out+"[:], in.Bytes())") fmt.Fprintln(g.out, ws+"}") } else { length := t.Len() fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" in.Delim('[')") fmt.Fprintln(g.out, ws+" "+iterVar+" := 0") fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") fmt.Fprintln(g.out, ws+" if "+iterVar+" < "+fmt.Sprint(length)+" {") if err := g.genTypeDecoder(elem, "("+out+")["+iterVar+"]", tags, indent+3); err != nil { return err } fmt.Fprintln(g.out, ws+" "+iterVar+"++") fmt.Fprintln(g.out, ws+" } else {") fmt.Fprintln(g.out, ws+" in.SkipRecursive()") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" in.WantComma()") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" in.Delim(']')") fmt.Fprintln(g.out, ws+"}") } case reflect.Struct: dec := g.getDecoderName(t) g.addType(t) if len(out) > 0 && out[0] == '*' { // NOTE: In order to remove an extra reference to a pointer fmt.Fprintln(g.out, ws+dec+"(in, "+out[1:]+")") } else { fmt.Fprintln(g.out, ws+dec+"(in, &"+out+")") } case reflect.Ptr: fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+" "+out+" = nil") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" if "+out+" == nil {") fmt.Fprintln(g.out, ws+" "+out+" = new("+g.getType(t.Elem())+")") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeDecoder(t.Elem(), "*"+out, tags, indent+1); err != nil { return err } fmt.Fprintln(g.out, ws+"}") case reflect.Map: key := t.Key() keyDec, ok := primitiveStringDecoders[key.Kind()] if !ok && !hasCustomUnmarshaler(key) { return fmt.Errorf("map type %v not supported: only string and integer keys and types implementing json.Unmarshaler are allowed", key) } // else assume the caller knows what they are doing and that the custom unmarshaler performs the translation from string or integer keys to the key type elem := t.Elem() tmpVar := g.uniqueVarName() keepEmpty := tags.required || tags.noOmitEmpty || (!g.omitEmpty && !tags.omitEmpty) fmt.Fprintln(g.out, ws+"if in.IsNull() {") fmt.Fprintln(g.out, ws+" in.Skip()") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" in.Delim('{')") if !keepEmpty { fmt.Fprintln(g.out, ws+" if !in.IsDelim('}') {") } fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+")") if !keepEmpty { fmt.Fprintln(g.out, ws+" } else {") fmt.Fprintln(g.out, ws+" "+out+" = nil") fmt.Fprintln(g.out, ws+" }") } fmt.Fprintln(g.out, ws+" for !in.IsDelim('}') {") // NOTE: extra check for TextUnmarshaler. It overrides default methods. if reflect.PtrTo(key).Implements(reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()) { fmt.Fprintln(g.out, ws+" var key "+g.getType(key)) fmt.Fprintln(g.out, ws+"if data := in.UnsafeBytes(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError(key.UnmarshalText(data) )") fmt.Fprintln(g.out, ws+"}") } else if keyDec != "" { fmt.Fprintln(g.out, ws+" key := "+g.getType(key)+"("+keyDec+")") } else { fmt.Fprintln(g.out, ws+" var key "+g.getType(key)) if err := g.genTypeDecoder(key, "key", tags, indent+2); err != nil { return err } } fmt.Fprintln(g.out, ws+" in.WantColon()") fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) if err := g.genTypeDecoder(elem, tmpVar, tags, indent+2); err != nil { return err } fmt.Fprintln(g.out, ws+" ("+out+")[key] = "+tmpVar) fmt.Fprintln(g.out, ws+" in.WantComma()") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" in.Delim('}')") fmt.Fprintln(g.out, ws+"}") case reflect.Interface: if t.NumMethod() != 0 { if g.interfaceIsEasyjsonUnmarshaller(t) { fmt.Fprintln(g.out, ws+out+".UnmarshalEasyJSON(in)") } else if g.interfaceIsJsonUnmarshaller(t) { fmt.Fprintln(g.out, ws+out+".UnmarshalJSON(in.Raw())") } else { return fmt.Errorf("interface type %v not supported: only interface{} and easyjson/json Unmarshaler are allowed", t) } } else { fmt.Fprintln(g.out, ws+"if m, ok := "+out+".(easyjson.Unmarshaler); ok {") fmt.Fprintln(g.out, ws+"m.UnmarshalEasyJSON(in)") fmt.Fprintln(g.out, ws+"} else if m, ok := "+out+".(json.Unmarshaler); ok {") fmt.Fprintln(g.out, ws+"_ = m.UnmarshalJSON(in.Raw())") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" "+out+" = in.Interface()") fmt.Fprintln(g.out, ws+"}") } default: return fmt.Errorf("don't know how to decode %v", t) } return nil } func (g *Generator) interfaceIsEasyjsonUnmarshaller(t reflect.Type) bool { return t.Implements(reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem()) } func (g *Generator) interfaceIsJsonUnmarshaller(t reflect.Type) bool { return t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) } func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField) error { jsonName := g.fieldNamer.GetJSONFieldName(t, f) tags := parseFieldTags(f) if tags.omit { return nil } if tags.intern && tags.noCopy { return errors.New("Mutually exclusive tags are specified: 'intern' and 'nocopy'") } fmt.Fprintf(g.out, " case %q:\n", jsonName) if err := g.genTypeDecoder(f.Type, "out."+f.Name, tags, 3); err != nil { return err } if tags.required { fmt.Fprintf(g.out, "%sSet = true\n", f.Name) } return nil } func (g *Generator) genRequiredFieldSet(t reflect.Type, f reflect.StructField) { tags := parseFieldTags(f) if !tags.required { return } fmt.Fprintf(g.out, "var %sSet bool\n", f.Name) } func (g *Generator) genRequiredFieldCheck(t reflect.Type, f reflect.StructField) { jsonName := g.fieldNamer.GetJSONFieldName(t, f) tags := parseFieldTags(f) if !tags.required { return } g.imports["fmt"] = "fmt" fmt.Fprintf(g.out, "if !%sSet {\n", f.Name) fmt.Fprintf(g.out, " in.AddError(fmt.Errorf(\"key '%s' is required\"))\n", jsonName) fmt.Fprintf(g.out, "}\n") } func mergeStructFields(fields1, fields2 []reflect.StructField) (fields []reflect.StructField) { used := map[string]bool{} for _, f := range fields2 { used[f.Name] = true fields = append(fields, f) } for _, f := range fields1 { if !used[f.Name] { fields = append(fields, f) } } return } func getStructFields(t reflect.Type) ([]reflect.StructField, error) { if t.Kind() != reflect.Struct { return nil, fmt.Errorf("got %v; expected a struct", t) } var efields []reflect.StructField var fields []reflect.StructField for i := 0; i < t.NumField(); i++ { f := t.Field(i) tags := parseFieldTags(f) if !f.Anonymous || tags.name != "" { continue } t1 := f.Type if t1.Kind() == reflect.Ptr { t1 = t1.Elem() } if t1.Kind() == reflect.Struct { fs, err := getStructFields(t1) if err != nil { return nil, fmt.Errorf("error processing embedded field: %v", err) } efields = mergeStructFields(efields, fs) } else if (t1.Kind() >= reflect.Bool && t1.Kind() < reflect.Complex128) || t1.Kind() == reflect.String { if strings.Contains(f.Name, ".") || unicode.IsUpper([]rune(f.Name)[0]) { fields = append(fields, f) } } } for i := 0; i < t.NumField(); i++ { f := t.Field(i) tags := parseFieldTags(f) if f.Anonymous && tags.name == "" { continue } c := []rune(f.Name)[0] if unicode.IsUpper(c) { fields = append(fields, f) } } return mergeStructFields(efields, fields), nil } func (g *Generator) genDecoder(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map: return g.genSliceArrayDecoder(t) default: return g.genStructDecoder(t) } } func (g *Generator) genSliceArrayDecoder(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map: default: return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) } fname := g.getDecoderName(t) typ := g.getType(t) fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") err := g.genTypeDecoderNoCheck(t, "*out", fieldTags{}, 1) if err != nil { return err } fmt.Fprintln(g.out, " if isTopLevel {") fmt.Fprintln(g.out, " in.Consumed()") fmt.Fprintln(g.out, " }") fmt.Fprintln(g.out, "}") return nil } func (g *Generator) genStructDecoder(t reflect.Type) error { if t.Kind() != reflect.Struct { return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) } fname := g.getDecoderName(t) typ := g.getType(t) fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") fmt.Fprintln(g.out, " if in.IsNull() {") fmt.Fprintln(g.out, " if isTopLevel {") fmt.Fprintln(g.out, " in.Consumed()") fmt.Fprintln(g.out, " }") fmt.Fprintln(g.out, " in.Skip()") fmt.Fprintln(g.out, " return") fmt.Fprintln(g.out, " }") // Init embedded pointer fields. for i := 0; i < t.NumField(); i++ { f := t.Field(i) if !f.Anonymous || f.Type.Kind() != reflect.Ptr { continue } fmt.Fprintln(g.out, " out."+f.Name+" = new("+g.getType(f.Type.Elem())+")") } fs, err := getStructFields(t) if err != nil { return fmt.Errorf("cannot generate decoder for %v: %v", t, err) } for _, f := range fs { g.genRequiredFieldSet(t, f) } fmt.Fprintln(g.out, " in.Delim('{')") fmt.Fprintln(g.out, " for !in.IsDelim('}') {") fmt.Fprintf(g.out, " key := in.UnsafeFieldName(%v)\n", g.skipMemberNameUnescaping) fmt.Fprintln(g.out, " in.WantColon()") fmt.Fprintln(g.out, " if in.IsNull() {") fmt.Fprintln(g.out, " in.Skip()") fmt.Fprintln(g.out, " in.WantComma()") fmt.Fprintln(g.out, " continue") fmt.Fprintln(g.out, " }") fmt.Fprintln(g.out, " switch key {") for _, f := range fs { if err := g.genStructFieldDecoder(t, f); err != nil { return err } } fmt.Fprintln(g.out, " default:") if g.disallowUnknownFields { fmt.Fprintln(g.out, ` in.AddError(&jlexer.LexerError{ Offset: in.GetPos(), Reason: "unknown field", Data: key, })`) } else if hasUnknownsUnmarshaler(t) { fmt.Fprintln(g.out, " out.UnmarshalUnknown(in, key)") } else { fmt.Fprintln(g.out, " in.SkipRecursive()") } fmt.Fprintln(g.out, " }") fmt.Fprintln(g.out, " in.WantComma()") fmt.Fprintln(g.out, " }") fmt.Fprintln(g.out, " in.Delim('}')") fmt.Fprintln(g.out, " if isTopLevel {") fmt.Fprintln(g.out, " in.Consumed()") fmt.Fprintln(g.out, " }") for _, f := range fs { g.genRequiredFieldCheck(t, f) } fmt.Fprintln(g.out, "}") return nil } func (g *Generator) genStructUnmarshaler(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: default: return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) } fname := g.getDecoderName(t) typ := g.getType(t) if !g.noStdMarshalers { fmt.Fprintln(g.out, "// UnmarshalJSON supports json.Unmarshaler interface") fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalJSON(data []byte) error {") fmt.Fprintln(g.out, " r := jlexer.Lexer{Data: data}") fmt.Fprintln(g.out, " "+fname+"(&r, v)") fmt.Fprintln(g.out, " return r.Error()") fmt.Fprintln(g.out, "}") } fmt.Fprintln(g.out, "// UnmarshalEasyJSON supports easyjson.Unmarshaler interface") fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalEasyJSON(l *jlexer.Lexer) {") fmt.Fprintln(g.out, " "+fname+"(l, v)") fmt.Fprintln(g.out, "}") return nil } easyjson-0.7.6/gen/encoder.go000066400000000000000000000342731371475264500161250ustar00rootroot00000000000000package gen import ( "encoding" "encoding/json" "fmt" "reflect" "strconv" "strings" "github.com/mailru/easyjson" ) func (g *Generator) getEncoderName(t reflect.Type) string { return g.functionName("encode", t) } var primitiveEncoders = map[reflect.Kind]string{ reflect.String: "out.String(string(%v))", reflect.Bool: "out.Bool(bool(%v))", reflect.Int: "out.Int(int(%v))", reflect.Int8: "out.Int8(int8(%v))", reflect.Int16: "out.Int16(int16(%v))", reflect.Int32: "out.Int32(int32(%v))", reflect.Int64: "out.Int64(int64(%v))", reflect.Uint: "out.Uint(uint(%v))", reflect.Uint8: "out.Uint8(uint8(%v))", reflect.Uint16: "out.Uint16(uint16(%v))", reflect.Uint32: "out.Uint32(uint32(%v))", reflect.Uint64: "out.Uint64(uint64(%v))", reflect.Float32: "out.Float32(float32(%v))", reflect.Float64: "out.Float64(float64(%v))", } var primitiveStringEncoders = map[reflect.Kind]string{ reflect.String: "out.String(string(%v))", reflect.Int: "out.IntStr(int(%v))", reflect.Int8: "out.Int8Str(int8(%v))", reflect.Int16: "out.Int16Str(int16(%v))", reflect.Int32: "out.Int32Str(int32(%v))", reflect.Int64: "out.Int64Str(int64(%v))", reflect.Uint: "out.UintStr(uint(%v))", reflect.Uint8: "out.Uint8Str(uint8(%v))", reflect.Uint16: "out.Uint16Str(uint16(%v))", reflect.Uint32: "out.Uint32Str(uint32(%v))", reflect.Uint64: "out.Uint64Str(uint64(%v))", reflect.Uintptr: "out.UintptrStr(uintptr(%v))", reflect.Float32: "out.Float32Str(float32(%v))", reflect.Float64: "out.Float64Str(float64(%v))", } // fieldTags contains parsed version of json struct field tags. type fieldTags struct { name string omit bool omitEmpty bool noOmitEmpty bool asString bool required bool intern bool noCopy bool } // parseFieldTags parses the json field tag into a structure. func parseFieldTags(f reflect.StructField) fieldTags { var ret fieldTags for i, s := range strings.Split(f.Tag.Get("json"), ",") { switch { case i == 0 && s == "-": ret.omit = true case i == 0: ret.name = s case s == "omitempty": ret.omitEmpty = true case s == "!omitempty": ret.noOmitEmpty = true case s == "string": ret.asString = true case s == "required": ret.required = true case s == "intern": ret.intern = true case s == "nocopy": ret.noCopy = true } } return ret } // genTypeEncoder generates code that encodes in of type t into the writer, but uses marshaler interface if implemented by t. func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)") return nil } marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )") return nil } marshalerIface = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.RawText( ("+in+").MarshalText() )") return nil } err := g.genTypeEncoderNoCheck(t, in, tags, indent, assumeNonEmpty) return err } // returns true if the type t implements one of the custom marshaler interfaces func hasCustomMarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) } // genTypeEncoderNoCheck generates code that encodes in of type t into the writer. func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) // Check whether type is primitive, needs to be done after interface check. if enc := primitiveStringEncoders[t.Kind()]; enc != "" && tags.asString { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } if enc := primitiveEncoders[t.Kind()]; enc != "" { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } switch t.Kind() { case reflect.Slice: elem := t.Elem() iVar := g.uniqueVarName() vVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { if g.simpleBytes { fmt.Fprintln(g.out, ws+"out.String(string("+in+"))") } else { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")") } } else { if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('[')") fmt.Fprintln(g.out, ws+" for "+iVar+", "+vVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, vVar, tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte(']')") fmt.Fprintln(g.out, ws+"}") } case reflect.Array: elem := t.Elem() iVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { if g.simpleBytes { fmt.Fprintln(g.out, ws+"out.String(string("+in+"[:]))") } else { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+"[:])") } } else { fmt.Fprintln(g.out, ws+"out.RawByte('[')") fmt.Fprintln(g.out, ws+"for "+iVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, "("+in+")["+iVar+"]", tags, indent+1, false); err != nil { return err } fmt.Fprintln(g.out, ws+"}") fmt.Fprintln(g.out, ws+"out.RawByte(']')") } case reflect.Struct: enc := g.getEncoderName(t) g.addType(t) fmt.Fprintln(g.out, ws+enc+"(out, "+in+")") case reflect.Ptr: if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } if err := g.genTypeEncoder(t.Elem(), "*"+in, tags, indent+1, false); err != nil { return err } if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"}") } case reflect.Map: key := t.Key() keyEnc, ok := primitiveStringEncoders[key.Kind()] if !ok && !hasCustomMarshaler(key) { return fmt.Errorf("map key type %v not supported: only string and integer keys and types implementing Marshaler interfaces are allowed", key) } // else assume the caller knows what they are doing and that the custom marshaler performs the translation from the key type to a string or integer tmpVar := g.uniqueVarName() if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+" out.RawString(`null`)") fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('{')") fmt.Fprintln(g.out, ws+" "+tmpVar+"First := true") fmt.Fprintln(g.out, ws+" for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+tmpVar+"First { "+tmpVar+"First = false } else { out.RawByte(',') }") // NOTE: extra check for TextMarshaler. It overrides default methods. if reflect.PtrTo(key).Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf("out.RawText(("+tmpVar+"Name).MarshalText()"+")")) } else if keyEnc != "" { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf(keyEnc, tmpVar+"Name")) } else { if err := g.genTypeEncoder(key, tmpVar+"Name", tags, indent+2, false); err != nil { return err } } fmt.Fprintln(g.out, ws+" out.RawByte(':')") if err := g.genTypeEncoder(t.Elem(), tmpVar+"Value", tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte('}')") fmt.Fprintln(g.out, ws+"}") case reflect.Interface: if t.NumMethod() != 0 { if g.interfaceIsEasyjsonMarshaller(t) { fmt.Fprintln(g.out, ws+in+".MarshalEasyJSON(out)") } else if g.interfaceIsJSONMarshaller(t) { fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+in+".MarshalJSON(out)") fmt.Fprintln(g.out, ws+"}") } else { return fmt.Errorf("interface type %v not supported: only interface{} and interfaces that implement json or easyjson Marshaling are allowed", t) } } else { fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") fmt.Fprintln(g.out, ws+"} else if m, ok := "+in+".(json.Marshaler); ok {") fmt.Fprintln(g.out, ws+" out.Raw(m.MarshalJSON())") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" out.Raw(json.Marshal("+in+"))") fmt.Fprintln(g.out, ws+"}") } default: return fmt.Errorf("don't know how to encode %v", t) } return nil } func (g *Generator) interfaceIsEasyjsonMarshaller(t reflect.Type) bool { return t.Implements(reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem()) } func (g *Generator) interfaceIsJSONMarshaller(t reflect.Type) bool { return t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) } func (g *Generator) notEmptyCheck(t reflect.Type, v string) string { optionalIface := reflect.TypeOf((*easyjson.Optional)(nil)).Elem() if reflect.PtrTo(t).Implements(optionalIface) { return "(" + v + ").IsDefined()" } switch t.Kind() { case reflect.Slice, reflect.Map: return "len(" + v + ") != 0" case reflect.Interface, reflect.Ptr: return v + " != nil" case reflect.Bool: return v case reflect.String: return v + ` != ""` case reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v + " != 0" default: // note: Array types don't have a useful empty value return "true" } } func (g *Generator) genStructFieldEncoder(t reflect.Type, f reflect.StructField, first, firstCondition bool) (bool, error) { jsonName := g.fieldNamer.GetJSONFieldName(t, f) tags := parseFieldTags(f) if tags.omit { return firstCondition, nil } toggleFirstCondition := firstCondition noOmitEmpty := (!tags.omitEmpty && !g.omitEmpty) || tags.noOmitEmpty if noOmitEmpty { fmt.Fprintln(g.out, " {") toggleFirstCondition = false } else { fmt.Fprintln(g.out, " if", g.notEmptyCheck(f.Type, "in."+f.Name), "{") // can be any in runtime, so toggleFirstCondition stay as is } if firstCondition { fmt.Fprintf(g.out, " const prefix string = %q\n", ","+strconv.Quote(jsonName)+":") if first { if !noOmitEmpty { fmt.Fprintln(g.out, " first = false") } fmt.Fprintln(g.out, " out.RawString(prefix[1:])") } else { fmt.Fprintln(g.out, " if first {") fmt.Fprintln(g.out, " first = false") fmt.Fprintln(g.out, " out.RawString(prefix[1:])") fmt.Fprintln(g.out, " } else {") fmt.Fprintln(g.out, " out.RawString(prefix)") fmt.Fprintln(g.out, " }") } } else { fmt.Fprintf(g.out, " const prefix string = %q\n", ","+strconv.Quote(jsonName)+":") fmt.Fprintln(g.out, " out.RawString(prefix)") } if err := g.genTypeEncoder(f.Type, "in."+f.Name, tags, 2, !noOmitEmpty); err != nil { return toggleFirstCondition, err } fmt.Fprintln(g.out, " }") return toggleFirstCondition, nil } func (g *Generator) genEncoder(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map: return g.genSliceArrayMapEncoder(t) default: return g.genStructEncoder(t) } } func (g *Generator) genSliceArrayMapEncoder(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map: default: return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) } fname := g.getEncoderName(t) typ := g.getType(t) fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") err := g.genTypeEncoderNoCheck(t, "in", fieldTags{}, 1, false) if err != nil { return err } fmt.Fprintln(g.out, "}") return nil } func (g *Generator) genStructEncoder(t reflect.Type) error { if t.Kind() != reflect.Struct { return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) } fname := g.getEncoderName(t) typ := g.getType(t) fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") fmt.Fprintln(g.out, " out.RawByte('{')") fmt.Fprintln(g.out, " first := true") fmt.Fprintln(g.out, " _ = first") fs, err := getStructFields(t) if err != nil { return fmt.Errorf("cannot generate encoder for %v: %v", t, err) } firstCondition := true for i, f := range fs { firstCondition, err = g.genStructFieldEncoder(t, f, i == 0, firstCondition) if err != nil { return err } } if hasUnknownsMarshaler(t) { if !firstCondition { fmt.Fprintln(g.out, " in.MarshalUnknowns(out, false)") } else { fmt.Fprintln(g.out, " in.MarshalUnknowns(out, first)") } } fmt.Fprintln(g.out, " out.RawByte('}')") fmt.Fprintln(g.out, "}") return nil } func (g *Generator) genStructMarshaler(t reflect.Type) error { switch t.Kind() { case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: default: return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) } fname := g.getEncoderName(t) typ := g.getType(t) if !g.noStdMarshalers { fmt.Fprintln(g.out, "// MarshalJSON supports json.Marshaler interface") fmt.Fprintln(g.out, "func (v "+typ+") MarshalJSON() ([]byte, error) {") fmt.Fprintln(g.out, " w := jwriter.Writer{}") fmt.Fprintln(g.out, " "+fname+"(&w, v)") fmt.Fprintln(g.out, " return w.Buffer.BuildBytes(), w.Error") fmt.Fprintln(g.out, "}") } fmt.Fprintln(g.out, "// MarshalEasyJSON supports easyjson.Marshaler interface") fmt.Fprintln(g.out, "func (v "+typ+") MarshalEasyJSON(w *jwriter.Writer) {") fmt.Fprintln(g.out, " "+fname+"(w, v)") fmt.Fprintln(g.out, "}") return nil } easyjson-0.7.6/gen/generator.go000066400000000000000000000321551371475264500164710ustar00rootroot00000000000000package gen import ( "bytes" "fmt" "hash/fnv" "io" "path" "reflect" "sort" "strconv" "strings" "unicode" ) const pkgWriter = "github.com/mailru/easyjson/jwriter" const pkgLexer = "github.com/mailru/easyjson/jlexer" const pkgEasyJSON = "github.com/mailru/easyjson" // FieldNamer defines a policy for generating names for struct fields. type FieldNamer interface { GetJSONFieldName(t reflect.Type, f reflect.StructField) string } // Generator generates the requested marshaler/unmarshalers. type Generator struct { out *bytes.Buffer pkgName string pkgPath string buildTags string hashString string varCounter int noStdMarshalers bool omitEmpty bool disallowUnknownFields bool fieldNamer FieldNamer simpleBytes bool skipMemberNameUnescaping bool // package path to local alias map for tracking imports imports map[string]string // types that marshalers were requested for by user marshalers map[reflect.Type]bool // types that encoders were already generated for typesSeen map[reflect.Type]bool // types that encoders were requested for (e.g. by encoders of other types) typesUnseen []reflect.Type // function name to relevant type maps to track names of de-/encoders in // case of a name clash or unnamed structs functionNames map[string]reflect.Type } // NewGenerator initializes and returns a Generator. func NewGenerator(filename string) *Generator { ret := &Generator{ imports: map[string]string{ pkgWriter: "jwriter", pkgLexer: "jlexer", pkgEasyJSON: "easyjson", "encoding/json": "json", }, fieldNamer: DefaultFieldNamer{}, marshalers: make(map[reflect.Type]bool), typesSeen: make(map[reflect.Type]bool), functionNames: make(map[string]reflect.Type), } // Use a file-unique prefix on all auxiliary funcs to avoid // name clashes. hash := fnv.New32() hash.Write([]byte(filename)) ret.hashString = fmt.Sprintf("%x", hash.Sum32()) return ret } // SetPkg sets the name and path of output package. func (g *Generator) SetPkg(name, path string) { g.pkgName = name g.pkgPath = path } // SetBuildTags sets build tags for the output file. func (g *Generator) SetBuildTags(tags string) { g.buildTags = tags } // SetFieldNamer sets field naming strategy. func (g *Generator) SetFieldNamer(n FieldNamer) { g.fieldNamer = n } // UseSnakeCase sets snake_case field naming strategy. func (g *Generator) UseSnakeCase() { g.fieldNamer = SnakeCaseFieldNamer{} } // UseLowerCamelCase sets lowerCamelCase field naming strategy. func (g *Generator) UseLowerCamelCase() { g.fieldNamer = LowerCamelCaseFieldNamer{} } // NoStdMarshalers instructs not to generate standard MarshalJSON/UnmarshalJSON // methods (only the custom interface). func (g *Generator) NoStdMarshalers() { g.noStdMarshalers = true } // DisallowUnknownFields instructs not to skip unknown fields in json and return error. func (g *Generator) DisallowUnknownFields() { g.disallowUnknownFields = true } // SkipMemberNameUnescaping instructs to skip member names unescaping to improve performance func (g *Generator) SkipMemberNameUnescaping() { g.skipMemberNameUnescaping = true } // OmitEmpty triggers `json=",omitempty"` behaviour by default. func (g *Generator) OmitEmpty() { g.omitEmpty = true } // SimpleBytes triggers generate output bytes as slice byte func (g *Generator) SimpleBytes() { g.simpleBytes = true } // addTypes requests to generate encoding/decoding funcs for the given type. func (g *Generator) addType(t reflect.Type) { if g.typesSeen[t] { return } for _, t1 := range g.typesUnseen { if t1 == t { return } } g.typesUnseen = append(g.typesUnseen, t) } // Add requests to generate marshaler/unmarshalers and encoding/decoding // funcs for the type of given object. func (g *Generator) Add(obj interface{}) { t := reflect.TypeOf(obj) if t.Kind() == reflect.Ptr { t = t.Elem() } g.addType(t) g.marshalers[t] = true } // printHeader prints package declaration and imports. func (g *Generator) printHeader() { if g.buildTags != "" { fmt.Println("// +build ", g.buildTags) fmt.Println() } fmt.Println("// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.") fmt.Println() fmt.Println("package ", g.pkgName) fmt.Println() byAlias := make(map[string]string, len(g.imports)) aliases := make([]string, 0, len(g.imports)) for path, alias := range g.imports { aliases = append(aliases, alias) byAlias[alias] = path } sort.Strings(aliases) fmt.Println("import (") for _, alias := range aliases { fmt.Printf(" %s %q\n", alias, byAlias[alias]) } fmt.Println(")") fmt.Println("") fmt.Println("// suppress unused package warning") fmt.Println("var (") fmt.Println(" _ *json.RawMessage") fmt.Println(" _ *jlexer.Lexer") fmt.Println(" _ *jwriter.Writer") fmt.Println(" _ easyjson.Marshaler") fmt.Println(")") fmt.Println() } // Run runs the generator and outputs generated code to out. func (g *Generator) Run(out io.Writer) error { g.out = &bytes.Buffer{} for len(g.typesUnseen) > 0 { t := g.typesUnseen[len(g.typesUnseen)-1] g.typesUnseen = g.typesUnseen[:len(g.typesUnseen)-1] g.typesSeen[t] = true if err := g.genDecoder(t); err != nil { return err } if err := g.genEncoder(t); err != nil { return err } if !g.marshalers[t] { continue } if err := g.genStructMarshaler(t); err != nil { return err } if err := g.genStructUnmarshaler(t); err != nil { return err } } g.printHeader() _, err := out.Write(g.out.Bytes()) return err } // fixes vendored paths func fixPkgPathVendoring(pkgPath string) string { const vendor = "/vendor/" if i := strings.LastIndex(pkgPath, vendor); i != -1 { return pkgPath[i+len(vendor):] } return pkgPath } func fixAliasName(alias string) string { alias = strings.Replace( strings.Replace(alias, ".", "_", -1), "-", "_", -1, ) if alias[0] == 'v' { // to void conflicting with var names, say v1 alias = "_" + alias } return alias } // pkgAlias creates and returns and import alias for a given package. func (g *Generator) pkgAlias(pkgPath string) string { pkgPath = fixPkgPathVendoring(pkgPath) if alias := g.imports[pkgPath]; alias != "" { return alias } for i := 0; ; i++ { alias := fixAliasName(path.Base(pkgPath)) if i > 0 { alias += fmt.Sprint(i) } exists := false for _, v := range g.imports { if v == alias { exists = true break } } if !exists { g.imports[pkgPath] = alias return alias } } } // getType return the textual type name of given type that can be used in generated code. func (g *Generator) getType(t reflect.Type) string { if t.Name() == "" { switch t.Kind() { case reflect.Ptr: return "*" + g.getType(t.Elem()) case reflect.Slice: return "[]" + g.getType(t.Elem()) case reflect.Array: return "[" + strconv.Itoa(t.Len()) + "]" + g.getType(t.Elem()) case reflect.Map: return "map[" + g.getType(t.Key()) + "]" + g.getType(t.Elem()) } } if t.Name() == "" || t.PkgPath() == "" { if t.Kind() == reflect.Struct { // the fields of an anonymous struct can have named types, // and t.String() will not be sufficient because it does not // remove the package name when it matches g.pkgPath. // so we convert by hand nf := t.NumField() lines := make([]string, 0, nf) for i := 0; i < nf; i++ { f := t.Field(i) var line string if !f.Anonymous { line = f.Name + " " } // else the field is anonymous (an embedded type) line += g.getType(f.Type) t := f.Tag if t != "" { line += " " + escapeTag(t) } lines = append(lines, line) } return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") } return t.String() } else if t.PkgPath() == g.pkgPath { return t.Name() } return g.pkgAlias(t.PkgPath()) + "." + t.Name() } // escape a struct field tag string back to source code func escapeTag(tag reflect.StructTag) string { t := string(tag) if strings.ContainsRune(t, '`') { // there are ` in the string; we can't use ` to enclose the string return strconv.Quote(t) } return "`" + t + "`" } // uniqueVarName returns a file-unique name that can be used for generated variables. func (g *Generator) uniqueVarName() string { g.varCounter++ return fmt.Sprint("v", g.varCounter) } // safeName escapes unsafe characters in pkg/type name and returns a string that can be used // in encoder/decoder names for the type. func (g *Generator) safeName(t reflect.Type) string { name := t.PkgPath() if t.Name() == "" { name += "anonymous" } else { name += "." + t.Name() } parts := []string{} part := []rune{} for _, c := range name { if unicode.IsLetter(c) || unicode.IsDigit(c) { part = append(part, c) } else if len(part) > 0 { parts = append(parts, string(part)) part = []rune{} } } return joinFunctionNameParts(false, parts...) } // functionName returns a function name for a given type with a given prefix. If a function // with this prefix already exists for a type, it is returned. // // Method is used to track encoder/decoder names for the type. func (g *Generator) functionName(prefix string, t reflect.Type) string { prefix = joinFunctionNameParts(true, "easyjson", g.hashString, prefix) name := joinFunctionNameParts(true, prefix, g.safeName(t)) // Most of the names will be unique, try a shortcut first. if e, ok := g.functionNames[name]; !ok || e == t { g.functionNames[name] = t return name } // Search if the function already exists. for name1, t1 := range g.functionNames { if t1 == t && strings.HasPrefix(name1, prefix) { return name1 } } // Create a new name in the case of a clash. for i := 1; ; i++ { nm := fmt.Sprint(name, i) if _, ok := g.functionNames[nm]; ok { continue } g.functionNames[nm] = t return nm } } // DefaultFieldsNamer implements trivial naming policy equivalent to encoding/json. type DefaultFieldNamer struct{} func (DefaultFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { jsonName := strings.Split(f.Tag.Get("json"), ",")[0] if jsonName != "" { return jsonName } return f.Name } // LowerCamelCaseFieldNamer type LowerCamelCaseFieldNamer struct{} func isLower(b byte) bool { return b <= 122 && b >= 97 } func isUpper(b byte) bool { return b >= 65 && b <= 90 } // convert HTTPRestClient to httpRestClient func lowerFirst(s string) string { if s == "" { return "" } str := "" strlen := len(s) /** Loop each char If is uppercase: If is first char, LOWER it If the following char is lower, LEAVE it If the following char is upper OR numeric, LOWER it If is the end of string, LEAVE it Else lowercase */ foundLower := false for i := range s { ch := s[i] if isUpper(ch) { switch { case i == 0: str += string(ch + 32) case !foundLower: // Currently just a stream of capitals, eg JSONRESTS[erver] if strlen > (i+1) && isLower(s[i+1]) { // Next char is lower, keep this a capital str += string(ch) } else { // Either at end of string or next char is capital str += string(ch + 32) } default: str += string(ch) } } else { foundLower = true str += string(ch) } } return str } func (LowerCamelCaseFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { jsonName := strings.Split(f.Tag.Get("json"), ",")[0] if jsonName != "" { return jsonName } return lowerFirst(f.Name) } // SnakeCaseFieldNamer implements CamelCase to snake_case conversion for fields names. type SnakeCaseFieldNamer struct{} func camelToSnake(name string) string { var ret bytes.Buffer multipleUpper := false var lastUpper rune var beforeUpper rune for _, c := range name { // Non-lowercase character after uppercase is considered to be uppercase too. isUpper := (unicode.IsUpper(c) || (lastUpper != 0 && !unicode.IsLower(c))) if lastUpper != 0 { // Output a delimiter if last character was either the first uppercase character // in a row, or the last one in a row (e.g. 'S' in "HTTPServer"). // Do not output a delimiter at the beginning of the name. firstInRow := !multipleUpper lastInRow := !isUpper if ret.Len() > 0 && (firstInRow || lastInRow) && beforeUpper != '_' { ret.WriteByte('_') } ret.WriteRune(unicode.ToLower(lastUpper)) } // Buffer uppercase char, do not output it yet as a delimiter may be required if the // next character is lowercase. if isUpper { multipleUpper = (lastUpper != 0) lastUpper = c continue } ret.WriteRune(c) lastUpper = 0 beforeUpper = c multipleUpper = false } if lastUpper != 0 { ret.WriteRune(unicode.ToLower(lastUpper)) } return string(ret.Bytes()) } func (SnakeCaseFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { jsonName := strings.Split(f.Tag.Get("json"), ",")[0] if jsonName != "" { return jsonName } return camelToSnake(f.Name) } func joinFunctionNameParts(keepFirst bool, parts ...string) string { buf := bytes.NewBufferString("") for i, part := range parts { if i == 0 && keepFirst { buf.WriteString(part) } else { if len(part) > 0 { buf.WriteString(strings.ToUpper(string(part[0]))) } if len(part) > 1 { buf.WriteString(part[1:]) } } } return buf.String() } easyjson-0.7.6/gen/generator_test.go000066400000000000000000000041451371475264500175260ustar00rootroot00000000000000package gen import ( "testing" ) func TestCamelToSnake(t *testing.T) { for i, test := range []struct { In, Out string }{ {"", ""}, {"A", "a"}, {"SimpleExample", "simple_example"}, {"internalField", "internal_field"}, {"SomeHTTPStuff", "some_http_stuff"}, {"WriteJSON", "write_json"}, {"HTTP2Server", "http2_server"}, {"Some_Mixed_Case", "some_mixed_case"}, {"do_nothing", "do_nothing"}, {"JSONHTTPRPCServer", "jsonhttprpc_server"}, // nothing can be done here without a dictionary } { got := camelToSnake(test.In) if got != test.Out { t.Errorf("[%d] camelToSnake(%s) = %s; want %s", i, test.In, got, test.Out) } } } func TestCamelToLowerCamel(t *testing.T) { for i, test := range []struct { In, Out string }{ {"", ""}, {"A", "a"}, {"SimpleExample", "simpleExample"}, {"internalField", "internalField"}, {"SomeHTTPStuff", "someHTTPStuff"}, {"WriteJSON", "writeJSON"}, {"HTTP2Server", "http2Server"}, {"JSONHTTPRPCServer", "jsonhttprpcServer"}, // nothing can be done here without a dictionary } { got := lowerFirst(test.In) if got != test.Out { t.Errorf("[%d] lowerFirst(%s) = %s; want %s", i, test.In, got, test.Out) } } } func TestJoinFunctionNameParts(t *testing.T) { for i, test := range []struct { keepFirst bool parts []string out string }{ {false, []string{}, ""}, {false, []string{"a"}, "A"}, {false, []string{"simple", "example"}, "SimpleExample"}, {true, []string{"first", "example"}, "firstExample"}, {false, []string{"some", "UPPER", "case"}, "SomeUPPERCase"}, {false, []string{"number", "123"}, "Number123"}, } { got := joinFunctionNameParts(test.keepFirst, test.parts...) if got != test.out { t.Errorf("[%d] joinFunctionNameParts(%v) = %s; want %s", i, test.parts, got, test.out) } } } func TestFixVendorPath(t *testing.T) { for i, test := range []struct { In, Out string }{ {"", ""}, {"time", "time"}, {"project/vendor/subpackage", "subpackage"}, } { got := fixPkgPathVendoring(test.In) if got != test.Out { t.Errorf("[%d] fixPkgPathVendoring(%s) = %s; want %s", i, test.In, got, test.Out) } } } easyjson-0.7.6/go.mod000066400000000000000000000001271371475264500145030ustar00rootroot00000000000000module github.com/mailru/easyjson go 1.12 require github.com/josharian/intern v1.0.0 easyjson-0.7.6/go.sum000066400000000000000000000002551371475264500145320ustar00rootroot00000000000000github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= easyjson-0.7.6/helpers.go000066400000000000000000000061301371475264500153660ustar00rootroot00000000000000// Package easyjson contains marshaler/unmarshaler interfaces and helper functions. package easyjson import ( "io" "io/ioutil" "net/http" "strconv" "unsafe" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // Marshaler is an easyjson-compatible marshaler interface. type Marshaler interface { MarshalEasyJSON(w *jwriter.Writer) } // Marshaler is an easyjson-compatible unmarshaler interface. type Unmarshaler interface { UnmarshalEasyJSON(w *jlexer.Lexer) } // MarshalerUnmarshaler is an easyjson-compatible marshaler/unmarshaler interface. type MarshalerUnmarshaler interface { Marshaler Unmarshaler } // Optional defines an undefined-test method for a type to integrate with 'omitempty' logic. type Optional interface { IsDefined() bool } // UnknownsUnmarshaler provides a method to unmarshal unknown struct fileds and save them as you want type UnknownsUnmarshaler interface { UnmarshalUnknown(in *jlexer.Lexer, key string) } // UnknownsMarshaler provides a method to write additional struct fields type UnknownsMarshaler interface { MarshalUnknowns(w *jwriter.Writer, first bool) } func isNilInterface(i interface{}) bool { return (*[2]uintptr)(unsafe.Pointer(&i))[1] == 0 } // Marshal returns data as a single byte slice. Method is suboptimal as the data is likely to be copied // from a chain of smaller chunks. func Marshal(v Marshaler) ([]byte, error) { if isNilInterface(v) { return nullBytes, nil } w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.BuildBytes() } // MarshalToWriter marshals the data to an io.Writer. func MarshalToWriter(v Marshaler, w io.Writer) (written int, err error) { if isNilInterface(v) { return w.Write(nullBytes) } jw := jwriter.Writer{} v.MarshalEasyJSON(&jw) return jw.DumpTo(w) } // MarshalToHTTPResponseWriter sets Content-Length and Content-Type headers for the // http.ResponseWriter, and send the data to the writer. started will be equal to // false if an error occurred before any http.ResponseWriter methods were actually // invoked (in this case a 500 reply is possible). func MarshalToHTTPResponseWriter(v Marshaler, w http.ResponseWriter) (started bool, written int, err error) { if isNilInterface(v) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Length", strconv.Itoa(len(nullBytes))) written, err = w.Write(nullBytes) return true, written, err } jw := jwriter.Writer{} v.MarshalEasyJSON(&jw) if jw.Error != nil { return false, 0, jw.Error } w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Length", strconv.Itoa(jw.Size())) started = true written, err = jw.DumpTo(w) return } // Unmarshal decodes the JSON in data into the object. func Unmarshal(data []byte, v Unmarshaler) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // UnmarshalFromReader reads all the data in the reader and decodes as JSON into the object. func UnmarshalFromReader(r io.Reader, v Unmarshaler) error { data, err := ioutil.ReadAll(r) if err != nil { return err } l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } easyjson-0.7.6/helpers_test.go000066400000000000000000000002721371475264500164260ustar00rootroot00000000000000package easyjson import "testing" func BenchmarkNilCheck(b *testing.B) { var a *int for i := 0; i < b.N; i++ { if !isNilInterface(a) { b.Fatal("expected it to be nil") } } } easyjson-0.7.6/jlexer/000077500000000000000000000000001371475264500146665ustar00rootroot00000000000000easyjson-0.7.6/jlexer/bytestostr.go000066400000000000000000000014001371475264500174320ustar00rootroot00000000000000// This file will only be included to the build if neither // easyjson_nounsafe nor appengine build tag is set. See README notes // for more details. //+build !easyjson_nounsafe //+build !appengine package jlexer import ( "reflect" "unsafe" ) // bytesToStr creates a string pointing at the slice to avoid copying. // // Warning: the string returned by the function should be used with care, as the whole input data // chunk may be either blocked from being freed by GC because of a single string or the buffer.Data // may be garbage-collected even when the string exists. func bytesToStr(data []byte) string { h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} return *(*string)(unsafe.Pointer(&shdr)) } easyjson-0.7.6/jlexer/bytestostr_nounsafe.go000066400000000000000000000005671371475264500213450ustar00rootroot00000000000000// This file is included to the build if any of the buildtags below // are defined. Refer to README notes for more details. //+build easyjson_nounsafe appengine package jlexer // bytesToStr creates a string normally from []byte // // Note that this method is roughly 1.5x slower than using the 'unsafe' method. func bytesToStr(data []byte) string { return string(data) } easyjson-0.7.6/jlexer/error.go000066400000000000000000000005551371475264500163530ustar00rootroot00000000000000package jlexer import "fmt" // LexerError implements the error interface and represents all possible errors that can be // generated during parsing the JSON data. type LexerError struct { Reason string Offset int Data string } func (l *LexerError) Error() string { return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) } easyjson-0.7.6/jlexer/lexer.go000066400000000000000000000604271371475264500163450ustar00rootroot00000000000000// Package jlexer contains a JSON lexer implementation. // // It is expected that it is mostly used with generated parser code, so the interface is tuned // for a parser that knows what kind of data is expected. package jlexer import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "strconv" "unicode" "unicode/utf16" "unicode/utf8" "github.com/josharian/intern" ) // tokenKind determines type of a token. type tokenKind byte const ( tokenUndef tokenKind = iota // No token. tokenDelim // Delimiter: one of '{', '}', '[' or ']'. tokenString // A string literal, e.g. "abc\u1234" tokenNumber // Number literal, e.g. 1.5e5 tokenBool // Boolean literal: true or false. tokenNull // null keyword. ) // token describes a single token: type, position in the input and value. type token struct { kind tokenKind // Type of a token. boolValue bool // Value if a boolean literal token. byteValueCloned bool // true if byteValue was allocated and does not refer to original json body byteValue []byte // Raw value of a token. delimValue byte } // Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. type Lexer struct { Data []byte // Input data given to the lexer. start int // Start of the current token. pos int // Current unscanned position in the input stream. token token // Last scanned token, if token.kind != tokenUndef. firstElement bool // Whether current element is the first in array or an object. wantSep byte // A comma or a colon character, which need to occur before a token. UseMultipleErrors bool // If we want to use multiple errors. fatalError error // Fatal error occurred during lexing. It is usually a syntax error. multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. } // FetchToken scans the input for the next token. func (r *Lexer) FetchToken() { r.token.kind = tokenUndef r.start = r.pos // Check if r.Data has r.pos element // If it doesn't, it mean corrupted input data if len(r.Data) < r.pos { r.errParse("Unexpected end of data") return } // Determine the type of a token by skipping whitespace and reading the // first character. for _, c := range r.Data[r.pos:] { switch c { case ':', ',': if r.wantSep == c { r.pos++ r.start++ r.wantSep = 0 } else { r.errSyntax() } case ' ', '\t', '\r', '\n': r.pos++ r.start++ case '"': if r.wantSep != 0 { r.errSyntax() } r.token.kind = tokenString r.fetchString() return case '{', '[': if r.wantSep != 0 { r.errSyntax() } r.firstElement = true r.token.kind = tokenDelim r.token.delimValue = r.Data[r.pos] r.pos++ return case '}', ']': if !r.firstElement && (r.wantSep != ',') { r.errSyntax() } r.wantSep = 0 r.token.kind = tokenDelim r.token.delimValue = r.Data[r.pos] r.pos++ return case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': if r.wantSep != 0 { r.errSyntax() } r.token.kind = tokenNumber r.fetchNumber() return case 'n': if r.wantSep != 0 { r.errSyntax() } r.token.kind = tokenNull r.fetchNull() return case 't': if r.wantSep != 0 { r.errSyntax() } r.token.kind = tokenBool r.token.boolValue = true r.fetchTrue() return case 'f': if r.wantSep != 0 { r.errSyntax() } r.token.kind = tokenBool r.token.boolValue = false r.fetchFalse() return default: r.errSyntax() return } } r.fatalError = io.EOF return } // isTokenEnd returns true if the char can follow a non-delimiter token func isTokenEnd(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' } // fetchNull fetches and checks remaining bytes of null keyword. func (r *Lexer) fetchNull() { r.pos += 4 if r.pos > len(r.Data) || r.Data[r.pos-3] != 'u' || r.Data[r.pos-2] != 'l' || r.Data[r.pos-1] != 'l' || (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 4 r.errSyntax() } } // fetchTrue fetches and checks remaining bytes of true keyword. func (r *Lexer) fetchTrue() { r.pos += 4 if r.pos > len(r.Data) || r.Data[r.pos-3] != 'r' || r.Data[r.pos-2] != 'u' || r.Data[r.pos-1] != 'e' || (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 4 r.errSyntax() } } // fetchFalse fetches and checks remaining bytes of false keyword. func (r *Lexer) fetchFalse() { r.pos += 5 if r.pos > len(r.Data) || r.Data[r.pos-4] != 'a' || r.Data[r.pos-3] != 'l' || r.Data[r.pos-2] != 's' || r.Data[r.pos-1] != 'e' || (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 5 r.errSyntax() } } // fetchNumber scans a number literal token. func (r *Lexer) fetchNumber() { hasE := false afterE := false hasDot := false r.pos++ for i, c := range r.Data[r.pos:] { switch { case c >= '0' && c <= '9': afterE = false case c == '.' && !hasDot: hasDot = true case (c == 'e' || c == 'E') && !hasE: hasE = true hasDot = true afterE = true case (c == '+' || c == '-') && afterE: afterE = false default: r.pos += i if !isTokenEnd(c) { r.errSyntax() } else { r.token.byteValue = r.Data[r.start:r.pos] } return } } r.pos = len(r.Data) r.token.byteValue = r.Data[r.start:] } // findStringLen tries to scan into the string literal for ending quote char to determine required size. // The size will be exact if no escapes are present and may be inexact if there are escaped chars. func findStringLen(data []byte) (isValid bool, length int) { for { idx := bytes.IndexByte(data, '"') if idx == -1 { return false, len(data) } if idx == 0 || (idx > 0 && data[idx-1] != '\\') { return true, length + idx } // count \\\\\\\ sequences. even number of slashes means quote is not really escaped cnt := 1 for idx-cnt-1 >= 0 && data[idx-cnt-1] == '\\' { cnt++ } if cnt%2 == 0 { return true, length + idx } length += idx + 1 data = data[idx+1:] } } // unescapeStringToken performs unescaping of string token. // if no escaping is needed, original string is returned, otherwise - a new one allocated func (r *Lexer) unescapeStringToken() (err error) { data := r.token.byteValue var unescapedData []byte for { i := bytes.IndexByte(data, '\\') if i == -1 { break } escapedRune, escapedBytes, err := decodeEscape(data[i:]) if err != nil { r.errParse(err.Error()) return err } if unescapedData == nil { unescapedData = make([]byte, 0, len(r.token.byteValue)) } var d [4]byte s := utf8.EncodeRune(d[:], escapedRune) unescapedData = append(unescapedData, data[:i]...) unescapedData = append(unescapedData, d[:s]...) data = data[i+escapedBytes:] } if unescapedData != nil { r.token.byteValue = append(unescapedData, data...) r.token.byteValueCloned = true } return } // getu4 decodes \uXXXX from the beginning of s, returning the hex value, // or it returns -1. func getu4(s []byte) rune { if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { return -1 } var val rune for i := 2; i < len(s) && i < 6; i++ { var v byte c := s[i] switch c { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': v = c - '0' case 'a', 'b', 'c', 'd', 'e', 'f': v = c - 'a' + 10 case 'A', 'B', 'C', 'D', 'E', 'F': v = c - 'A' + 10 default: return -1 } val <<= 4 val |= rune(v) } return val } // decodeEscape processes a single escape sequence and returns number of bytes processed. func decodeEscape(data []byte) (decoded rune, bytesProcessed int, err error) { if len(data) < 2 { return 0, 0, errors.New("incorrect escape symbol \\ at the end of token") } c := data[1] switch c { case '"', '/', '\\': return rune(c), 2, nil case 'b': return '\b', 2, nil case 'f': return '\f', 2, nil case 'n': return '\n', 2, nil case 'r': return '\r', 2, nil case 't': return '\t', 2, nil case 'u': rr := getu4(data) if rr < 0 { return 0, 0, errors.New("incorrectly escaped \\uXXXX sequence") } read := 6 if utf16.IsSurrogate(rr) { rr1 := getu4(data[read:]) if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { read += 6 rr = dec } else { rr = unicode.ReplacementChar } } return rr, read, nil } return 0, 0, errors.New("incorrectly escaped bytes") } // fetchString scans a string literal token. func (r *Lexer) fetchString() { r.pos++ data := r.Data[r.pos:] isValid, length := findStringLen(data) if !isValid { r.pos += length r.errParse("unterminated string literal") return } r.token.byteValue = data[:length] r.pos += length + 1 // skip closing '"' as well } // scanToken scans the next token if no token is currently available in the lexer. func (r *Lexer) scanToken() { if r.token.kind != tokenUndef || r.fatalError != nil { return } r.FetchToken() } // consume resets the current token to allow scanning the next one. func (r *Lexer) consume() { r.token.kind = tokenUndef r.token.delimValue = 0 } // Ok returns true if no error (including io.EOF) was encountered during scanning. func (r *Lexer) Ok() bool { return r.fatalError == nil } const maxErrorContextLen = 13 func (r *Lexer) errParse(what string) { if r.fatalError == nil { var str string if len(r.Data)-r.pos <= maxErrorContextLen { str = string(r.Data) } else { str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." } r.fatalError = &LexerError{ Reason: what, Offset: r.pos, Data: str, } } } func (r *Lexer) errSyntax() { r.errParse("syntax error") } func (r *Lexer) errInvalidToken(expected string) { if r.fatalError != nil { return } if r.UseMultipleErrors { r.pos = r.start r.consume() r.SkipRecursive() switch expected { case "[": r.token.delimValue = ']' r.token.kind = tokenDelim case "{": r.token.delimValue = '}' r.token.kind = tokenDelim } r.addNonfatalError(&LexerError{ Reason: fmt.Sprintf("expected %s", expected), Offset: r.start, Data: string(r.Data[r.start:r.pos]), }) return } var str string if len(r.token.byteValue) <= maxErrorContextLen { str = string(r.token.byteValue) } else { str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." } r.fatalError = &LexerError{ Reason: fmt.Sprintf("expected %s", expected), Offset: r.pos, Data: str, } } func (r *Lexer) GetPos() int { return r.pos } // Delim consumes a token and verifies that it is the given delimiter. func (r *Lexer) Delim(c byte) { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.delimValue != c { r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. r.errInvalidToken(string([]byte{c})) } else { r.consume() } } // IsDelim returns true if there was no scanning error and next token is the given delimiter. func (r *Lexer) IsDelim(c byte) bool { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } return !r.Ok() || r.token.delimValue == c } // Null verifies that the next token is null and consumes it. func (r *Lexer) Null() { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenNull { r.errInvalidToken("null") } r.consume() } // IsNull returns true if the next token is a null keyword. func (r *Lexer) IsNull() bool { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } return r.Ok() && r.token.kind == tokenNull } // Skip skips a single token. func (r *Lexer) Skip() { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } r.consume() } // SkipRecursive skips next array or object completely, or just skips a single token if not // an array/object. // // Note: no syntax validation is performed on the skipped data. func (r *Lexer) SkipRecursive() { r.scanToken() var start, end byte switch r.token.delimValue { case '{': start, end = '{', '}' case '[': start, end = '[', ']' default: r.consume() return } r.consume() level := 1 inQuotes := false wasEscape := false for i, c := range r.Data[r.pos:] { switch { case c == start && !inQuotes: level++ case c == end && !inQuotes: level-- if level == 0 { r.pos += i + 1 return } case c == '\\' && inQuotes: wasEscape = !wasEscape continue case c == '"' && inQuotes: inQuotes = wasEscape case c == '"': inQuotes = true } wasEscape = false } r.pos = len(r.Data) r.fatalError = &LexerError{ Reason: "EOF reached while skipping array/object or token", Offset: r.pos, Data: string(r.Data[r.pos:]), } } // Raw fetches the next item recursively as a data slice func (r *Lexer) Raw() []byte { r.SkipRecursive() if !r.Ok() { return nil } return r.Data[r.start:r.pos] } // IsStart returns whether the lexer is positioned at the start // of an input string. func (r *Lexer) IsStart() bool { return r.pos == 0 } // Consumed reads all remaining bytes from the input, publishing an error if // there is anything but whitespace remaining. func (r *Lexer) Consumed() { if r.pos > len(r.Data) || !r.Ok() { return } for _, c := range r.Data[r.pos:] { if c != ' ' && c != '\t' && c != '\r' && c != '\n' { r.AddError(&LexerError{ Reason: "invalid character '" + string(c) + "' after top-level value", Offset: r.pos, Data: string(r.Data[r.pos:]), }) return } r.pos++ r.start++ } } func (r *Lexer) unsafeString(skipUnescape bool) (string, []byte) { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenString { r.errInvalidToken("string") return "", nil } if !skipUnescape { if err := r.unescapeStringToken(); err != nil { r.errInvalidToken("string") return "", nil } } bytes := r.token.byteValue ret := bytesToStr(r.token.byteValue) r.consume() return ret, bytes } // UnsafeString returns the string value if the token is a string literal. // // Warning: returned string may point to the input buffer, so the string should not outlive // the input buffer. Intended pattern of usage is as an argument to a switch statement. func (r *Lexer) UnsafeString() string { ret, _ := r.unsafeString(false) return ret } // UnsafeBytes returns the byte slice if the token is a string literal. func (r *Lexer) UnsafeBytes() []byte { _, ret := r.unsafeString(false) return ret } // UnsafeFieldName returns current member name string token func (r *Lexer) UnsafeFieldName(skipUnescape bool) string { ret, _ := r.unsafeString(skipUnescape) return ret } // String reads a string literal. func (r *Lexer) String() string { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenString { r.errInvalidToken("string") return "" } if err := r.unescapeStringToken(); err != nil { r.errInvalidToken("string") return "" } var ret string if r.token.byteValueCloned { ret = bytesToStr(r.token.byteValue) } else { ret = string(r.token.byteValue) } r.consume() return ret } // StringIntern reads a string literal, and performs string interning on it. func (r *Lexer) StringIntern() string { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenString { r.errInvalidToken("string") return "" } if err := r.unescapeStringToken(); err != nil { r.errInvalidToken("string") return "" } ret := intern.Bytes(r.token.byteValue) r.consume() return ret } // Bytes reads a string literal and base64 decodes it into a byte slice. func (r *Lexer) Bytes() []byte { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenString { r.errInvalidToken("string") return nil } ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) n, err := base64.StdEncoding.Decode(ret, r.token.byteValue) if err != nil { r.fatalError = &LexerError{ Reason: err.Error(), } return nil } r.consume() return ret[:n] } // Bool reads a true or false boolean keyword. func (r *Lexer) Bool() bool { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenBool { r.errInvalidToken("bool") return false } ret := r.token.boolValue r.consume() return ret } func (r *Lexer) number() string { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() || r.token.kind != tokenNumber { r.errInvalidToken("number") return "" } ret := bytesToStr(r.token.byteValue) r.consume() return ret } func (r *Lexer) Uint8() uint8 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 8) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return uint8(n) } func (r *Lexer) Uint16() uint16 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 16) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return uint16(n) } func (r *Lexer) Uint32() uint32 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return uint32(n) } func (r *Lexer) Uint64() uint64 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return n } func (r *Lexer) Uint() uint { return uint(r.Uint64()) } func (r *Lexer) Int8() int8 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 8) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return int8(n) } func (r *Lexer) Int16() int16 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 16) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return int16(n) } func (r *Lexer) Int32() int32 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return int32(n) } func (r *Lexer) Int64() int64 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return n } func (r *Lexer) Int() int { return int(r.Int64()) } func (r *Lexer) Uint8Str() uint8 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 8) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return uint8(n) } func (r *Lexer) Uint16Str() uint16 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 16) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return uint16(n) } func (r *Lexer) Uint32Str() uint32 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return uint32(n) } func (r *Lexer) Uint64Str() uint64 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseUint(s, 10, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return n } func (r *Lexer) UintStr() uint { return uint(r.Uint64Str()) } func (r *Lexer) UintptrStr() uintptr { return uintptr(r.Uint64Str()) } func (r *Lexer) Int8Str() int8 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 8) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return int8(n) } func (r *Lexer) Int16Str() int16 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 16) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return int16(n) } func (r *Lexer) Int32Str() int32 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return int32(n) } func (r *Lexer) Int64Str() int64 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseInt(s, 10, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return n } func (r *Lexer) IntStr() int { return int(r.Int64Str()) } func (r *Lexer) Float32() float32 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseFloat(s, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return float32(n) } func (r *Lexer) Float32Str() float32 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseFloat(s, 32) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return float32(n) } func (r *Lexer) Float64() float64 { s := r.number() if !r.Ok() { return 0 } n, err := strconv.ParseFloat(s, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: s, }) } return n } func (r *Lexer) Float64Str() float64 { s, b := r.unsafeString(false) if !r.Ok() { return 0 } n, err := strconv.ParseFloat(s, 64) if err != nil { r.addNonfatalError(&LexerError{ Offset: r.start, Reason: err.Error(), Data: string(b), }) } return n } func (r *Lexer) Error() error { return r.fatalError } func (r *Lexer) AddError(e error) { if r.fatalError == nil { r.fatalError = e } } func (r *Lexer) AddNonFatalError(e error) { r.addNonfatalError(&LexerError{ Offset: r.start, Data: string(r.Data[r.start:r.pos]), Reason: e.Error(), }) } func (r *Lexer) addNonfatalError(err *LexerError) { if r.UseMultipleErrors { // We don't want to add errors with the same offset. if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { return } r.multipleErrors = append(r.multipleErrors, err) return } r.fatalError = err } func (r *Lexer) GetNonFatalErrors() []*LexerError { return r.multipleErrors } // JsonNumber fetches and json.Number from 'encoding/json' package. // Both int, float or string, contains them are valid values func (r *Lexer) JsonNumber() json.Number { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() { r.errInvalidToken("json.Number") return json.Number("") } switch r.token.kind { case tokenString: return json.Number(r.String()) case tokenNumber: return json.Number(r.Raw()) case tokenNull: r.Null() return json.Number("") default: r.errSyntax() return json.Number("") } } // Interface fetches an interface{} analogous to the 'encoding/json' package. func (r *Lexer) Interface() interface{} { if r.token.kind == tokenUndef && r.Ok() { r.FetchToken() } if !r.Ok() { return nil } switch r.token.kind { case tokenString: return r.String() case tokenNumber: return r.Float64() case tokenBool: return r.Bool() case tokenNull: r.Null() return nil } if r.token.delimValue == '{' { r.consume() ret := map[string]interface{}{} for !r.IsDelim('}') { key := r.String() r.WantColon() ret[key] = r.Interface() r.WantComma() } r.Delim('}') if r.Ok() { return ret } else { return nil } } else if r.token.delimValue == '[' { r.consume() ret := []interface{}{} for !r.IsDelim(']') { ret = append(ret, r.Interface()) r.WantComma() } r.Delim(']') if r.Ok() { return ret } else { return nil } } r.errSyntax() return nil } // WantComma requires a comma to be present before fetching next token. func (r *Lexer) WantComma() { r.wantSep = ',' r.firstElement = false } // WantColon requires a colon to be present before fetching next token. func (r *Lexer) WantColon() { r.wantSep = ':' r.firstElement = false } easyjson-0.7.6/jlexer/lexer_test.go000066400000000000000000000255741371475264500174100ustar00rootroot00000000000000package jlexer import ( "bytes" "encoding/json" "reflect" "testing" ) func TestString(t *testing.T) { for i, test := range []struct { toParse string want string wantError bool }{ {toParse: `"simple string"`, want: "simple string"}, {toParse: " \r\r\n\t " + `"test"`, want: "test"}, {toParse: `"\n\t\"\/\\\f\r"`, want: "\n\t\"/\\\f\r"}, {toParse: `"\u0020"`, want: " "}, {toParse: `"\u0020-\t"`, want: " -\t"}, {toParse: `"\ufffd\uFFFD"`, want: "\ufffd\ufffd"}, {toParse: `"\ud83d\ude00"`, want: "😀"}, {toParse: `"\ud83d\ude08"`, want: "😈"}, {toParse: `"\ud8"`, wantError: true}, {toParse: `"test"junk`, want: "test"}, {toParse: `5`, wantError: true}, // not a string {toParse: `"\x"`, wantError: true}, // invalid escape {toParse: `"\ud800"`, want: "�"}, // invalid utf-8 char; return replacement char } { { l := Lexer{Data: []byte(test.toParse)} got := l.String() if got != test.want { t.Errorf("[%d, %q] String() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] String() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] String() ok; want error", i, test.toParse) } } { l := Lexer{Data: []byte(test.toParse)} got := l.StringIntern() if got != test.want { t.Errorf("[%d, %q] String() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] String() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] String() ok; want error", i, test.toParse) } } } } func TestStringIntern(t *testing.T) { data := []byte(`"string interning test"`) var l Lexer allocsPerRun := testing.AllocsPerRun(1000, func() { l = Lexer{Data: data} _ = l.StringIntern() }) if allocsPerRun != 0 { t.Fatalf("expected 0 allocs, got %f", allocsPerRun) } allocsPerRun = testing.AllocsPerRun(1000, func() { l = Lexer{Data: data} _ = l.String() }) if allocsPerRun != 1 { t.Fatalf("expected 1 allocs, got %f", allocsPerRun) } } func TestBytes(t *testing.T) { for i, test := range []struct { toParse string want string wantError bool }{ {toParse: `"c2ltcGxlIHN0cmluZw=="`, want: "simple string"}, {toParse: " \r\r\n\t " + `"dGVzdA=="`, want: "test"}, {toParse: `5`, wantError: true}, // not a JSON string {toParse: `"foobar"`, wantError: true}, // not base64 encoded {toParse: `"c2ltcGxlIHN0cmluZw="`, wantError: true}, // invalid base64 padding } { l := Lexer{Data: []byte(test.toParse)} got := l.Bytes() if bytes.Compare(got, []byte(test.want)) != 0 { t.Errorf("[%d, %q] Bytes() = %v; want: %v", i, test.toParse, got, []byte(test.want)) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] Bytes() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] Bytes() ok; want error", i, test.toParse) } } } func TestNumber(t *testing.T) { for i, test := range []struct { toParse string want string wantError bool }{ {toParse: "123", want: "123"}, {toParse: "-123", want: "-123"}, {toParse: "\r\n12.35", want: "12.35"}, {toParse: "12.35e+1", want: "12.35e+1"}, {toParse: "12.35e-15", want: "12.35e-15"}, {toParse: "12.35E-15", want: "12.35E-15"}, {toParse: "12.35E15", want: "12.35E15"}, {toParse: `"a"`, wantError: true}, {toParse: "123junk", wantError: true}, {toParse: "1.2.3", wantError: true}, {toParse: "1e2e3", wantError: true}, {toParse: "1e2.3", wantError: true}, } { l := Lexer{Data: []byte(test.toParse)} got := l.number() if got != test.want { t.Errorf("[%d, %q] number() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] number() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] number() ok; want error", i, test.toParse) } } } func TestBool(t *testing.T) { for i, test := range []struct { toParse string want bool wantError bool }{ {toParse: "true", want: true}, {toParse: "false", want: false}, {toParse: "1", wantError: true}, {toParse: "truejunk", wantError: true}, {toParse: `false"junk"`, wantError: true}, {toParse: "True", wantError: true}, {toParse: "False", wantError: true}, } { l := Lexer{Data: []byte(test.toParse)} got := l.Bool() if got != test.want { t.Errorf("[%d, %q] Bool() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] Bool() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] Bool() ok; want error", i, test.toParse) } } } func TestSkipRecursive(t *testing.T) { for i, test := range []struct { toParse string left string wantError bool }{ {toParse: "5, 4", left: ", 4"}, {toParse: "[5, 6], 4", left: ", 4"}, {toParse: "[5, [7,8]]: 4", left: ": 4"}, {toParse: `{"a":1}, 4`, left: ", 4"}, {toParse: `{"a":1, "b":{"c": 5}, "e":[12,15]}, 4`, left: ", 4"}, // array start/end chars in a string {toParse: `[5, "]"], 4`, left: ", 4"}, {toParse: `[5, "\"]"], 4`, left: ", 4"}, {toParse: `[5, "["], 4`, left: ", 4"}, {toParse: `[5, "\"["], 4`, left: ", 4"}, // object start/end chars in a string {toParse: `{"a}":1}, 4`, left: ", 4"}, {toParse: `{"a\"}":1}, 4`, left: ", 4"}, {toParse: `{"a{":1}, 4`, left: ", 4"}, {toParse: `{"a\"{":1}, 4`, left: ", 4"}, // object with double slashes at the end of string {toParse: `{"a":"hey\\"}, 4`, left: ", 4"}, } { l := Lexer{Data: []byte(test.toParse)} l.SkipRecursive() got := string(l.Data[l.pos:]) if got != test.left { t.Errorf("[%d, %q] SkipRecursive() left = %v; want %v", i, test.toParse, got, test.left) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] SkipRecursive() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] SkipRecursive() ok; want error", i, test.toParse) } } } func TestInterface(t *testing.T) { for i, test := range []struct { toParse string want interface{} wantError bool }{ {toParse: "null", want: nil}, {toParse: "true", want: true}, {toParse: `"a"`, want: "a"}, {toParse: "5", want: float64(5)}, {toParse: `{}`, want: map[string]interface{}{}}, {toParse: `[]`, want: []interface{}{}}, {toParse: `{"a": "b"}`, want: map[string]interface{}{"a": "b"}}, {toParse: `[5]`, want: []interface{}{float64(5)}}, {toParse: `{"a":5 , "b" : "string"}`, want: map[string]interface{}{"a": float64(5), "b": "string"}}, {toParse: `["a", 5 , null, true]`, want: []interface{}{"a", float64(5), nil, true}}, {toParse: `{"a" "b"}`, wantError: true}, {toParse: `{"a": "b",}`, wantError: true}, {toParse: `{"a":"b","c" "b"}`, wantError: true}, {toParse: `{"a": "b","c":"d",}`, wantError: true}, {toParse: `{,}`, wantError: true}, {toParse: `[1, 2,]`, wantError: true}, {toParse: `[1 2]`, wantError: true}, {toParse: `[,]`, wantError: true}, } { l := Lexer{Data: []byte(test.toParse)} got := l.Interface() if !reflect.DeepEqual(got, test.want) { t.Errorf("[%d, %q] Interface() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] Interface() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] Interface() ok; want error", i, test.toParse) } } } func TestConsumed(t *testing.T) { for i, test := range []struct { toParse string wantError bool }{ {toParse: "", wantError: false}, {toParse: " ", wantError: false}, {toParse: "\r\n", wantError: false}, {toParse: "\t\t", wantError: false}, {toParse: "{", wantError: true}, } { l := Lexer{Data: []byte(test.toParse)} l.Consumed() err := l.Error() if err != nil && !test.wantError { t.Errorf("[%d, %q] Consumed() error: %v", i, test.toParse, err) } else if err == nil && test.wantError { t.Errorf("[%d, %q] Consumed() ok; want error", i, test.toParse) } } } func TestJsonNumber(t *testing.T) { for i, test := range []struct { toParse string want json.Number wantLexerError bool wantValue interface{} wantValueError bool }{ {toParse: `10`, want: json.Number("10"), wantValue: int64(10)}, {toParse: `0`, want: json.Number("0"), wantValue: int64(0)}, {toParse: `0.12`, want: json.Number("0.12"), wantValue: 0.12}, {toParse: `25E-4`, want: json.Number("25E-4"), wantValue: 25e-4}, {toParse: `"10"`, want: json.Number("10"), wantValue: int64(10)}, {toParse: `"0"`, want: json.Number("0"), wantValue: int64(0)}, {toParse: `"0.12"`, want: json.Number("0.12"), wantValue: 0.12}, {toParse: `"25E-4"`, want: json.Number("25E-4"), wantValue: 25e-4}, {toParse: `"foo"`, want: json.Number("foo"), wantValueError: true}, {toParse: `null`, want: json.Number(""), wantValueError: true}, {toParse: `"a""`, want: json.Number("a"), wantValueError: true}, {toParse: `[1]`, want: json.Number(""), wantLexerError: true, wantValueError: true}, {toParse: `{}`, want: json.Number(""), wantLexerError: true, wantValueError: true}, {toParse: `a`, want: json.Number(""), wantLexerError: true, wantValueError: true}, } { l := Lexer{Data: []byte(test.toParse)} got := l.JsonNumber() if got != test.want { t.Errorf("[%d, %q] JsonNumber() = %v; want %v", i, test.toParse, got, test.want) } err := l.Error() if err != nil && !test.wantLexerError { t.Errorf("[%d, %q] JsonNumber() lexer error: %v", i, test.toParse, err) } else if err == nil && test.wantLexerError { t.Errorf("[%d, %q] JsonNumber() ok; want lexer error", i, test.toParse) } var valueErr error var gotValue interface{} switch test.wantValue.(type) { case float64: gotValue, valueErr = got.Float64() default: gotValue, valueErr = got.Int64() } if !reflect.DeepEqual(gotValue, test.wantValue) && !test.wantLexerError && !test.wantValueError { t.Errorf("[%d, %q] JsonNumber() = %v; want %v", i, test.toParse, gotValue, test.wantValue) } if valueErr != nil && !test.wantValueError { t.Errorf("[%d, %q] JsonNumber() value error: %v", i, test.toParse, valueErr) } else if valueErr == nil && test.wantValueError { t.Errorf("[%d, %q] JsonNumber() ok; want value error", i, test.toParse) } } } func TestFetchStringUnterminatedString(t *testing.T) { for _, test := range []struct { data []byte }{ {data: []byte(`"sting without trailing quote`)}, {data: []byte(`"\"`)}, {data: []byte{'"'}}, } { l := Lexer{Data: test.data} l.fetchString() if l.pos > len(l.Data) { t.Errorf("fetchString(%s): pos=%v should not be greater than length of Data = %v", test.data, l.pos, len(l.Data)) } if l.Error() == nil { t.Errorf("fetchString(%s): should add parsing error", test.data) } } } easyjson-0.7.6/jwriter/000077500000000000000000000000001371475264500150635ustar00rootroot00000000000000easyjson-0.7.6/jwriter/writer.go000066400000000000000000000235571371475264500167420ustar00rootroot00000000000000// Package jwriter contains a JSON writer. package jwriter import ( "io" "strconv" "unicode/utf8" "github.com/mailru/easyjson/buffer" ) // Flags describe various encoding options. The behavior may be actually implemented in the encoder, but // Flags field in Writer is used to set and pass them around. type Flags int const ( NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. ) // Writer is a JSON writer. type Writer struct { Flags Flags Error error Buffer buffer.Buffer NoEscapeHTML bool } // Size returns the size of the data that was written out. func (w *Writer) Size() int { return w.Buffer.Size() } // DumpTo outputs the data to given io.Writer, resetting the buffer. func (w *Writer) DumpTo(out io.Writer) (written int, err error) { return w.Buffer.DumpTo(out) } // BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice // as argument that it will try to reuse. func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.BuildBytes(reuse...), nil } // ReadCloser returns an io.ReadCloser that can be used to read the data. // ReadCloser also resets the buffer. func (w *Writer) ReadCloser() (io.ReadCloser, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.ReadCloser(), nil } // RawByte appends raw binary data to the buffer. func (w *Writer) RawByte(c byte) { w.Buffer.AppendByte(c) } // RawByte appends raw binary data to the buffer. func (w *Writer) RawString(s string) { w.Buffer.AppendString(s) } // Raw appends raw binary data to the buffer or sets the error if it is given. Useful for // calling with results of MarshalJSON-like functions. func (w *Writer) Raw(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.Buffer.AppendBytes(data) default: w.RawString("null") } } // RawText encloses raw binary data in quotes and appends in to the buffer. // Useful for calling with results of MarshalText-like functions. func (w *Writer) RawText(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.String(string(data)) default: w.RawString("null") } } // Base64Bytes appends data to the buffer after base64 encoding it func (w *Writer) Base64Bytes(data []byte) { if data == nil { w.Buffer.AppendString("null") return } w.Buffer.AppendByte('"') w.base64(data) w.Buffer.AppendByte('"') } func (w *Writer) Uint8(n uint8) { w.Buffer.EnsureSpace(3) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint16(n uint16) { w.Buffer.EnsureSpace(5) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint32(n uint32) { w.Buffer.EnsureSpace(10) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint(n uint) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint64(n uint64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) } func (w *Writer) Int8(n int8) { w.Buffer.EnsureSpace(4) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int16(n int16) { w.Buffer.EnsureSpace(6) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int32(n int32) { w.Buffer.EnsureSpace(11) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int(n int) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int64(n int64) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) } func (w *Writer) Uint8Str(n uint8) { w.Buffer.EnsureSpace(3) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint16Str(n uint16) { w.Buffer.EnsureSpace(5) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint32Str(n uint32) { w.Buffer.EnsureSpace(10) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) UintStr(n uint) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint64Str(n uint64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) UintptrStr(n uintptr) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int8Str(n int8) { w.Buffer.EnsureSpace(4) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int16Str(n int16) { w.Buffer.EnsureSpace(6) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int32Str(n int32) { w.Buffer.EnsureSpace(11) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) IntStr(n int) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int64Str(n int64) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Float32(n float32) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) } func (w *Writer) Float32Str(n float32) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Float64(n float64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) } func (w *Writer) Float64Str(n float64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Bool(v bool) { w.Buffer.EnsureSpace(5) if v { w.Buffer.Buf = append(w.Buffer.Buf, "true"...) } else { w.Buffer.Buf = append(w.Buffer.Buf, "false"...) } } const chars = "0123456789abcdef" func getTable(falseValues ...int) [128]bool { table := [128]bool{} for i := 0; i < 128; i++ { table[i] = true } for _, v := range falseValues { table[v] = false } return table } var ( htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\') htmlNoEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '\\') ) func (w *Writer) String(s string) { w.Buffer.AppendByte('"') // Portions of the string that contain no escapes are appended as // byte slices. p := 0 // last non-escape symbol escapeTable := &htmlEscapeTable if w.NoEscapeHTML { escapeTable = &htmlNoEscapeTable } for i := 0; i < len(s); { c := s[i] if c < utf8.RuneSelf { if escapeTable[c] { // single-width character, no escaping is required i++ continue } w.Buffer.AppendString(s[p:i]) switch c { case '\t': w.Buffer.AppendString(`\t`) case '\r': w.Buffer.AppendString(`\r`) case '\n': w.Buffer.AppendString(`\n`) case '\\': w.Buffer.AppendString(`\\`) case '"': w.Buffer.AppendString(`\"`) default: w.Buffer.AppendString(`\u00`) w.Buffer.AppendByte(chars[c>>4]) w.Buffer.AppendByte(chars[c&0xf]) } i++ p = i continue } // broken utf runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) if runeValue == utf8.RuneError && runeWidth == 1 { w.Buffer.AppendString(s[p:i]) w.Buffer.AppendString(`\ufffd`) i++ p = i continue } // jsonp stuff - tab separator and line separator if runeValue == '\u2028' || runeValue == '\u2029' { w.Buffer.AppendString(s[p:i]) w.Buffer.AppendString(`\u202`) w.Buffer.AppendByte(chars[runeValue&0xf]) i += runeWidth p = i continue } i += runeWidth } w.Buffer.AppendString(s[p:]) w.Buffer.AppendByte('"') } const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" const padChar = '=' func (w *Writer) base64(in []byte) { if len(in) == 0 { return } w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) si := 0 n := (len(in) / 3) * 3 for si < n { // Convert 3x 8bit source bytes into 4 bytes val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) si += 3 } remain := len(in) - si if remain == 0 { return } // Add the remaining small block val := uint(in[si+0]) << 16 if remain == 2 { val |= uint(in[si+1]) << 8 } w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) switch remain { case 2: w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) case 1: w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) } } easyjson-0.7.6/opt/000077500000000000000000000000001371475264500141775ustar00rootroot00000000000000easyjson-0.7.6/opt/gotemplate_Bool.go000066400000000000000000000032641371475264500176470ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Bool struct { V bool Defined bool } // Creates an optional type with a given value. func OBool(v bool) Bool { return Bool{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Bool) Get(deflt bool) bool { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Bool) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Bool(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Bool) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Bool{} } else { v.V = l.Bool() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Bool) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Bool) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Bool) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Bool) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Float32.go000066400000000000000000000033521371475264500201640ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Float32 struct { V float32 Defined bool } // Creates an optional type with a given value. func OFloat32(v float32) Float32 { return Float32{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Float32) Get(deflt float32) float32 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Float32) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Float32(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Float32) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Float32{} } else { v.V = l.Float32() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Float32) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Float32) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Float32) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Float32) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Float64.go000066400000000000000000000033521371475264500201710ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Float64 struct { V float64 Defined bool } // Creates an optional type with a given value. func OFloat64(v float64) Float64 { return Float64{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Float64) Get(deflt float64) float64 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Float64) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Float64(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Float64) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Float64{} } else { v.V = l.Float64() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Float64) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Float64) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Float64) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Float64) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Int.go000066400000000000000000000032421371475264500175020ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int struct { V int Defined bool } // Creates an optional type with a given value. func OInt(v int) Int { return Int{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int) Get(deflt int) int { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int{} } else { v.V = l.Int() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Int) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Int) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Int16.go000066400000000000000000000033061371475264500176520ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int16 struct { V int16 Defined bool } // Creates an optional type with a given value. func OInt16(v int16) Int16 { return Int16{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int16) Get(deflt int16) int16 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int16) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int16(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int16) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int16{} } else { v.V = l.Int16() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Int16) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Int16) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int16) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int16) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Int32.go000066400000000000000000000033061371475264500176500ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int32 struct { V int32 Defined bool } // Creates an optional type with a given value. func OInt32(v int32) Int32 { return Int32{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int32) Get(deflt int32) int32 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int32) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int32(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int32) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int32{} } else { v.V = l.Int32() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Int32) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Int32) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int32) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int32) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Int64.go000066400000000000000000000033061371475264500176550ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int64 struct { V int64 Defined bool } // Creates an optional type with a given value. func OInt64(v int64) Int64 { return Int64{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int64) Get(deflt int64) int64 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int64) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int64(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int64) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int64{} } else { v.V = l.Int64() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Int64) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Int64) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int64) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int64) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Int8.go000066400000000000000000000032641371475264500175760ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Int8 struct { V int8 Defined bool } // Creates an optional type with a given value. func OInt8(v int8) Int8 { return Int8{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Int8) Get(deflt int8) int8 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Int8) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Int8(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Int8) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Int8{} } else { v.V = l.Int8() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Int8) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Int8) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Int8) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Int8) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_String.go000066400000000000000000000033301371475264500202140ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type String struct { V string Defined bool } // Creates an optional type with a given value. func OString(v string) String { return String{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v String) Get(deflt string) string { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v String) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.String(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *String) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = String{} } else { v.V = l.String() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v String) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *String) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v String) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v String) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Uint.go000066400000000000000000000032641371475264500176730ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Uint struct { V uint Defined bool } // Creates an optional type with a given value. func OUint(v uint) Uint { return Uint{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Uint) Get(deflt uint) uint { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Uint) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Uint(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Uint) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Uint{} } else { v.V = l.Uint() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Uint) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Uint) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Uint) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Uint) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Uint16.go000066400000000000000000000033301371475264500200340ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Uint16 struct { V uint16 Defined bool } // Creates an optional type with a given value. func OUint16(v uint16) Uint16 { return Uint16{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Uint16) Get(deflt uint16) uint16 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Uint16) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Uint16(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Uint16) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Uint16{} } else { v.V = l.Uint16() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Uint16) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Uint16) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Uint16) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Uint16) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Uint32.go000066400000000000000000000033301371475264500200320ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Uint32 struct { V uint32 Defined bool } // Creates an optional type with a given value. func OUint32(v uint32) Uint32 { return Uint32{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Uint32) Get(deflt uint32) uint32 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Uint32) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Uint32(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Uint32) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Uint32{} } else { v.V = l.Uint32() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Uint32) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Uint32) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Uint32) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Uint32) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Uint64.go000066400000000000000000000033301371475264500200370ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Uint64 struct { V uint64 Defined bool } // Creates an optional type with a given value. func OUint64(v uint64) Uint64 { return Uint64{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Uint64) Get(deflt uint64) uint64 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Uint64) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Uint64(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Uint64) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Uint64{} } else { v.V = l.Uint64() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Uint64) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Uint64) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Uint64) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Uint64) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/gotemplate_Uint8.go000066400000000000000000000033061371475264500177600ustar00rootroot00000000000000// generated by gotemplate package opt import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) // A 'gotemplate'-based type for providing optional semantics without using pointers. type Uint8 struct { V uint8 Defined bool } // Creates an optional type with a given value. func OUint8(v uint8) Uint8 { return Uint8{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Uint8) Get(deflt uint8) uint8 { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Uint8) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Uint8(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Uint8) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Uint8{} } else { v.V = l.Uint8() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Uint8) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Uint8) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Uint8) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Uint8) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/optional/000077500000000000000000000000001371475264500160245ustar00rootroot00000000000000easyjson-0.7.6/opt/optional/opt.go000066400000000000000000000033441371475264500171610ustar00rootroot00000000000000// +build none package optional import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // template type Optional(A) type A int // A 'gotemplate'-based type for providing optional semantics without using pointers. type Optional struct { V A Defined bool } // Creates an optional type with a given value. func OOptional(v A) Optional { return Optional{V: v, Defined: true} } // Get returns the value or given default in the case the value is undefined. func (v Optional) Get(deflt A) A { if !v.Defined { return deflt } return v.V } // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v Optional) MarshalEasyJSON(w *jwriter.Writer) { if v.Defined { w.Optional(v.V) } else { w.RawString("null") } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *Optional) UnmarshalEasyJSON(l *jlexer.Lexer) { if l.IsNull() { l.Skip() *v = Optional{} } else { v.V = l.Optional() v.Defined = true } } // MarshalJSON implements a standard json marshaler interface. func (v Optional) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error } // UnmarshalJSON implements a standard json unmarshaler interface. func (v *Optional) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() } // IsDefined returns whether the value is defined, a function is required so that it can // be used in an interface. func (v Optional) IsDefined() bool { return v.Defined } // String implements a stringer interface using fmt.Sprint for the value. func (v Optional) String() string { if !v.Defined { return "" } return fmt.Sprint(v.V) } easyjson-0.7.6/opt/opts.go000066400000000000000000000024251371475264500155160ustar00rootroot00000000000000package opt //go:generate sed -i "s/\\+build none/generated by gotemplate/" optional/opt.go //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int(int) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint(uint) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int8(int8) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int16(int16) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int32(int32) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int64(int64) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint8(uint8) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint16(uint16) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint32(uint32) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint64(uint64) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float32(float32) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float64(float64) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Bool(bool) //go:generate gotemplate "github.com/mailru/easyjson/opt/optional" String(string) //go:generate sed -i "s/generated by gotemplate/+build none/" optional/opt.go easyjson-0.7.6/parser/000077500000000000000000000000001371475264500146715ustar00rootroot00000000000000easyjson-0.7.6/parser/modulepath.go000066400000000000000000000052411371475264500173640ustar00rootroot00000000000000package parser import ( "bytes" "strconv" ) // Content of this file was copied from the package golang.org/x/mod/modfile // https://github.com/golang/mod/blob/v0.2.0/modfile/read.go#L877 // Under the BSD-3-Clause licence: // golang.org/x/mod@v0.2.0/LICENSE /* Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var ( slashSlash = []byte("//") moduleStr = []byte("module") ) // modulePath returns the module path from the gomod file text. // If it cannot find a module path, it returns an empty string. // It is tolerant of unrelated problems in the go.mod file. func modulePath(mod []byte) string { for len(mod) > 0 { line := mod mod = nil if i := bytes.IndexByte(line, '\n'); i >= 0 { line, mod = line[:i], line[i+1:] } if i := bytes.Index(line, slashSlash); i >= 0 { line = line[:i] } line = bytes.TrimSpace(line) if !bytes.HasPrefix(line, moduleStr) { continue } line = line[len(moduleStr):] n := len(line) line = bytes.TrimSpace(line) if len(line) == n || len(line) == 0 { continue } if line[0] == '"' || line[0] == '`' { p, err := strconv.Unquote(string(line)) if err != nil { return "" // malformed quoted string or multiline module path } return p } return string(line) } return "" // missing module path } easyjson-0.7.6/parser/parser.go000066400000000000000000000046421371475264500165220ustar00rootroot00000000000000package parser import ( "go/ast" "go/parser" "go/token" "os" "strings" ) const ( structComment = "easyjson:json" structSkipComment = "easyjson:skip" ) type Parser struct { PkgPath string PkgName string StructNames []string AllStructs bool } type visitor struct { *Parser name string } func (p *Parser) needType(comments *ast.CommentGroup) (skip, explicit bool) { if comments == nil { return } for _, v := range comments.List { comment := v.Text if len(comment) > 2 { switch comment[1] { case '/': // -style comment (no newline at the end) comment = comment[2:] case '*': /*-style comment */ comment = comment[2 : len(comment)-2] } } for _, comment := range strings.Split(comment, "\n") { comment = strings.TrimSpace(comment) if strings.HasPrefix(comment, structSkipComment) { return true, false } if strings.HasPrefix(comment, structComment) { return false, true } } } return } func (v *visitor) Visit(n ast.Node) (w ast.Visitor) { switch n := n.(type) { case *ast.Package: return v case *ast.File: v.PkgName = n.Name.String() return v case *ast.GenDecl: skip, explicit := v.needType(n.Doc) if skip || explicit { for _, nc := range n.Specs { switch nct := nc.(type) { case *ast.TypeSpec: nct.Doc = n.Doc } } } return v case *ast.TypeSpec: skip, explicit := v.needType(n.Doc) if skip { return nil } if !explicit && !v.AllStructs { return nil } v.name = n.Name.String() // Allow to specify non-structs explicitly independent of '-all' flag. if explicit { v.StructNames = append(v.StructNames, v.name) return nil } return v case *ast.StructType: v.StructNames = append(v.StructNames, v.name) return nil } return nil } func (p *Parser) Parse(fname string, isDir bool) error { var err error if p.PkgPath, err = getPkgPath(fname, isDir); err != nil { return err } fset := token.NewFileSet() if isDir { packages, err := parser.ParseDir(fset, fname, excludeTestFiles, parser.ParseComments) if err != nil { return err } for _, pckg := range packages { ast.Walk(&visitor{Parser: p}, pckg) } } else { f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments) if err != nil { return err } ast.Walk(&visitor{Parser: p}, f) } return nil } func excludeTestFiles(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") } easyjson-0.7.6/parser/pkgpath.go000066400000000000000000000057261371475264500166700ustar00rootroot00000000000000package parser import ( "bytes" "fmt" "go/build" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "sync" ) func getPkgPath(fname string, isDir bool) (string, error) { if !filepath.IsAbs(fname) { pwd, err := os.Getwd() if err != nil { return "", err } fname = filepath.Join(pwd, fname) } goModPath, _ := goModPath(fname, isDir) if strings.Contains(goModPath, "go.mod") { pkgPath, err := getPkgPathFromGoMod(fname, isDir, goModPath) if err != nil { return "", err } return pkgPath, nil } return getPkgPathFromGOPATH(fname, isDir) } var goModPathCache = struct { paths map[string]string sync.RWMutex }{ paths: make(map[string]string), } // empty if no go.mod, GO111MODULE=off or go without go modules support func goModPath(fname string, isDir bool) (string, error) { root := fname if !isDir { root = filepath.Dir(fname) } goModPathCache.RLock() goModPath, ok := goModPathCache.paths[root] goModPathCache.RUnlock() if ok { return goModPath, nil } defer func() { goModPathCache.Lock() goModPathCache.paths[root] = goModPath goModPathCache.Unlock() }() cmd := exec.Command("go", "env", "GOMOD") cmd.Dir = root stdout, err := cmd.Output() if err != nil { return "", err } goModPath = string(bytes.TrimSpace(stdout)) return goModPath, nil } func getPkgPathFromGoMod(fname string, isDir bool, goModPath string) (string, error) { modulePath := getModulePath(goModPath) if modulePath == "" { return "", fmt.Errorf("cannot determine module path from %s", goModPath) } rel := path.Join(modulePath, filePathToPackagePath(strings.TrimPrefix(fname, filepath.Dir(goModPath)))) if !isDir { return path.Dir(rel), nil } return path.Clean(rel), nil } var pkgPathFromGoModCache = struct { paths map[string]string sync.RWMutex }{ paths: make(map[string]string), } func getModulePath(goModPath string) string { pkgPathFromGoModCache.RLock() pkgPath, ok := pkgPathFromGoModCache.paths[goModPath] pkgPathFromGoModCache.RUnlock() if ok { return pkgPath } defer func() { pkgPathFromGoModCache.Lock() pkgPathFromGoModCache.paths[goModPath] = pkgPath pkgPathFromGoModCache.Unlock() }() data, err := ioutil.ReadFile(goModPath) if err != nil { return "" } pkgPath = modulePath(data) return pkgPath } func getPkgPathFromGOPATH(fname string, isDir bool) (string, error) { gopath := os.Getenv("GOPATH") if gopath == "" { gopath = build.Default.GOPATH } for _, p := range strings.Split(gopath, string(filepath.ListSeparator)) { prefix := filepath.Join(p, "src") + string(filepath.Separator) rel, err := filepath.Rel(prefix, fname) if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { if !isDir { return path.Dir(filePathToPackagePath(rel)), nil } else { return path.Clean(filePathToPackagePath(rel)), nil } } } return "", fmt.Errorf("file '%v' is not in GOPATH '%v'", fname, gopath) } func filePathToPackagePath(path string) string { return filepath.ToSlash(path) } easyjson-0.7.6/parser/pkgpath_test.go000066400000000000000000000017471371475264500177260ustar00rootroot00000000000000package parser import "testing" func Test_getModulePath(t *testing.T) { tests := map[string]struct { goModPath string want string }{ "valid go.mod without comments and deps": { goModPath: "./testdata/default.go.mod", want: "example.com/user/project", }, "valid go.mod with comments and without deps": { goModPath: "./testdata/comments.go.mod", want: "example.com/user/project", }, "valid go.mod with comments and deps": { goModPath: "./testdata/comments_deps.go.mod", want: "example.com/user/project", }, "actual easyjson go.mod": { goModPath: "../go.mod", want: "github.com/mailru/easyjson", }, "invalid go.mod with missing module": { goModPath: "./testdata/missing_module.go", want: "", }, } for name := range tests { tt := tests[name] t.Run(name, func(t *testing.T) { if got := getModulePath(tt.goModPath); got != tt.want { t.Errorf("getModulePath() = %v, want %v", got, tt.want) } }) } } easyjson-0.7.6/parser/testdata/000077500000000000000000000000001371475264500165025ustar00rootroot00000000000000easyjson-0.7.6/parser/testdata/comments.go.mod000066400000000000000000000002171371475264500214340ustar00rootroot00000000000000// first-line comment which should bresk anything module example.com/user/project // end-line comment which should not break anything go 1.13 easyjson-0.7.6/parser/testdata/comments_deps.go.mod000066400000000000000000000002771371475264500224550ustar00rootroot00000000000000// first-line comment which should bresk anything module example.com/user/project // end-line comment which should not break anything go 1.13 require ( github.com/mailru/easyjson v0.7.0 ) easyjson-0.7.6/parser/testdata/default.go.mod000066400000000000000000000000511371475264500212270ustar00rootroot00000000000000module example.com/user/project go 1.13 easyjson-0.7.6/parser/testdata/missing_module.go.mod000066400000000000000000000000711371475264500226230ustar00rootroot00000000000000 go 1.13 require ( github.com/mailru/easyjson v0.7.0 ) easyjson-0.7.6/raw.go000066400000000000000000000021511371475264500145140ustar00rootroot00000000000000package easyjson import ( "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // RawMessage is a raw piece of JSON (number, string, bool, object, array or // null) that is extracted without parsing and output as is during marshaling. type RawMessage []byte // MarshalEasyJSON does JSON marshaling using easyjson interface. func (v *RawMessage) MarshalEasyJSON(w *jwriter.Writer) { if len(*v) == 0 { w.RawString("null") } else { w.Raw(*v, nil) } } // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) { *v = RawMessage(l.Raw()) } // UnmarshalJSON implements encoding/json.Unmarshaler interface. func (v *RawMessage) UnmarshalJSON(data []byte) error { *v = data return nil } var nullBytes = []byte("null") // MarshalJSON implements encoding/json.Marshaler interface. func (v RawMessage) MarshalJSON() ([]byte, error) { if len(v) == 0 { return nullBytes, nil } return v, nil } // IsDefined is required for integration with omitempty easyjson logic. func (v *RawMessage) IsDefined() bool { return len(*v) > 0 } easyjson-0.7.6/tests/000077500000000000000000000000001371475264500145375ustar00rootroot00000000000000easyjson-0.7.6/tests/basic_test.go000066400000000000000000000207431371475264500172140ustar00rootroot00000000000000package tests import ( "bytes" "encoding/json" "net/http/httptest" "reflect" "testing" "github.com/mailru/easyjson" "github.com/mailru/easyjson/jwriter" ) type testType interface { json.Marshaler json.Unmarshaler } var testCases = []struct { Decoded testType Encoded string }{ {&primitiveTypesValue, primitiveTypesString}, {&namedPrimitiveTypesValue, namedPrimitiveTypesString}, {&structsValue, structsString}, {&omitEmptyValue, omitEmptyString}, {&snakeStructValue, snakeStructString}, {&omitEmptyDefaultValue, omitEmptyDefaultString}, {&optsValue, optsString}, {&rawValue, rawString}, {&stdMarshalerValue, stdMarshalerString}, {&userMarshalerValue, userMarshalerString}, {&unexportedStructValue, unexportedStructString}, {&excludedFieldValue, excludedFieldString}, {&sliceValue, sliceString}, {&arrayValue, arrayString}, {&mapsValue, mapsString}, {&deepNestValue, deepNestString}, {&IntsValue, IntsString}, {&mapStringStringValue, mapStringStringString}, {&namedTypeValue, namedTypeValueString}, {&customMapKeyTypeValue, customMapKeyTypeValueString}, {&embeddedTypeValue, embeddedTypeValueString}, {&mapMyIntStringValue, mapMyIntStringValueString}, {&mapIntStringValue, mapIntStringValueString}, {&mapInt32StringValue, mapInt32StringValueString}, {&mapInt64StringValue, mapInt64StringValueString}, {&mapUintStringValue, mapUintStringValueString}, {&mapUint32StringValue, mapUint32StringValueString}, {&mapUint64StringValue, mapUint64StringValueString}, {&mapUintptrStringValue, mapUintptrStringValueString}, {&intKeyedMapStructValue, intKeyedMapStructValueString}, {&intArrayStructValue, intArrayStructValueString}, {&myUInt8SliceValue, myUInt8SliceString}, {&myUInt8ArrayValue, myUInt8ArrayString}, {&mapWithEncodingMarshaler, mapWithEncodingMarshalerString}, {&myGenDeclaredValue, myGenDeclaredString}, {&myGenDeclaredWithCommentValue, myGenDeclaredWithCommentString}, {&myTypeDeclaredValue, myTypeDeclaredString}, {&myTypeNotSkippedValue, myTypeNotSkippedString}, {&intern, internString}, } func TestMarshal(t *testing.T) { for i, test := range testCases { data, err := test.Decoded.MarshalJSON() if err != nil { t.Errorf("[%d, %T] MarshalJSON() error: %v", i, test.Decoded, err) } got := string(data) if got != test.Encoded { t.Errorf("[%d, %T] MarshalJSON(): got \n%v\n\t\t want \n%v", i, test.Decoded, got, test.Encoded) } } } func TestUnmarshal(t *testing.T) { for i, test := range testCases { v1 := reflect.New(reflect.TypeOf(test.Decoded).Elem()).Interface() v := v1.(testType) err := v.UnmarshalJSON([]byte(test.Encoded)) if err != nil { t.Errorf("[%d, %T] UnmarshalJSON() error: %v", i, test.Decoded, err) } if !reflect.DeepEqual(v, test.Decoded) { t.Errorf("[%d, %T] UnmarshalJSON(): got \n%+v\n\t\t want \n%+v", i, test.Decoded, v, test.Decoded) } } } func TestRawMessageSTD(t *testing.T) { type T struct { F easyjson.RawMessage Fnil easyjson.RawMessage } val := T{F: easyjson.RawMessage([]byte(`"test"`))} str := `{"F":"test","Fnil":null}` data, err := json.Marshal(val) if err != nil { t.Errorf("json.Marshal() error: %v", err) } got := string(data) if got != str { t.Errorf("json.Marshal() = %v; want %v", got, str) } wantV := T{F: easyjson.RawMessage([]byte(`"test"`)), Fnil: easyjson.RawMessage([]byte("null"))} var gotV T err = json.Unmarshal([]byte(str), &gotV) if err != nil { t.Errorf("json.Unmarshal() error: %v", err) } if !reflect.DeepEqual(gotV, wantV) { t.Errorf("json.Unmarshal() = %v; want %v", gotV, wantV) } } func TestParseNull(t *testing.T) { var got, want SubStruct if err := easyjson.Unmarshal([]byte("null"), &got); err != nil { t.Errorf("Unmarshal() error: %v", err) } if !reflect.DeepEqual(got, want) { t.Errorf("Unmarshal() = %+v; want %+v", got, want) } } var testSpecialCases = []struct { EncodedString string Value string }{ {`"Username \u003cuser@example.com\u003e"`, `Username `}, {`"Username\ufffd"`, "Username\xc5"}, {`"тестzтест"`, "тестzтест"}, {`"тест\ufffdтест"`, "тест\xc5тест"}, {`"绿茶"`, "绿茶"}, {`"绿\ufffd茶"`, "绿\xc5茶"}, {`"тест\u2028"`, "тест\xE2\x80\xA8"}, {`"\\\r\n\t\""`, "\\\r\n\t\""}, {`"text\\\""`, "text\\\""}, {`"ü"`, "ü"}, } func TestSpecialCases(t *testing.T) { for i, test := range testSpecialCases { w := jwriter.Writer{} w.String(test.Value) got := string(w.Buffer.BuildBytes()) if got != test.EncodedString { t.Errorf("[%d] Encoded() = %+v; want %+v", i, got, test.EncodedString) } } } func TestOverflowArray(t *testing.T) { var a Arrays err := easyjson.Unmarshal([]byte(arrayOverflowString), &a) if err != nil { t.Error(err) } if a != arrayValue { t.Errorf("Unmarshal(%v) = %+v; want %+v", arrayOverflowString, a, arrayValue) } } func TestUnderflowArray(t *testing.T) { var a Arrays err := easyjson.Unmarshal([]byte(arrayUnderflowString), &a) if err != nil { t.Error(err) } if a != arrayUnderflowValue { t.Errorf("Unmarshal(%v) = %+v; want %+v", arrayUnderflowString, a, arrayUnderflowValue) } } func TestEncodingFlags(t *testing.T) { for i, test := range []struct { Flags jwriter.Flags In easyjson.Marshaler Want string }{ {0, EncodingFlagsTestMap{}, `{"F":null}`}, {0, EncodingFlagsTestSlice{}, `{"F":null}`}, {jwriter.NilMapAsEmpty, EncodingFlagsTestMap{}, `{"F":{}}`}, {jwriter.NilSliceAsEmpty, EncodingFlagsTestSlice{}, `{"F":[]}`}, } { w := &jwriter.Writer{Flags: test.Flags} test.In.MarshalEasyJSON(w) data, err := w.BuildBytes() if err != nil { t.Errorf("[%v] easyjson.Marshal(%+v) error: %v", i, test.In, err) } v := string(data) if v != test.Want { t.Errorf("[%v] easyjson.Marshal(%+v) = %v; want %v", i, test.In, v, test.Want) } } } func TestNestedEasyJsonMarshal(t *testing.T) { n := map[string]*NestedEasyMarshaler{ "Value": {}, "Slice1": {}, "Slice2": {}, "Map1": {}, "Map2": {}, } ni := NestedInterfaces{ Value: n["Value"], Slice: []interface{}{n["Slice1"], n["Slice2"]}, Map: map[string]interface{}{"1": n["Map1"], "2": n["Map2"]}, } easyjson.Marshal(ni) for k, v := range n { if !v.EasilyMarshaled { t.Errorf("Nested interface %s wasn't easily marshaled", k) } } } func TestNestedMarshaler(t *testing.T) { s := NestedMarshaler{ Value: &StructWithMarshaler{ Value: 5, }, Value2: 10, } data, err := s.MarshalJSON() if err != nil { t.Errorf("Can't marshal NestedMarshaler: %s", err) } s2 := NestedMarshaler { Value: &StructWithMarshaler{}, } err = s2.UnmarshalJSON(data) if err != nil { t.Errorf("Can't unmarshal NestedMarshaler: %s", err) } if !reflect.DeepEqual(s2, s) { t.Errorf("easyjson.Unmarshal() = %#v; want %#v", s2, s) } } func TestUnmarshalStructWithEmbeddedPtrStruct(t *testing.T) { var s = StructWithInterface{Field2: &EmbeddedStruct{}} var err error err = easyjson.Unmarshal([]byte(structWithInterfaceString), &s) if err != nil { t.Errorf("easyjson.Unmarshal() error: %v", err) } if !reflect.DeepEqual(s, structWithInterfaceValueFilled) { t.Errorf("easyjson.Unmarshal() = %#v; want %#v", s, structWithInterfaceValueFilled) } } func TestDisallowUnknown(t *testing.T) { var d DisallowUnknown err := easyjson.Unmarshal([]byte(disallowUnknownString), &d) if err == nil { t.Error("want error, got nil") } } var testNotGeneratedTypeCases = []interface{}{ TypeNotDeclared{}, TypeSkipped{}, } func TestMethodsNoGenerated(t *testing.T) { var ok bool for i, instance := range testNotGeneratedTypeCases { _, ok = instance.(json.Marshaler) if ok { t.Errorf("[%d, %T] Unexpected MarshalJSON()", i, instance) } _, ok = instance.(json.Unmarshaler) if ok { t.Errorf("[%d, %T] Unexpected Unmarshaler()", i, instance) } } } func TestNil(t *testing.T) { var p *PrimitiveTypes data, err := easyjson.Marshal(p) if err != nil { t.Errorf("easyjson.Marshal() error: %v", err) } if string(data) != "null" { t.Errorf("Wanted null, got %q", string(data)) } var b bytes.Buffer if n, err := easyjson.MarshalToWriter(p, &b); err != nil || n != 4 { t.Errorf("easyjson.MarshalToWriter() error: %v, written %d", err, n) } if s := b.String(); s != "null" { t.Errorf("Wanted null, got %q", s) } w := httptest.NewRecorder() started, written, err := easyjson.MarshalToHTTPResponseWriter(p, w) if !started || written != 4 || err != nil { t.Errorf("easyjson.MarshalToHTTPResponseWriter() error: %v, written %d, started %t", err, written, started) } if s := w.Body.String(); s != "null" { t.Errorf("Wanted null, got %q", s) } } easyjson-0.7.6/tests/custom_map_key_type.go000066400000000000000000000010641371475264500211470ustar00rootroot00000000000000package tests import fmt "fmt" //easyjson:json type CustomMapKeyType struct { Map map[customKeyType]int } type customKeyType [2]byte func (k customKeyType) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"%02x"`, k)), nil } func (k *customKeyType) UnmarshalJSON(b []byte) error { _, err := fmt.Sscanf(string(b), `"%02x%02x"`, &k[0], &k[1]) return err } var customMapKeyTypeValue CustomMapKeyType func init() { customMapKeyTypeValue.Map = map[customKeyType]int{ {0x01, 0x02}: 3, } } var customMapKeyTypeValueString = `{"Map":{"0102":3}}` easyjson-0.7.6/tests/data.go000066400000000000000000000410571371475264500160060ustar00rootroot00000000000000package tests import ( "fmt" "math" "net" "time" "github.com/mailru/easyjson" "github.com/mailru/easyjson/opt" ) type PrimitiveTypes struct { String string Bool bool Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 Uint uint Uint8 uint8 Uint16 uint16 Uint32 uint32 Uint64 uint64 IntString int `json:",string"` Int8String int8 `json:",string"` Int16String int16 `json:",string"` Int32String int32 `json:",string"` Int64String int64 `json:",string"` UintString uint `json:",string"` Uint8String uint8 `json:",string"` Uint16String uint16 `json:",string"` Uint32String uint32 `json:",string"` Uint64String uint64 `json:",string"` Float32 float32 Float64 float64 Float32String float32 `json:",string"` Float64String float64 `json:",string"` Ptr *string PtrNil *string } var str = "bla" var primitiveTypesValue = PrimitiveTypes{ String: "test", Bool: true, Int: math.MinInt32, Int8: math.MinInt8, Int16: math.MinInt16, Int32: math.MinInt32, Int64: math.MinInt64, Uint: math.MaxUint32, Uint8: math.MaxUint8, Uint16: math.MaxUint16, Uint32: math.MaxUint32, Uint64: math.MaxUint64, IntString: math.MinInt32, Int8String: math.MinInt8, Int16String: math.MinInt16, Int32String: math.MinInt32, Int64String: math.MinInt64, UintString: math.MaxUint32, Uint8String: math.MaxUint8, Uint16String: math.MaxUint16, Uint32String: math.MaxUint32, Uint64String: math.MaxUint64, Float32: 1.5, Float64: math.MaxFloat64, Float32String: 1.5, Float64String: math.MaxFloat64, Ptr: &str, } var primitiveTypesString = "{" + `"String":"test","Bool":true,` + `"Int":` + fmt.Sprint(math.MinInt32) + `,` + `"Int8":` + fmt.Sprint(math.MinInt8) + `,` + `"Int16":` + fmt.Sprint(math.MinInt16) + `,` + `"Int32":` + fmt.Sprint(math.MinInt32) + `,` + `"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` + `"Uint":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` + `"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` + `"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` + `"Uint32":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` + `"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` + `"IntString":"` + fmt.Sprint(math.MinInt32) + `",` + `"Int8String":"` + fmt.Sprint(math.MinInt8) + `",` + `"Int16String":"` + fmt.Sprint(math.MinInt16) + `",` + `"Int32String":"` + fmt.Sprint(math.MinInt32) + `",` + `"Int64String":"` + fmt.Sprint(int64(math.MinInt64)) + `",` + `"UintString":"` + fmt.Sprint(uint32(math.MaxUint32)) + `",` + `"Uint8String":"` + fmt.Sprint(math.MaxUint8) + `",` + `"Uint16String":"` + fmt.Sprint(math.MaxUint16) + `",` + `"Uint32String":"` + fmt.Sprint(uint32(math.MaxUint32)) + `",` + `"Uint64String":"` + fmt.Sprint(uint64(math.MaxUint64)) + `",` + `"Float32":` + fmt.Sprint(1.5) + `,` + `"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` + `"Float32String":"` + fmt.Sprint(1.5) + `",` + `"Float64String":"` + fmt.Sprint(math.MaxFloat64) + `",` + `"Ptr":"bla",` + `"PtrNil":null` + "}" type ( NamedString string NamedBool bool NamedInt int NamedInt8 int8 NamedInt16 int16 NamedInt32 int32 NamedInt64 int64 NamedUint uint NamedUint8 uint8 NamedUint16 uint16 NamedUint32 uint32 NamedUint64 uint64 NamedFloat32 float32 NamedFloat64 float64 NamedStrPtr *string ) type NamedPrimitiveTypes struct { String NamedString Bool NamedBool Int NamedInt Int8 NamedInt8 Int16 NamedInt16 Int32 NamedInt32 Int64 NamedInt64 Uint NamedUint Uint8 NamedUint8 Uint16 NamedUint16 Uint32 NamedUint32 Uint64 NamedUint64 Float32 NamedFloat32 Float64 NamedFloat64 Ptr NamedStrPtr PtrNil NamedStrPtr } var namedPrimitiveTypesValue = NamedPrimitiveTypes{ String: "test", Bool: true, Int: math.MinInt32, Int8: math.MinInt8, Int16: math.MinInt16, Int32: math.MinInt32, Int64: math.MinInt64, Uint: math.MaxUint32, Uint8: math.MaxUint8, Uint16: math.MaxUint16, Uint32: math.MaxUint32, Uint64: math.MaxUint64, Float32: 1.5, Float64: math.MaxFloat64, Ptr: NamedStrPtr(&str), } var namedPrimitiveTypesString = "{" + `"String":"test",` + `"Bool":true,` + `"Int":` + fmt.Sprint(math.MinInt32) + `,` + `"Int8":` + fmt.Sprint(math.MinInt8) + `,` + `"Int16":` + fmt.Sprint(math.MinInt16) + `,` + `"Int32":` + fmt.Sprint(math.MinInt32) + `,` + `"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` + `"Uint":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` + `"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` + `"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` + `"Uint32":` + fmt.Sprint(uint32(math.MaxUint32)) + `,` + `"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` + `"Float32":` + fmt.Sprint(1.5) + `,` + `"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` + `"Ptr":"bla",` + `"PtrNil":null` + "}" type SubStruct struct { Value string Value2 string unexpored bool } type SubP struct { V string } type SubStructAlias SubStruct type Structs struct { SubStruct *SubP Value2 int Sub1 SubStruct `json:"substruct"` Sub2 *SubStruct SubNil *SubStruct SubSlice []SubStruct SubSliceNil []SubStruct SubPtrSlice []*SubStruct SubPtrSliceNil []*SubStruct SubA1 SubStructAlias SubA2 *SubStructAlias Anonymous struct { V string I int } Anonymous1 *struct { V string } AnonymousSlice []struct{ V int } AnonymousPtrSlice []*struct{ V int } Slice []string unexported bool } var structsValue = Structs{ SubStruct: SubStruct{Value: "test"}, SubP: &SubP{V: "subp"}, Value2: 5, Sub1: SubStruct{Value: "test1", Value2: "v"}, Sub2: &SubStruct{Value: "test2", Value2: "v2"}, SubSlice: []SubStruct{ {Value: "s1"}, {Value: "s2"}, }, SubPtrSlice: []*SubStruct{ {Value: "p1"}, {Value: "p2"}, }, SubA1: SubStructAlias{Value: "test3", Value2: "v3"}, SubA2: &SubStructAlias{Value: "test4", Value2: "v4"}, Anonymous: struct { V string I int }{V: "bla", I: 5}, Anonymous1: &struct { V string }{V: "bla1"}, AnonymousSlice: []struct{ V int }{{1}, {2}}, AnonymousPtrSlice: []*struct{ V int }{{3}, {4}}, Slice: []string{"test5", "test6"}, } var structsString = "{" + `"Value2":5,` + `"substruct":{"Value":"test1","Value2":"v"},` + `"Sub2":{"Value":"test2","Value2":"v2"},` + `"SubNil":null,` + `"SubSlice":[{"Value":"s1","Value2":""},{"Value":"s2","Value2":""}],` + `"SubSliceNil":null,` + `"SubPtrSlice":[{"Value":"p1","Value2":""},{"Value":"p2","Value2":""}],` + `"SubPtrSliceNil":null,` + `"SubA1":{"Value":"test3","Value2":"v3"},` + `"SubA2":{"Value":"test4","Value2":"v4"},` + `"Anonymous":{"V":"bla","I":5},` + `"Anonymous1":{"V":"bla1"},` + `"AnonymousSlice":[{"V":1},{"V":2}],` + `"AnonymousPtrSlice":[{"V":3},{"V":4}],` + `"Slice":["test5","test6"],` + // Embedded fields go last. `"V":"subp",` + `"Value":"test"` + "}" type OmitEmpty struct { // NOTE: first field is empty to test comma printing. StrE, StrNE string `json:",omitempty"` PtrE, PtrNE *string `json:",omitempty"` IntNE int `json:"intField,omitempty"` IntE int `json:",omitempty"` // NOTE: omitempty has no effect on non-pointer struct fields. SubE, SubNE SubStruct `json:",omitempty"` SubPE, SubPNE *SubStruct `json:",omitempty"` } var omitEmptyValue = OmitEmpty{ StrNE: "str", PtrNE: &str, IntNE: 6, SubNE: SubStruct{Value: "1", Value2: "2"}, SubPNE: &SubStruct{Value: "3", Value2: "4"}, } var omitEmptyString = "{" + `"StrNE":"str",` + `"PtrNE":"bla",` + `"intField":6,` + `"SubE":{"Value":"","Value2":""},` + `"SubNE":{"Value":"1","Value2":"2"},` + `"SubPNE":{"Value":"3","Value2":"4"}` + "}" type Opts struct { StrNull opt.String StrEmpty opt.String Str opt.String StrOmitempty opt.String `json:",omitempty"` IntNull opt.Int IntZero opt.Int Int opt.Int } var optsValue = Opts{ StrEmpty: opt.OString(""), Str: opt.OString("test"), IntZero: opt.OInt(0), Int: opt.OInt(5), } var optsString = `{` + `"StrNull":null,` + `"StrEmpty":"",` + `"Str":"test",` + `"IntNull":null,` + `"IntZero":0,` + `"Int":5` + `}` type Raw struct { Field easyjson.RawMessage Field2 string } var rawValue = Raw{ Field: []byte(`{"a" : "b"}`), Field2: "test", } var rawString = `{` + `"Field":{"a" : "b"},` + `"Field2":"test"` + `}` type StdMarshaler struct { T time.Time IP net.IP } var stdMarshalerValue = StdMarshaler{ T: time.Date(2016, 01, 02, 14, 15, 10, 0, time.UTC), IP: net.IPv4(192, 168, 0, 1), } var stdMarshalerString = `{` + `"T":"2016-01-02T14:15:10Z",` + `"IP":"192.168.0.1"` + `}` type UserMarshaler struct { V vMarshaler T tMarshaler } type vMarshaler net.IP func (v vMarshaler) MarshalJSON() ([]byte, error) { return []byte(`"0::0"`), nil } func (v *vMarshaler) UnmarshalJSON([]byte) error { *v = vMarshaler(net.IPv6zero) return nil } type tMarshaler net.IP func (v tMarshaler) MarshalText() ([]byte, error) { return []byte(`[0::0]`), nil } func (v *tMarshaler) UnmarshalText([]byte) error { *v = tMarshaler(net.IPv6zero) return nil } var userMarshalerValue = UserMarshaler{ V: vMarshaler(net.IPv6zero), T: tMarshaler(net.IPv6zero), } var userMarshalerString = `{` + `"V":"0::0",` + `"T":"[0::0]"` + `}` type unexportedStruct struct { Value string } var unexportedStructValue = unexportedStruct{"test"} var unexportedStructString = `{"Value":"test"}` type ExcludedField struct { Process bool `json:"process"` DoNotProcess bool `json:"-"` DoNotProcess1 bool `json:"-"` } var excludedFieldValue = ExcludedField{ Process: true, DoNotProcess: false, DoNotProcess1: false, } var excludedFieldString = `{"process":true}` type Slices struct { ByteSlice []byte EmptyByteSlice []byte NilByteSlice []byte IntSlice []int EmptyIntSlice []int NilIntSlice []int } var sliceValue = Slices{ ByteSlice: []byte("abc"), EmptyByteSlice: []byte{}, NilByteSlice: []byte(nil), IntSlice: []int{1, 2, 3, 4, 5}, EmptyIntSlice: []int{}, NilIntSlice: []int(nil), } var sliceString = `{` + `"ByteSlice":"YWJj",` + `"EmptyByteSlice":"",` + `"NilByteSlice":null,` + `"IntSlice":[1,2,3,4,5],` + `"EmptyIntSlice":[],` + `"NilIntSlice":null` + `}` type Arrays struct { ByteArray [3]byte EmptyByteArray [0]byte IntArray [5]int EmptyIntArray [0]int } var arrayValue = Arrays{ ByteArray: [3]byte{'a', 'b', 'c'}, EmptyByteArray: [0]byte{}, IntArray: [5]int{1, 2, 3, 4, 5}, EmptyIntArray: [0]int{}, } var arrayString = `{` + `"ByteArray":"YWJj",` + `"EmptyByteArray":"",` + `"IntArray":[1,2,3,4,5],` + `"EmptyIntArray":[]` + `}` var arrayOverflowString = `{` + `"ByteArray":"YWJjbnNk",` + `"EmptyByteArray":"YWJj",` + `"IntArray":[1,2,3,4,5,6],` + `"EmptyIntArray":[7,8]` + `}` var arrayUnderflowValue = Arrays{ ByteArray: [3]byte{'x', 0, 0}, EmptyByteArray: [0]byte{}, IntArray: [5]int{1, 2, 0, 0, 0}, EmptyIntArray: [0]int{}, } var arrayUnderflowString = `{` + `"ByteArray":"eA==",` + `"IntArray":[1,2]` + `}` type Str string type Maps struct { Map map[string]string InterfaceMap map[string]interface{} NilMap map[string]string CustomMap map[Str]Str } var mapsValue = Maps{ Map: map[string]string{"A": "b"}, // only one item since map iteration is randomized InterfaceMap: map[string]interface{}{"G": float64(1)}, CustomMap: map[Str]Str{"c": "d"}, } var mapsString = `{` + `"Map":{"A":"b"},` + `"InterfaceMap":{"G":1},` + `"NilMap":null,` + `"CustomMap":{"c":"d"}` + `}` type NamedSlice []Str type NamedMap map[Str]Str type DeepNest struct { SliceMap map[Str][]Str SliceMap1 map[Str][]Str SliceMap2 map[Str][]Str NamedSliceMap map[Str]NamedSlice NamedMapMap map[Str]NamedMap MapSlice []map[Str]Str NamedSliceSlice []NamedSlice NamedMapSlice []NamedMap NamedStringSlice []NamedString } var deepNestValue = DeepNest{ SliceMap: map[Str][]Str{ "testSliceMap": { "0", "1", }, }, SliceMap1: map[Str][]Str{ "testSliceMap1": []Str(nil), }, SliceMap2: map[Str][]Str{ "testSliceMap2": {}, }, NamedSliceMap: map[Str]NamedSlice{ "testNamedSliceMap": { "2", "3", }, }, NamedMapMap: map[Str]NamedMap{ "testNamedMapMap": { "key1": "value1", }, }, MapSlice: []map[Str]Str{ { "testMapSlice": "someValue", }, }, NamedSliceSlice: []NamedSlice{ { "someValue1", "someValue2", }, { "someValue3", "someValue4", }, }, NamedMapSlice: []NamedMap{ { "key2": "value2", }, { "key3": "value3", }, }, NamedStringSlice: []NamedString{ "value4", "value5", }, } var deepNestString = `{` + `"SliceMap":{` + `"testSliceMap":["0","1"]` + `},` + `"SliceMap1":{` + `"testSliceMap1":null` + `},` + `"SliceMap2":{` + `"testSliceMap2":[]` + `},` + `"NamedSliceMap":{` + `"testNamedSliceMap":["2","3"]` + `},` + `"NamedMapMap":{` + `"testNamedMapMap":{"key1":"value1"}` + `},` + `"MapSlice":[` + `{"testMapSlice":"someValue"}` + `],` + `"NamedSliceSlice":[` + `["someValue1","someValue2"],` + `["someValue3","someValue4"]` + `],` + `"NamedMapSlice":[` + `{"key2":"value2"},` + `{"key3":"value3"}` + `],` + `"NamedStringSlice":["value4","value5"]` + `}` type DeepNestOptional struct { MapSlice []map[Str]Str `json:",omitempty"` } var deepNestOptionalValue = DeepNestOptional{ MapSlice: []map[Str]Str{{}}, } var deepNestOptionalString = `{` + `"MapSlice":[` + `{}` + `]` + `}` //easyjson:json type Ints []int var IntsValue = Ints{1, 2, 3, 4, 5} var IntsString = `[1,2,3,4,5]` //easyjson:json type MapStringString map[string]string var mapStringStringValue = MapStringString{"a": "b"} var mapStringStringString = `{"a":"b"}` type RequiredOptionalStruct struct { FirstName string `json:"first_name,required"` Lastname string `json:"last_name"` } type RequiredOptionalMap struct { ReqMap map[int]string `json:"req_map,required"` OmitEmptyMap map[int]string `json:"oe_map,omitempty"` NoOmitEmptyMap map[int]string `json:"noe_map,!omitempty"` } //easyjson:json type EncodingFlagsTestMap struct { F map[string]string } //easyjson:json type EncodingFlagsTestSlice struct { F []string } type StructWithInterface struct { Field1 int `json:"f1"` Field2 interface{} `json:"f2"` Field3 string `json:"f3"` } type EmbeddedStruct struct { Field1 int `json:"f1"` Field2 string `json:"f2"` } var structWithInterfaceString = `{"f1":1,"f2":{"f1":11,"f2":"22"},"f3":"3"}` var structWithInterfaceValueFilled = StructWithInterface{1, &EmbeddedStruct{11, "22"}, "3"} //easyjson:json type MapIntString map[int]string var mapIntStringValue = MapIntString{3: "hi"} var mapIntStringValueString = `{"3":"hi"}` //easyjson:json type MapInt32String map[int32]string var mapInt32StringValue = MapInt32String{-354634382: "life"} var mapInt32StringValueString = `{"-354634382":"life"}` //easyjson:json type MapInt64String map[int64]string var mapInt64StringValue = MapInt64String{-3546343826724305832: "life"} var mapInt64StringValueString = `{"-3546343826724305832":"life"}` //easyjson:json type MapUintString map[uint]string var mapUintStringValue = MapUintString{42: "life"} var mapUintStringValueString = `{"42":"life"}` //easyjson:json type MapUint32String map[uint32]string var mapUint32StringValue = MapUint32String{354634382: "life"} var mapUint32StringValueString = `{"354634382":"life"}` //easyjson:json type MapUint64String map[uint64]string var mapUint64StringValue = MapUint64String{3546343826724305832: "life"} var mapUint64StringValueString = `{"3546343826724305832":"life"}` //easyjson:json type MapUintptrString map[uintptr]string var mapUintptrStringValue = MapUintptrString{272679208: "obj"} var mapUintptrStringValueString = `{"272679208":"obj"}` type MyInt int //easyjson:json type MapMyIntString map[MyInt]string var mapMyIntStringValue = MapMyIntString{MyInt(42): "life"} var mapMyIntStringValueString = `{"42":"life"}` //easyjson:json type IntKeyedMapStruct struct { Foo MapMyIntString `json:"foo"` Bar map[int16]MapUint32String `json:"bar"` } var intKeyedMapStructValue = IntKeyedMapStruct{ Foo: mapMyIntStringValue, Bar: map[int16]MapUint32String{32: mapUint32StringValue}, } var intKeyedMapStructValueString = `{` + `"foo":{"42":"life"},` + `"bar":{"32":{"354634382":"life"}}` + `}` type IntArray [2]int //easyjson:json type IntArrayStruct struct { Pointer *IntArray `json:"pointer"` Value IntArray `json:"value"` } var intArrayStructValue = IntArrayStruct{ Pointer: &IntArray{1, 2}, Value: IntArray{1, 2}, } var intArrayStructValueString = `{` + `"pointer":[1,2],` + `"value":[1,2]` + `}` type MyUInt8 uint8 //easyjson:json type MyUInt8Slice []MyUInt8 var myUInt8SliceValue = MyUInt8Slice{1, 2, 3, 4, 5} var myUInt8SliceString = `[1,2,3,4,5]` //easyjson:json type MyUInt8Array [2]MyUInt8 var myUInt8ArrayValue = MyUInt8Array{1, 2} var myUInt8ArrayString = `[1,2]` easyjson-0.7.6/tests/disallow_unknown.go000066400000000000000000000002531371475264500204630ustar00rootroot00000000000000package tests //easyjson:json type DisallowUnknown struct { FieldOne string `json:"field_one"` } var disallowUnknownString = `{"field_one": "one", "field_two": "two"}` easyjson-0.7.6/tests/embedded_type.go000066400000000000000000000010461371475264500176610ustar00rootroot00000000000000package tests //easyjson:json type EmbeddedType struct { EmbeddedInnerType Inner struct { EmbeddedInnerType } Field2 int EmbeddedInnerType2 `json:"named"` } type EmbeddedInnerType struct { Field1 int } type EmbeddedInnerType2 struct { Field3 int } var embeddedTypeValue EmbeddedType func init() { embeddedTypeValue.Field1 = 1 embeddedTypeValue.Field2 = 2 embeddedTypeValue.Inner.Field1 = 3 embeddedTypeValue.Field3 = 4 } var embeddedTypeValueString = `{"Inner":{"Field1":3},"Field2":2,"named":{"Field3":4},"Field1":1}` easyjson-0.7.6/tests/errors.go000066400000000000000000000007541371475264500164100ustar00rootroot00000000000000package tests //easyjson:json type ErrorIntSlice []int //easyjson:json type ErrorBoolSlice []bool //easyjson:json type ErrorUintSlice []uint //easyjson:json type ErrorStruct struct { Int int `json:"int"` String string `json:"string"` Slice []int `json:"slice"` IntSlice []int `json:"int_slice"` } type ErrorNestedStruct struct { ErrorStruct ErrorStruct `json:"error_struct"` Int int `json:"int"` } //easyjson:json type ErrorIntMap map[uint32]string easyjson-0.7.6/tests/errors_test.go000066400000000000000000000143131371475264500174430ustar00rootroot00000000000000package tests import ( "testing" "github.com/mailru/easyjson/jlexer" ) func TestMultipleErrorsInt(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`[1, 2, 3, "4", "5"]`), Offsets: []int{10, 15}, }, { Data: []byte(`[1, {"2":"3"}, 3, "4"]`), Offsets: []int{4, 18}, }, { Data: []byte(`[1, "2", "3", "4", "5", "6"]`), Offsets: []int{4, 9, 14, 19, 24}, }, { Data: []byte(`[1, 2, 3, 4, "5"]`), Offsets: []int{13}, }, { Data: []byte(`[{"1": "2"}]`), Offsets: []int{1}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorIntSlice v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsInt(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsInt(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } func TestMultipleErrorsBool(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`[true, false, true, false]`), }, { Data: []byte(`["test", "value", "lol", "1"]`), Offsets: []int{1, 9, 18, 25}, }, { Data: []byte(`[true, 42, {"a":"b", "c":"d"}, false]`), Offsets: []int{7, 11}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorBoolSlice v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsBool(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsBool(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } func TestMultipleErrorsUint(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`[42, 42, 42]`), }, { Data: []byte(`[17, "42", 32]`), Offsets: []int{5}, }, { Data: []byte(`["zz", "zz"]`), Offsets: []int{1, 7}, }, { Data: []byte(`[{}, 42]`), Offsets: []int{1}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorUintSlice v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsUint(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsUint(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } func TestMultipleErrorsStruct(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`{"string": "test", "slice":[42, 42, 42], "int_slice":[1, 2, 3]}`), }, { Data: []byte(`{"string": {"test": "test"}, "slice":[42, 42, 42], "int_slice":["1", 2, 3]}`), Offsets: []int{11, 64}, }, { Data: []byte(`{"slice": [42, 42], "string": {"test": "test"}, "int_slice":["1", "2", 3]}`), Offsets: []int{30, 61, 66}, }, { Data: []byte(`{"string": "test", "slice": {}}`), Offsets: []int{28}, }, { Data: []byte(`{"slice":5, "string" : "test"}`), Offsets: []int{9}, }, { Data: []byte(`{"slice" : "test", "string" : "test"}`), Offsets: []int{11}, }, { Data: []byte(`{"slice": "", "string" : {}, "int":{}}`), Offsets: []int{10, 25, 35}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorStruct v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsStruct(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsStruct(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } func TestMultipleErrorsNestedStruct(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`{"error_struct":{}}`), }, { Data: []byte(`{"error_struct":5}`), Offsets: []int{16}, }, { Data: []byte(`{"error_struct":[]}`), Offsets: []int{16}, }, { Data: []byte(`{"error_struct":{"int":{}}}`), Offsets: []int{23}, }, { Data: []byte(`{"error_struct":{"int_slice":{}}, "int":4}`), Offsets: []int{29}, }, { Data: []byte(`{"error_struct":{"int_slice":["1", 2, "3"]}, "int":[]}`), Offsets: []int{30, 38, 51}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorNestedStruct v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsNestedStruct(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsNestedStruct(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } func TestMultipleErrorsIntMap(t *testing.T) { for i, test := range []struct { Data []byte Offsets []int }{ { Data: []byte(`{"a":"NumErr"}`), Offsets: []int{1}, }, { Data: []byte(`{"":"ErrSyntax"}`), Offsets: []int{1}, }, { Data: []byte(`{"a":"NumErr","33147483647":"ErrRange","-1":"ErrRange"}`), Offsets: []int{1, 14, 39}, }, } { l := jlexer.Lexer{ Data: test.Data, UseMultipleErrors: true, } var v ErrorIntMap v.UnmarshalEasyJSON(&l) errors := l.GetNonFatalErrors() if len(errors) != len(test.Offsets) { t.Errorf("[%d] TestMultipleErrorsInt(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) return } for ii, e := range errors { if e.Offset != test.Offsets[ii] { t.Errorf("[%d] TestMultipleErrorsInt(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) } } } } easyjson-0.7.6/tests/escaping.go000066400000000000000000000002331371475264500166550ustar00rootroot00000000000000package tests //easyjson:json type EscStringStruct struct { A string `json:"a"` } //easyjson:json type EscIntStruct struct { A int `json:"a,string"` } easyjson-0.7.6/tests/escaping_test.go000066400000000000000000000030671371475264500177240ustar00rootroot00000000000000package tests import ( "reflect" "testing" "github.com/mailru/easyjson" ) func TestStrFieldsUnescaping(t *testing.T) { cases := []struct { data string exp EscStringStruct }{ { data: `{}`, exp: EscStringStruct{}, }, { data: `{"a": "\""}`, exp: EscStringStruct{A: `"`}, }, { data: `{"a": "\\"}`, exp: EscStringStruct{A: `\`}, }, { data: `{"a": "\\\""}`, exp: EscStringStruct{A: `\"`}, }, { data: `{"a": "\\\\'"}`, exp: EscStringStruct{A: `\\'`}, }, { data: `{"a": "\t\\\nx\\\""}`, exp: EscStringStruct{A: "\t\\\nx\\\""}, }, { data: `{"a": "\r\n"}`, exp: EscStringStruct{A: "\r\n"}, }, { data: `{"a": "\r\n\u4e2D\u56fD\\\""}`, exp: EscStringStruct{A: "\r\n中国\\\""}, }, } for i, c := range cases { var val EscStringStruct err := easyjson.Unmarshal([]byte(c.data), &val) if err != nil { t.Error(err) } if !reflect.DeepEqual(val, c.exp) { t.Errorf("[%d] TestStrFieldsUnescaping(): got=%q, exp=%q", i, val, c.exp) } } } func TestIntFieldsUnescaping(t *testing.T) { cases := []struct { data string exp EscIntStruct }{ { data: `{}`, exp: EscIntStruct{A: 0}, }, { data: `{"a": "1"}`, exp: EscIntStruct{A: 1}, }, { data: `{"a": "\u0032"}`, exp: EscIntStruct{A: 2}, }, } for i, c := range cases { var val EscIntStruct err := easyjson.Unmarshal([]byte(c.data), &val) if err != nil { t.Error(err) } if !reflect.DeepEqual(val, c.exp) { t.Errorf("[%d] TestIntFieldsUnescaping(): got=%v, exp=%v", i, val, c.exp) } } } easyjson-0.7.6/tests/html.go000066400000000000000000000000631371475264500160310ustar00rootroot00000000000000package tests type Struct struct { Test string } easyjson-0.7.6/tests/html_test.go000066400000000000000000000010311371475264500170640ustar00rootroot00000000000000package tests import ( "testing" "github.com/mailru/easyjson/jwriter" ) func TestHTML(t *testing.T) { s := Struct{ Test: "test", } j := jwriter.Writer{ NoEscapeHTML: false, } s.MarshalEasyJSON(&j) data, _ := j.BuildBytes() if string(data) != `{"Test":"\u003cb\u003etest\u003c/b\u003e"}` { t.Fatal("EscapeHTML error:", string(data)) } j.NoEscapeHTML = true s.MarshalEasyJSON(&j) data, _ = j.BuildBytes() if string(data) != `{"Test":"test"}` { t.Fatal("NoEscapeHTML error:", string(data)) } } easyjson-0.7.6/tests/intern.go000066400000000000000000000003631371475264500163670ustar00rootroot00000000000000package tests //easyjson:json type NoIntern struct { Field string `json:"field"` } //easyjson:json type Intern struct { Field string `json:"field,intern"` } var intern = Intern{Field: "interned"} var internString = `{"field":"interned"}` easyjson-0.7.6/tests/intern_test.go000066400000000000000000000014721371475264500174300ustar00rootroot00000000000000package tests import ( "testing" "github.com/mailru/easyjson" ) func TestStringIntern(t *testing.T) { data := []byte(`{"field": "string interning test"}`) var i Intern allocsPerRun := testing.AllocsPerRun(1000, func() { i = Intern{} err := easyjson.Unmarshal(data, &i) if err != nil { t.Error(err) } if i.Field != "string interning test" { t.Fatalf("wrong value: %q", i.Field) } }) if allocsPerRun != 1 { t.Fatalf("expected 1 allocs, got %f", allocsPerRun) } var n NoIntern allocsPerRun = testing.AllocsPerRun(1000, func() { n = NoIntern{} err := easyjson.Unmarshal(data, &n) if err != nil { t.Error(err) } if n.Field != "string interning test" { t.Fatalf("wrong value: %q", n.Field) } }) if allocsPerRun != 2 { t.Fatalf("expected 2 allocs, got %f", allocsPerRun) } } easyjson-0.7.6/tests/key_marshaler_map.go000066400000000000000000000010101371475264500205410ustar00rootroot00000000000000package tests type KeyWithEncodingMarshaler int func (f KeyWithEncodingMarshaler) MarshalText() (text []byte, err error) { return []byte("hello"), nil } func (f *KeyWithEncodingMarshaler) UnmarshalText(text []byte) error { if string(text) == "hello" { *f = 5 } return nil } //easyjson:json type KeyWithEncodingMarshalers map[KeyWithEncodingMarshaler]string var mapWithEncodingMarshaler KeyWithEncodingMarshalers = KeyWithEncodingMarshalers{5: "hello"} var mapWithEncodingMarshalerString = `{"hello":"hello"}` easyjson-0.7.6/tests/members_escaped.go000066400000000000000000000001301371475264500201760ustar00rootroot00000000000000package tests //easyjson:json type MembersEscaped struct { A string `json:"漢語"` } easyjson-0.7.6/tests/members_escaping_test.go000066400000000000000000000023271371475264500214340ustar00rootroot00000000000000package tests import ( "reflect" "testing" "github.com/mailru/easyjson" ) func TestMembersEscaping(t *testing.T) { cases := []struct { data string esc MembersEscaped unesc MembersUnescaped }{ { data: `{"漢語": "中国"}`, esc: MembersEscaped{A: "中国"}, unesc: MembersUnescaped{A: "中国"}, }, { data: `{"漢語": "\u4e2D\u56fD"}`, esc: MembersEscaped{A: "中国"}, unesc: MembersUnescaped{A: "中国"}, }, { data: `{"\u6f22\u8a9E": "中国"}`, esc: MembersEscaped{A: "中国"}, unesc: MembersUnescaped{A: ""}, }, { data: `{"\u6f22\u8a9E": "\u4e2D\u56fD"}`, esc: MembersEscaped{A: "中国"}, unesc: MembersUnescaped{A: ""}, }, } for i, c := range cases { var esc MembersEscaped err := easyjson.Unmarshal([]byte(c.data), &esc) if err != nil { t.Error(err) } if !reflect.DeepEqual(esc, c.esc) { t.Errorf("[%d] TestMembersEscaping(): got=%+v, exp=%+v", i, esc, c.esc) } var unesc MembersUnescaped err = easyjson.Unmarshal([]byte(c.data), &unesc) if err != nil { t.Error(err) } if !reflect.DeepEqual(unesc, c.unesc) { t.Errorf("[%d] TestMembersEscaping(): no-unescaping case: got=%+v, exp=%+v", i, esc, c.esc) } } } easyjson-0.7.6/tests/members_unescaped.go000066400000000000000000000001321371475264500205430ustar00rootroot00000000000000package tests //easyjson:json type MembersUnescaped struct { A string `json:"漢語"` } easyjson-0.7.6/tests/named_type.go000066400000000000000000000010441371475264500172120ustar00rootroot00000000000000package tests //easyjson:json type NamedType struct { Inner struct { // easyjson is mistakenly naming the type of this field 'tests.MyString' in the generated output // something about a named type inside an anonmymous type is triggering this bug Field MyString `tag:"value"` Field2 int "tag:\"value with ` in it\"" } } type MyString string var namedTypeValue NamedType func init() { namedTypeValue.Inner.Field = "test" namedTypeValue.Inner.Field2 = 123 } var namedTypeValueString = `{"Inner":{"Field":"test","Field2":123}}` easyjson-0.7.6/tests/nested_easy.go000066400000000000000000000010221371475264500173640ustar00rootroot00000000000000package tests import ( "github.com/mailru/easyjson" "github.com/mailru/easyjson/jwriter" ) //easyjson:json type NestedInterfaces struct { Value interface{} Slice []interface{} Map map[string]interface{} } type NestedEasyMarshaler struct { EasilyMarshaled bool } var _ easyjson.Marshaler = &NestedEasyMarshaler{} func (i *NestedEasyMarshaler) MarshalEasyJSON(w *jwriter.Writer) { // We use this method only to indicate that easyjson.Marshaler // interface was really used while encoding. i.EasilyMarshaled = true } easyjson-0.7.6/tests/nested_marshaler.go000066400000000000000000000007051371475264500204100ustar00rootroot00000000000000package tests import ( "github.com/mailru/easyjson" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) //easyjson:json type NestedMarshaler struct { Value easyjson.MarshalerUnmarshaler Value2 int } type StructWithMarshaler struct { Value int } func (s *StructWithMarshaler) UnmarshalEasyJSON(w *jlexer.Lexer) { s.Value = w.Int() } func (s *StructWithMarshaler) MarshalEasyJSON(w *jwriter.Writer) { w.Int(s.Value) } easyjson-0.7.6/tests/nocopy.go000066400000000000000000000001551371475264500163760ustar00rootroot00000000000000package tests //easyjson:json type NocopyStruct struct { A string `json:"a"` B string `json:"b,nocopy"` } easyjson-0.7.6/tests/nocopy_test.go000066400000000000000000000032351371475264500174370ustar00rootroot00000000000000package tests import ( "reflect" "testing" "unsafe" "github.com/mailru/easyjson" ) // verifies if string pointer belongs to the given buffer or outside of it func strBelongsTo(s string, buf []byte) bool { sPtr := (*reflect.StringHeader)(unsafe.Pointer(&s)).Data bufPtr := (*reflect.SliceHeader)(unsafe.Pointer(&buf)).Data if bufPtr <= sPtr && sPtr < bufPtr+uintptr(len(buf)) { return true } return false } func TestNocopy(t *testing.T) { data := []byte(`{"a": "valueA", "b": "valueB"}`) exp := NocopyStruct{ A: "valueA", B: "valueB", } res := NocopyStruct{} err := easyjson.Unmarshal(data, &res) if err != nil { t.Error(err) } if !reflect.DeepEqual(exp, res) { t.Errorf("TestNocopy(): got=%+v, exp=%+v", res, exp) } if strBelongsTo(res.A, data) { t.Error("TestNocopy(): field A was not copied and refers to buffer") } if !strBelongsTo(res.B, data) { t.Error("TestNocopy(): field B was copied rather than refer to bufferr") } data = []byte(`{"b": "valueNoCopy"}`) res = NocopyStruct{} allocsPerRun := testing.AllocsPerRun(1000, func() { err := easyjson.Unmarshal(data, &res) if err != nil { t.Error(err) } if res.B != "valueNoCopy" { t.Fatalf("wrong value: %q", res.B) } }) if allocsPerRun != 1 { t.Fatalf("noCopy field unmarshal: expected 1 allocs, got %f", allocsPerRun) } data = []byte(`{"a": "valueNoCopy"}`) allocsPerRun = testing.AllocsPerRun(1000, func() { err := easyjson.Unmarshal(data, &res) if err != nil { t.Error(err) } if res.A != "valueNoCopy" { t.Fatalf("wrong value: %q", res.A) } }) if allocsPerRun != 2 { t.Fatalf("copy field unmarshal: expected 2 allocs, got %f", allocsPerRun) } } easyjson-0.7.6/tests/nothing.go000066400000000000000000000000521371475264500165310ustar00rootroot00000000000000package tests // No structs in this file easyjson-0.7.6/tests/omitempty.go000066400000000000000000000004411371475264500171140ustar00rootroot00000000000000package tests //easyjson:json type OmitEmptyDefault struct { Field string Str string Str1 string `json:"s,!omitempty"` Str2 string `json:",!omitempty"` } var omitEmptyDefaultValue = OmitEmptyDefault{Field: "test"} var omitEmptyDefaultString = `{"Field":"test","s":"","Str2":""}` easyjson-0.7.6/tests/opt_test.go000066400000000000000000000025661371475264500167400ustar00rootroot00000000000000package tests import ( "math" "reflect" "testing" "encoding/json" "github.com/mailru/easyjson/opt" ) // This struct type must NOT have a generated marshaler type OptsVanilla struct { Int opt.Int Uint opt.Uint Int8 opt.Int8 Int16 opt.Int16 Int32 opt.Int32 Int64 opt.Int64 Uint8 opt.Uint8 Uint16 opt.Uint16 Uint32 opt.Uint32 Uint64 opt.Uint64 Float32 opt.Float32 Float64 opt.Float64 Bool opt.Bool String opt.String } var optsVanillaValue = OptsVanilla{ Int: opt.OInt(-123), Uint: opt.OUint(123), Int8: opt.OInt8(math.MaxInt8), Int16: opt.OInt16(math.MaxInt16), Int32: opt.OInt32(math.MaxInt32), Int64: opt.OInt64(math.MaxInt64), Uint8: opt.OUint8(math.MaxUint8), Uint16: opt.OUint16(math.MaxUint16), Uint32: opt.OUint32(math.MaxUint32), Uint64: opt.OUint64(math.MaxUint64), Float32: opt.OFloat32(math.MaxFloat32), Float64: opt.OFloat64(math.MaxFloat64), Bool: opt.OBool(true), String: opt.OString("foo"), } func TestOptsVanilla(t *testing.T) { data, err := json.Marshal(optsVanillaValue) if err != nil { t.Errorf("Failed to marshal vanilla opts: %v", err) } var ov OptsVanilla if err := json.Unmarshal(data, &ov); err != nil { t.Errorf("Failed to unmarshal vanilla opts: %v", err) } if !reflect.DeepEqual(optsVanillaValue, ov) { t.Errorf("Vanilla opts unmarshal returned invalid value %+v, want %+v", ov, optsVanillaValue) } } easyjson-0.7.6/tests/reference_to_pointer.go000066400000000000000000000002471371475264500212710ustar00rootroot00000000000000package tests type Struct1 struct { } //easyjson:json type Struct2 struct { From *Struct1 `json:"from,omitempty"` Through *Struct1 `json:"through,omitempty"` } easyjson-0.7.6/tests/required_test.go000066400000000000000000000030261371475264500177460ustar00rootroot00000000000000package tests import ( "fmt" "reflect" "testing" ) func TestRequiredField(t *testing.T) { cases := []struct{ json, errorMessage string }{ {`{"first_name":"Foo", "last_name": "Bar"}`, ""}, {`{"last_name":"Bar"}`, "key 'first_name' is required"}, {"{}", "key 'first_name' is required"}, } for _, tc := range cases { var v RequiredOptionalStruct err := v.UnmarshalJSON([]byte(tc.json)) if tc.errorMessage == "" { if err != nil { t.Errorf("%s. UnmarshalJSON didn`t expect error: %v", tc.json, err) } } else { if fmt.Sprintf("%v", err) != tc.errorMessage { t.Errorf("%s. UnmarshalJSON expected error: %v. got: %v", tc.json, tc.errorMessage, err) } } } } func TestRequiredOptionalMap(t *testing.T) { baseJson := `{"req_map":{}, "oe_map":{}, "noe_map":{}, "oe_slice":[]}` wantDecoding := RequiredOptionalMap{MapIntString{}, nil, MapIntString{}} var v RequiredOptionalMap if err := v.UnmarshalJSON([]byte(baseJson)); err != nil { t.Errorf("%s. UnmarshalJSON didn't expect error: %v", baseJson, err) } if !reflect.DeepEqual(v, wantDecoding) { t.Errorf("%s. UnmarshalJSON expected to gen: %v. got: %v", baseJson, wantDecoding, v) } baseStruct := RequiredOptionalMap{MapIntString{}, MapIntString{}, MapIntString{}} wantJson := `{"req_map":{},"noe_map":{}}` data, err := baseStruct.MarshalJSON() if err != nil { t.Errorf("MarshalJSON didn't expect error: %v on %v", err, data) } else if string(data) != wantJson { t.Errorf("%v. MarshalJSON wanted: %s got %s", baseStruct, wantJson, string(data)) } } easyjson-0.7.6/tests/snake.go000066400000000000000000000003361371475264500161710ustar00rootroot00000000000000package tests //easyjson:json type SnakeStruct struct { WeirdHTTPStuff bool CustomNamedField string `json:"cUsToM"` } var snakeStructValue SnakeStruct var snakeStructString = `{"weird_http_stuff":false,"cUsToM":""}` easyjson-0.7.6/tests/type_declaration.go000066400000000000000000000013141371475264500204130ustar00rootroot00000000000000package tests //easyjson:json type ( GenDeclared1 struct { Value string } // A gen declared easyjson struct with a comment GenDeclaredWithComment struct { Value string } ) type ( //easyjson:json TypeDeclared struct { Value string } TypeNotDeclared struct { Value string } ) var ( myGenDeclaredValue = TypeDeclared{Value: "GenDeclared"} myGenDeclaredString = `{"Value":"GenDeclared"}` myGenDeclaredWithCommentValue = TypeDeclared{Value: "GenDeclaredWithComment"} myGenDeclaredWithCommentString = `{"Value":"GenDeclaredWithComment"}` myTypeDeclaredValue = TypeDeclared{Value: "TypeDeclared"} myTypeDeclaredString = `{"Value":"TypeDeclared"}` ) easyjson-0.7.6/tests/type_declaration_skip.go000066400000000000000000000003671371475264500214500ustar00rootroot00000000000000package tests //easyjson:skip type TypeSkipped struct { Value string } type TypeNotSkipped struct { Value string } var ( myTypeNotSkippedValue = TypeDeclared{Value: "TypeNotSkipped"} myTypeNotSkippedString = `{"Value":"TypeNotSkipped"}` ) easyjson-0.7.6/tests/unknown_fields.go000066400000000000000000000004401371475264500201110ustar00rootroot00000000000000package tests import "github.com/mailru/easyjson" //easyjson:json type StructWithUnknownsProxy struct { easyjson.UnknownFieldsProxy Field1 string } //easyjson:json type StructWithUnknownsProxyWithOmitempty struct { easyjson.UnknownFieldsProxy Field1 string `json:",omitempty"` } easyjson-0.7.6/tests/unknown_fields_test.go000066400000000000000000000023621371475264500211550ustar00rootroot00000000000000package tests import ( "reflect" "testing" ) func TestUnknownFieldsProxy(t *testing.T) { baseJson := `{"Field1":"123","Field2":"321"}` s := StructWithUnknownsProxy{} err := s.UnmarshalJSON([]byte(baseJson)) if err != nil { t.Errorf("UnmarshalJSON didn't expect error: %v", err) } if s.Field1 != "123" { t.Errorf("UnmarshalJSON expected to parse Field1 as \"123\". got: %v", s.Field1) } data, err := s.MarshalJSON() if err != nil { t.Errorf("MarshalJSON didn't expect error: %v", err) } if !reflect.DeepEqual(baseJson, string(data)) { t.Errorf("MarshalJSON expected to gen: %v. got: %v", baseJson, string(data)) } } func TestUnknownFieldsProxyWithOmitempty(t *testing.T) { baseJson := `{"Field1":"123","Field2":"321"}` s := StructWithUnknownsProxyWithOmitempty{} err := s.UnmarshalJSON([]byte(baseJson)) if err != nil { t.Errorf("UnmarshalJSON didn't expect error: %v", err) } if s.Field1 != "123" { t.Errorf("UnmarshalJSON expected to parse Field1 as \"123\". got: %v", s.Field1) } data, err := s.MarshalJSON() if err != nil { t.Errorf("MarshalJSON didn't expect error: %v", err) } if !reflect.DeepEqual(baseJson, string(data)) { t.Errorf("MarshalJSON expected to gen: %v. got: %v", baseJson, string(data)) } } easyjson-0.7.6/unknown_fields.go000066400000000000000000000014371371475264500167560ustar00rootroot00000000000000package easyjson import ( jlexer "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) // UnknownFieldsProxy implemets UnknownsUnmarshaler and UnknownsMarshaler // use it as embedded field in your structure to parse and then serialize unknown struct fields type UnknownFieldsProxy struct { unknownFields map[string][]byte } func (s *UnknownFieldsProxy) UnmarshalUnknown(in *jlexer.Lexer, key string) { if s.unknownFields == nil { s.unknownFields = make(map[string][]byte, 1) } s.unknownFields[key] = in.Raw() } func (s UnknownFieldsProxy) MarshalUnknowns(out *jwriter.Writer, first bool) { for key, val := range s.unknownFields { if first { first = false } else { out.RawByte(',') } out.String(string(key)) out.RawByte(':') out.Raw(val, nil) } }