Showing preview only (502K chars total). Download the full file or copy to clipboard to get everything.
Repository: json-iterator/go
Branch: master
Commit: 71ac16282d12
Files: 138
Total size: 469.3 KB
Directory structure:
gitextract_ugnavu_c/
├── .codecov.yml
├── .gitignore
├── .travis.yml
├── Gopkg.toml
├── LICENSE
├── README.md
├── adapter.go
├── any.go
├── any_array.go
├── any_bool.go
├── any_float.go
├── any_int32.go
├── any_int64.go
├── any_invalid.go
├── any_nil.go
├── any_number.go
├── any_object.go
├── any_str.go
├── any_tests/
│ ├── jsoniter_any_array_test.go
│ ├── jsoniter_any_bool_test.go
│ ├── jsoniter_any_float_test.go
│ ├── jsoniter_any_int_test.go
│ ├── jsoniter_any_map_test.go
│ ├── jsoniter_any_null_test.go
│ ├── jsoniter_any_object_test.go
│ ├── jsoniter_any_string_test.go
│ ├── jsoniter_must_be_valid_test.go
│ └── jsoniter_wrap_test.go
├── any_uint32.go
├── any_uint64.go
├── api_tests/
│ ├── config_test.go
│ ├── decoder_test.go
│ ├── encoder_18_test.go
│ ├── encoder_test.go
│ ├── marshal_indent_test.go
│ ├── marshal_json_escape_test.go
│ └── marshal_json_test.go
├── benchmarks/
│ ├── encode_string_test.go
│ ├── jsoniter_large_file_test.go
│ └── stream_test.go
├── build.sh
├── config.go
├── example_test.go
├── extension_tests/
│ ├── decoder_test.go
│ └── extension_test.go
├── extra/
│ ├── binary_as_string_codec.go
│ ├── binary_as_string_codec_test.go
│ ├── fuzzy_decoder.go
│ ├── fuzzy_decoder_test.go
│ ├── naming_strategy.go
│ ├── naming_strategy_test.go
│ ├── privat_fields.go
│ ├── private_fields_test.go
│ ├── time_as_int64_codec.go
│ └── time_as_int64_codec_test.go
├── fuzzy_mode_convert_table.md
├── go.mod
├── go.sum
├── iter.go
├── iter_array.go
├── iter_float.go
├── iter_int.go
├── iter_object.go
├── iter_skip.go
├── iter_skip_sloppy.go
├── iter_skip_sloppy_test.go
├── iter_skip_strict.go
├── iter_str.go
├── jsoniter.go
├── misc_tests/
│ ├── jsoniter_array_test.go
│ ├── jsoniter_bool_test.go
│ ├── jsoniter_float_test.go
│ ├── jsoniter_int_test.go
│ ├── jsoniter_interface_test.go
│ ├── jsoniter_iterator_test.go
│ ├── jsoniter_map_test.go
│ ├── jsoniter_nested_test.go
│ ├── jsoniter_null_test.go
│ ├── jsoniter_object_test.go
│ └── jsoniter_raw_message_test.go
├── pool.go
├── reflect.go
├── reflect_array.go
├── reflect_dynamic.go
├── reflect_extension.go
├── reflect_json_number.go
├── reflect_json_raw_message.go
├── reflect_map.go
├── reflect_marshaler.go
├── reflect_native.go
├── reflect_optional.go
├── reflect_slice.go
├── reflect_struct_decoder.go
├── reflect_struct_encoder.go
├── skip_tests/
│ ├── array_test.go
│ ├── float64_test.go
│ ├── jsoniter_skip_test.go
│ ├── skip_test.go
│ ├── string_test.go
│ └── struct_test.go
├── stream.go
├── stream_float.go
├── stream_int.go
├── stream_str.go
├── stream_test.go
├── test.sh
├── type_tests/
│ ├── array_test.go
│ ├── builtin_test.go
│ ├── map_key_test.go
│ ├── map_test.go
│ ├── marshaler_string_test.go
│ ├── marshaler_struct_test.go
│ ├── slice_test.go
│ ├── struct_embedded_test.go
│ ├── struct_field_case_test.go
│ ├── struct_tags_test.go
│ ├── struct_test.go
│ ├── text_marshaler_string_test.go
│ ├── text_marshaler_struct_test.go
│ └── type_test.go
└── value_tests/
├── array_test.go
├── bool_test.go
├── eface_test.go
├── error_test.go
├── float_test.go
├── iface_test.go
├── int_test.go
├── invalid_test.go
├── map_test.go
├── marshaler_test.go
├── number_test.go
├── ptr_114_test.go
├── ptr_test.go
├── raw_message_test.go
├── slice_test.go
├── string_test.go
├── struct_test.go
└── value_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .codecov.yml
================================================
ignore:
- "output_tests/.*"
================================================
FILE: .gitignore
================================================
/vendor
/bug_test.go
/coverage.txt
/.idea
================================================
FILE: .travis.yml
================================================
language: go
go:
- 1.8.x
- 1.x
before_install:
- go get -t -v ./...
script:
- ./test.sh
after_success:
- bash <(curl -s https://codecov.io/bash)
================================================
FILE: Gopkg.toml
================================================
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"]
[[constraint]]
name = "github.com/modern-go/reflect2"
version = "1.0.1"
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2016 json-iterator
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.
================================================
FILE: README.md
================================================
[](https://sourcegraph.com/github.com/json-iterator/go?badge)
[](https://pkg.go.dev/github.com/json-iterator/go)
[](https://travis-ci.org/json-iterator/go)
[](https://codecov.io/gh/json-iterator/go)
[](https://goreportcard.com/report/github.com/json-iterator/go)
[](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE)
[](https://gitter.im/json-iterator/Lobby)
A high-performance 100% compatible drop-in replacement of "encoding/json"
# Benchmark

Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go
Raw Result (easyjson requires static code generation)
| | ns/op | allocation bytes | allocation times |
| --------------- | ----------- | ---------------- | ---------------- |
| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op |
| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op |
| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op |
| std encode | 2213 ns/op | 712 B/op | 5 allocs/op |
| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op |
| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op |
Always benchmark with your own workload.
The result depends heavily on the data input.
# Usage
100% compatibility with standard lib
Replace
```go
import "encoding/json"
json.Marshal(&data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)
```
Replace
```go
import "encoding/json"
json.Unmarshal(input, &data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Unmarshal(input, &data)
```
[More documentation](http://jsoniter.com/migrate-from-go-std.html)
# How to get
```
go get github.com/json-iterator/go
```
# Contribution Welcomed !
Contributors
- [thockin](https://github.com/thockin)
- [mattn](https://github.com/mattn)
- [cch123](https://github.com/cch123)
- [Oleg Shaldybin](https://github.com/olegshaldybin)
- [Jason Toffaletti](https://github.com/toffaletti)
Report issue or pull request, or email taowen@gmail.com, or [](https://gitter.im/json-iterator/Lobby)
================================================
FILE: adapter.go
================================================
package jsoniter
import (
"bytes"
"io"
)
// RawMessage to make replace json with jsoniter
type RawMessage []byte
// Unmarshal adapts to json/encoding Unmarshal API
//
// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
// Refer to https://godoc.org/encoding/json#Unmarshal for more information
func Unmarshal(data []byte, v interface{}) error {
return ConfigDefault.Unmarshal(data, v)
}
// UnmarshalFromString is a convenient method to read from string instead of []byte
func UnmarshalFromString(str string, v interface{}) error {
return ConfigDefault.UnmarshalFromString(str, v)
}
// Get quick method to get value from deeply nested JSON structure
func Get(data []byte, path ...interface{}) Any {
return ConfigDefault.Get(data, path...)
}
// Marshal adapts to json/encoding Marshal API
//
// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API
// Refer to https://godoc.org/encoding/json#Marshal for more information
func Marshal(v interface{}) ([]byte, error) {
return ConfigDefault.Marshal(v)
}
// MarshalIndent same as json.MarshalIndent. Prefix is not supported.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
return ConfigDefault.MarshalIndent(v, prefix, indent)
}
// MarshalToString convenient method to write as string instead of []byte
func MarshalToString(v interface{}) (string, error) {
return ConfigDefault.MarshalToString(v)
}
// NewDecoder adapts to json/stream NewDecoder API.
//
// NewDecoder returns a new decoder that reads from r.
//
// Instead of a json/encoding Decoder, an Decoder is returned
// Refer to https://godoc.org/encoding/json#NewDecoder for more information
func NewDecoder(reader io.Reader) *Decoder {
return ConfigDefault.NewDecoder(reader)
}
// Decoder reads and decodes JSON values from an input stream.
// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress)
type Decoder struct {
iter *Iterator
}
// Decode decode JSON into interface{}
func (adapter *Decoder) Decode(obj interface{}) error {
if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil {
if !adapter.iter.loadMore() {
return io.EOF
}
}
adapter.iter.ReadVal(obj)
err := adapter.iter.Error
if err == io.EOF {
return nil
}
return adapter.iter.Error
}
// More is there more?
func (adapter *Decoder) More() bool {
iter := adapter.iter
if iter.Error != nil {
return false
}
c := iter.nextToken()
if c == 0 {
return false
}
iter.unreadByte()
return c != ']' && c != '}'
}
// Buffered remaining buffer
func (adapter *Decoder) Buffered() io.Reader {
remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail]
return bytes.NewReader(remaining)
}
// UseNumber causes the Decoder to unmarshal a number into an interface{} as a
// Number instead of as a float64.
func (adapter *Decoder) UseNumber() {
cfg := adapter.iter.cfg.configBeforeFrozen
cfg.UseNumber = true
adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions)
}
// DisallowUnknownFields causes the Decoder to return an error when the destination
// is a struct and the input contains object keys which do not match any
// non-ignored, exported fields in the destination.
func (adapter *Decoder) DisallowUnknownFields() {
cfg := adapter.iter.cfg.configBeforeFrozen
cfg.DisallowUnknownFields = true
adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions)
}
// NewEncoder same as json.NewEncoder
func NewEncoder(writer io.Writer) *Encoder {
return ConfigDefault.NewEncoder(writer)
}
// Encoder same as json.Encoder
type Encoder struct {
stream *Stream
}
// Encode encode interface{} as JSON to io.Writer
func (adapter *Encoder) Encode(val interface{}) error {
adapter.stream.WriteVal(val)
adapter.stream.WriteRaw("\n")
adapter.stream.Flush()
return adapter.stream.Error
}
// SetIndent set the indention. Prefix is not supported
func (adapter *Encoder) SetIndent(prefix, indent string) {
config := adapter.stream.cfg.configBeforeFrozen
config.IndentionStep = len(indent)
adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions)
}
// SetEscapeHTML escape html by default, set to false to disable
func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) {
config := adapter.stream.cfg.configBeforeFrozen
config.EscapeHTML = escapeHTML
adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions)
}
// Valid reports whether data is a valid JSON encoding.
func Valid(data []byte) bool {
return ConfigDefault.Valid(data)
}
================================================
FILE: any.go
================================================
package jsoniter
import (
"errors"
"fmt"
"github.com/modern-go/reflect2"
"io"
"reflect"
"strconv"
"unsafe"
)
// Any generic object representation.
// The lazy json implementation holds []byte and parse lazily.
type Any interface {
LastError() error
ValueType() ValueType
MustBeValid() Any
ToBool() bool
ToInt() int
ToInt32() int32
ToInt64() int64
ToUint() uint
ToUint32() uint32
ToUint64() uint64
ToFloat32() float32
ToFloat64() float64
ToString() string
ToVal(val interface{})
Get(path ...interface{}) Any
Size() int
Keys() []string
GetInterface() interface{}
WriteTo(stream *Stream)
}
type baseAny struct{}
func (any *baseAny) Get(path ...interface{}) Any {
return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)}
}
func (any *baseAny) Size() int {
return 0
}
func (any *baseAny) Keys() []string {
return []string{}
}
func (any *baseAny) ToVal(obj interface{}) {
panic("not implemented")
}
// WrapInt32 turn int32 into Any interface
func WrapInt32(val int32) Any {
return &int32Any{baseAny{}, val}
}
// WrapInt64 turn int64 into Any interface
func WrapInt64(val int64) Any {
return &int64Any{baseAny{}, val}
}
// WrapUint32 turn uint32 into Any interface
func WrapUint32(val uint32) Any {
return &uint32Any{baseAny{}, val}
}
// WrapUint64 turn uint64 into Any interface
func WrapUint64(val uint64) Any {
return &uint64Any{baseAny{}, val}
}
// WrapFloat64 turn float64 into Any interface
func WrapFloat64(val float64) Any {
return &floatAny{baseAny{}, val}
}
// WrapString turn string into Any interface
func WrapString(val string) Any {
return &stringAny{baseAny{}, val}
}
// Wrap turn a go object into Any interface
func Wrap(val interface{}) Any {
if val == nil {
return &nilAny{}
}
asAny, isAny := val.(Any)
if isAny {
return asAny
}
typ := reflect2.TypeOf(val)
switch typ.Kind() {
case reflect.Slice:
return wrapArray(val)
case reflect.Struct:
return wrapStruct(val)
case reflect.Map:
return wrapMap(val)
case reflect.String:
return WrapString(val.(string))
case reflect.Int:
if strconv.IntSize == 32 {
return WrapInt32(int32(val.(int)))
}
return WrapInt64(int64(val.(int)))
case reflect.Int8:
return WrapInt32(int32(val.(int8)))
case reflect.Int16:
return WrapInt32(int32(val.(int16)))
case reflect.Int32:
return WrapInt32(val.(int32))
case reflect.Int64:
return WrapInt64(val.(int64))
case reflect.Uint:
if strconv.IntSize == 32 {
return WrapUint32(uint32(val.(uint)))
}
return WrapUint64(uint64(val.(uint)))
case reflect.Uintptr:
if ptrSize == 32 {
return WrapUint32(uint32(val.(uintptr)))
}
return WrapUint64(uint64(val.(uintptr)))
case reflect.Uint8:
return WrapUint32(uint32(val.(uint8)))
case reflect.Uint16:
return WrapUint32(uint32(val.(uint16)))
case reflect.Uint32:
return WrapUint32(uint32(val.(uint32)))
case reflect.Uint64:
return WrapUint64(val.(uint64))
case reflect.Float32:
return WrapFloat64(float64(val.(float32)))
case reflect.Float64:
return WrapFloat64(val.(float64))
case reflect.Bool:
if val.(bool) == true {
return &trueAny{}
}
return &falseAny{}
}
return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)}
}
// ReadAny read next JSON element as an Any object. It is a better json.RawMessage.
func (iter *Iterator) ReadAny() Any {
return iter.readAny()
}
func (iter *Iterator) readAny() Any {
c := iter.nextToken()
switch c {
case '"':
iter.unreadByte()
return &stringAny{baseAny{}, iter.ReadString()}
case 'n':
iter.skipThreeBytes('u', 'l', 'l') // null
return &nilAny{}
case 't':
iter.skipThreeBytes('r', 'u', 'e') // true
return &trueAny{}
case 'f':
iter.skipFourBytes('a', 'l', 's', 'e') // false
return &falseAny{}
case '{':
return iter.readObjectAny()
case '[':
return iter.readArrayAny()
case '-':
return iter.readNumberAny(false)
case 0:
return &invalidAny{baseAny{}, errors.New("input is empty")}
default:
return iter.readNumberAny(true)
}
}
func (iter *Iterator) readNumberAny(positive bool) Any {
iter.startCapture(iter.head - 1)
iter.skipNumber()
lazyBuf := iter.stopCapture()
return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func (iter *Iterator) readObjectAny() Any {
iter.startCapture(iter.head - 1)
iter.skipObject()
lazyBuf := iter.stopCapture()
return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func (iter *Iterator) readArrayAny() Any {
iter.startCapture(iter.head - 1)
iter.skipArray()
lazyBuf := iter.stopCapture()
return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func locateObjectField(iter *Iterator, target string) []byte {
var found []byte
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
if field == target {
found = iter.SkipAndReturnBytes()
return false
}
iter.Skip()
return true
})
return found
}
func locateArrayElement(iter *Iterator, target int) []byte {
var found []byte
n := 0
iter.ReadArrayCB(func(iter *Iterator) bool {
if n == target {
found = iter.SkipAndReturnBytes()
return false
}
iter.Skip()
n++
return true
})
return found
}
func locatePath(iter *Iterator, path []interface{}) Any {
for i, pathKeyObj := range path {
switch pathKey := pathKeyObj.(type) {
case string:
valueBytes := locateObjectField(iter, pathKey)
if valueBytes == nil {
return newInvalidAny(path[i:])
}
iter.ResetBytes(valueBytes)
case int:
valueBytes := locateArrayElement(iter, pathKey)
if valueBytes == nil {
return newInvalidAny(path[i:])
}
iter.ResetBytes(valueBytes)
case int32:
if '*' == pathKey {
return iter.readAny().Get(path[i:]...)
}
return newInvalidAny(path[i:])
default:
return newInvalidAny(path[i:])
}
}
if iter.Error != nil && iter.Error != io.EOF {
return &invalidAny{baseAny{}, iter.Error}
}
return iter.readAny()
}
var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem()
func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder {
if typ == anyType {
return &directAnyCodec{}
}
if typ.Implements(anyType) {
return &anyCodec{
valType: typ,
}
}
return nil
}
func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder {
if typ == anyType {
return &directAnyCodec{}
}
if typ.Implements(anyType) {
return &anyCodec{
valType: typ,
}
}
return nil
}
type anyCodec struct {
valType reflect2.Type
}
func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
panic("not implemented")
}
func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
obj := codec.valType.UnsafeIndirect(ptr)
any := obj.(Any)
any.WriteTo(stream)
}
func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
obj := codec.valType.UnsafeIndirect(ptr)
any := obj.(Any)
return any.Size() == 0
}
type directAnyCodec struct {
}
func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
*(*Any)(ptr) = iter.readAny()
}
func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
any := *(*Any)(ptr)
if any == nil {
stream.WriteNil()
return
}
any.WriteTo(stream)
}
func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool {
any := *(*Any)(ptr)
return any.Size() == 0
}
================================================
FILE: any_array.go
================================================
package jsoniter
import (
"reflect"
"unsafe"
)
type arrayLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *arrayLazyAny) ValueType() ValueType {
return ArrayValue
}
func (any *arrayLazyAny) MustBeValid() Any {
return any
}
func (any *arrayLazyAny) LastError() error {
return any.err
}
func (any *arrayLazyAny) ToBool() bool {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.ReadArray()
}
func (any *arrayLazyAny) ToInt() int {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToInt32() int32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToInt64() int64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint() uint {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint32() uint32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint64() uint64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToFloat32() float32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToFloat64() float64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *arrayLazyAny) ToVal(val interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(val)
}
func (any *arrayLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int:
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
valueBytes := locateArrayElement(iter, firstPath)
if valueBytes == nil {
return newInvalidAny(path)
}
iter.ResetBytes(valueBytes)
return locatePath(iter, path[1:])
case int32:
if '*' == firstPath {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
arr := make([]Any, 0)
iter.ReadArrayCB(func(iter *Iterator) bool {
found := iter.readAny().Get(path[1:]...)
if found.ValueType() != InvalidValue {
arr = append(arr, found)
}
return true
})
return wrapArray(arr)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *arrayLazyAny) Size() int {
size := 0
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadArrayCB(func(iter *Iterator) bool {
size++
iter.Skip()
return true
})
return size
}
func (any *arrayLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *arrayLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}
type arrayAny struct {
baseAny
val reflect.Value
}
func wrapArray(val interface{}) *arrayAny {
return &arrayAny{baseAny{}, reflect.ValueOf(val)}
}
func (any *arrayAny) ValueType() ValueType {
return ArrayValue
}
func (any *arrayAny) MustBeValid() Any {
return any
}
func (any *arrayAny) LastError() error {
return nil
}
func (any *arrayAny) ToBool() bool {
return any.val.Len() != 0
}
func (any *arrayAny) ToInt() int {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToInt32() int32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToInt64() int64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint() uint {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint32() uint32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint64() uint64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToFloat32() float32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToFloat64() float64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToString() string {
str, _ := MarshalToString(any.val.Interface())
return str
}
func (any *arrayAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int:
if firstPath < 0 || firstPath >= any.val.Len() {
return newInvalidAny(path)
}
return Wrap(any.val.Index(firstPath).Interface())
case int32:
if '*' == firstPath {
mappedAll := make([]Any, 0)
for i := 0; i < any.val.Len(); i++ {
mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll = append(mappedAll, mapped)
}
}
return wrapArray(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *arrayAny) Size() int {
return any.val.Len()
}
func (any *arrayAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *arrayAny) GetInterface() interface{} {
return any.val.Interface()
}
================================================
FILE: any_bool.go
================================================
package jsoniter
type trueAny struct {
baseAny
}
func (any *trueAny) LastError() error {
return nil
}
func (any *trueAny) ToBool() bool {
return true
}
func (any *trueAny) ToInt() int {
return 1
}
func (any *trueAny) ToInt32() int32 {
return 1
}
func (any *trueAny) ToInt64() int64 {
return 1
}
func (any *trueAny) ToUint() uint {
return 1
}
func (any *trueAny) ToUint32() uint32 {
return 1
}
func (any *trueAny) ToUint64() uint64 {
return 1
}
func (any *trueAny) ToFloat32() float32 {
return 1
}
func (any *trueAny) ToFloat64() float64 {
return 1
}
func (any *trueAny) ToString() string {
return "true"
}
func (any *trueAny) WriteTo(stream *Stream) {
stream.WriteTrue()
}
func (any *trueAny) Parse() *Iterator {
return nil
}
func (any *trueAny) GetInterface() interface{} {
return true
}
func (any *trueAny) ValueType() ValueType {
return BoolValue
}
func (any *trueAny) MustBeValid() Any {
return any
}
type falseAny struct {
baseAny
}
func (any *falseAny) LastError() error {
return nil
}
func (any *falseAny) ToBool() bool {
return false
}
func (any *falseAny) ToInt() int {
return 0
}
func (any *falseAny) ToInt32() int32 {
return 0
}
func (any *falseAny) ToInt64() int64 {
return 0
}
func (any *falseAny) ToUint() uint {
return 0
}
func (any *falseAny) ToUint32() uint32 {
return 0
}
func (any *falseAny) ToUint64() uint64 {
return 0
}
func (any *falseAny) ToFloat32() float32 {
return 0
}
func (any *falseAny) ToFloat64() float64 {
return 0
}
func (any *falseAny) ToString() string {
return "false"
}
func (any *falseAny) WriteTo(stream *Stream) {
stream.WriteFalse()
}
func (any *falseAny) Parse() *Iterator {
return nil
}
func (any *falseAny) GetInterface() interface{} {
return false
}
func (any *falseAny) ValueType() ValueType {
return BoolValue
}
func (any *falseAny) MustBeValid() Any {
return any
}
================================================
FILE: any_float.go
================================================
package jsoniter
import (
"strconv"
)
type floatAny struct {
baseAny
val float64
}
func (any *floatAny) Parse() *Iterator {
return nil
}
func (any *floatAny) ValueType() ValueType {
return NumberValue
}
func (any *floatAny) MustBeValid() Any {
return any
}
func (any *floatAny) LastError() error {
return nil
}
func (any *floatAny) ToBool() bool {
return any.ToFloat64() != 0
}
func (any *floatAny) ToInt() int {
return int(any.val)
}
func (any *floatAny) ToInt32() int32 {
return int32(any.val)
}
func (any *floatAny) ToInt64() int64 {
return int64(any.val)
}
func (any *floatAny) ToUint() uint {
if any.val > 0 {
return uint(any.val)
}
return 0
}
func (any *floatAny) ToUint32() uint32 {
if any.val > 0 {
return uint32(any.val)
}
return 0
}
func (any *floatAny) ToUint64() uint64 {
if any.val > 0 {
return uint64(any.val)
}
return 0
}
func (any *floatAny) ToFloat32() float32 {
return float32(any.val)
}
func (any *floatAny) ToFloat64() float64 {
return any.val
}
func (any *floatAny) ToString() string {
return strconv.FormatFloat(any.val, 'E', -1, 64)
}
func (any *floatAny) WriteTo(stream *Stream) {
stream.WriteFloat64(any.val)
}
func (any *floatAny) GetInterface() interface{} {
return any.val
}
================================================
FILE: any_int32.go
================================================
package jsoniter
import (
"strconv"
)
type int32Any struct {
baseAny
val int32
}
func (any *int32Any) LastError() error {
return nil
}
func (any *int32Any) ValueType() ValueType {
return NumberValue
}
func (any *int32Any) MustBeValid() Any {
return any
}
func (any *int32Any) ToBool() bool {
return any.val != 0
}
func (any *int32Any) ToInt() int {
return int(any.val)
}
func (any *int32Any) ToInt32() int32 {
return any.val
}
func (any *int32Any) ToInt64() int64 {
return int64(any.val)
}
func (any *int32Any) ToUint() uint {
return uint(any.val)
}
func (any *int32Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *int32Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *int32Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *int32Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *int32Any) ToString() string {
return strconv.FormatInt(int64(any.val), 10)
}
func (any *int32Any) WriteTo(stream *Stream) {
stream.WriteInt32(any.val)
}
func (any *int32Any) Parse() *Iterator {
return nil
}
func (any *int32Any) GetInterface() interface{} {
return any.val
}
================================================
FILE: any_int64.go
================================================
package jsoniter
import (
"strconv"
)
type int64Any struct {
baseAny
val int64
}
func (any *int64Any) LastError() error {
return nil
}
func (any *int64Any) ValueType() ValueType {
return NumberValue
}
func (any *int64Any) MustBeValid() Any {
return any
}
func (any *int64Any) ToBool() bool {
return any.val != 0
}
func (any *int64Any) ToInt() int {
return int(any.val)
}
func (any *int64Any) ToInt32() int32 {
return int32(any.val)
}
func (any *int64Any) ToInt64() int64 {
return any.val
}
func (any *int64Any) ToUint() uint {
return uint(any.val)
}
func (any *int64Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *int64Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *int64Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *int64Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *int64Any) ToString() string {
return strconv.FormatInt(any.val, 10)
}
func (any *int64Any) WriteTo(stream *Stream) {
stream.WriteInt64(any.val)
}
func (any *int64Any) Parse() *Iterator {
return nil
}
func (any *int64Any) GetInterface() interface{} {
return any.val
}
================================================
FILE: any_invalid.go
================================================
package jsoniter
import "fmt"
type invalidAny struct {
baseAny
err error
}
func newInvalidAny(path []interface{}) *invalidAny {
return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)}
}
func (any *invalidAny) LastError() error {
return any.err
}
func (any *invalidAny) ValueType() ValueType {
return InvalidValue
}
func (any *invalidAny) MustBeValid() Any {
panic(any.err)
}
func (any *invalidAny) ToBool() bool {
return false
}
func (any *invalidAny) ToInt() int {
return 0
}
func (any *invalidAny) ToInt32() int32 {
return 0
}
func (any *invalidAny) ToInt64() int64 {
return 0
}
func (any *invalidAny) ToUint() uint {
return 0
}
func (any *invalidAny) ToUint32() uint32 {
return 0
}
func (any *invalidAny) ToUint64() uint64 {
return 0
}
func (any *invalidAny) ToFloat32() float32 {
return 0
}
func (any *invalidAny) ToFloat64() float64 {
return 0
}
func (any *invalidAny) ToString() string {
return ""
}
func (any *invalidAny) WriteTo(stream *Stream) {
}
func (any *invalidAny) Get(path ...interface{}) Any {
if any.err == nil {
return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)}
}
return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)}
}
func (any *invalidAny) Parse() *Iterator {
return nil
}
func (any *invalidAny) GetInterface() interface{} {
return nil
}
================================================
FILE: any_nil.go
================================================
package jsoniter
type nilAny struct {
baseAny
}
func (any *nilAny) LastError() error {
return nil
}
func (any *nilAny) ValueType() ValueType {
return NilValue
}
func (any *nilAny) MustBeValid() Any {
return any
}
func (any *nilAny) ToBool() bool {
return false
}
func (any *nilAny) ToInt() int {
return 0
}
func (any *nilAny) ToInt32() int32 {
return 0
}
func (any *nilAny) ToInt64() int64 {
return 0
}
func (any *nilAny) ToUint() uint {
return 0
}
func (any *nilAny) ToUint32() uint32 {
return 0
}
func (any *nilAny) ToUint64() uint64 {
return 0
}
func (any *nilAny) ToFloat32() float32 {
return 0
}
func (any *nilAny) ToFloat64() float64 {
return 0
}
func (any *nilAny) ToString() string {
return ""
}
func (any *nilAny) WriteTo(stream *Stream) {
stream.WriteNil()
}
func (any *nilAny) Parse() *Iterator {
return nil
}
func (any *nilAny) GetInterface() interface{} {
return nil
}
================================================
FILE: any_number.go
================================================
package jsoniter
import (
"io"
"unsafe"
)
type numberLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *numberLazyAny) ValueType() ValueType {
return NumberValue
}
func (any *numberLazyAny) MustBeValid() Any {
return any
}
func (any *numberLazyAny) LastError() error {
return any.err
}
func (any *numberLazyAny) ToBool() bool {
return any.ToFloat64() != 0
}
func (any *numberLazyAny) ToInt() int {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToInt32() int32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToInt64() int64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint() uint {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint32() uint32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint64() uint64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToFloat32() float32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadFloat32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToFloat64() float64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadFloat64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *numberLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *numberLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}
================================================
FILE: any_object.go
================================================
package jsoniter
import (
"reflect"
"unsafe"
)
type objectLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *objectLazyAny) ValueType() ValueType {
return ObjectValue
}
func (any *objectLazyAny) MustBeValid() Any {
return any
}
func (any *objectLazyAny) LastError() error {
return any.err
}
func (any *objectLazyAny) ToBool() bool {
return true
}
func (any *objectLazyAny) ToInt() int {
return 0
}
func (any *objectLazyAny) ToInt32() int32 {
return 0
}
func (any *objectLazyAny) ToInt64() int64 {
return 0
}
func (any *objectLazyAny) ToUint() uint {
return 0
}
func (any *objectLazyAny) ToUint32() uint32 {
return 0
}
func (any *objectLazyAny) ToUint64() uint64 {
return 0
}
func (any *objectLazyAny) ToFloat32() float32 {
return 0
}
func (any *objectLazyAny) ToFloat64() float64 {
return 0
}
func (any *objectLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *objectLazyAny) ToVal(obj interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(obj)
}
func (any *objectLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case string:
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
valueBytes := locateObjectField(iter, firstPath)
if valueBytes == nil {
return newInvalidAny(path)
}
iter.ResetBytes(valueBytes)
return locatePath(iter, path[1:])
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadMapCB(func(iter *Iterator, field string) bool {
mapped := locatePath(iter, path[1:])
if mapped.ValueType() != InvalidValue {
mappedAll[field] = mapped
}
return true
})
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *objectLazyAny) Keys() []string {
keys := []string{}
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadMapCB(func(iter *Iterator, field string) bool {
iter.Skip()
keys = append(keys, field)
return true
})
return keys
}
func (any *objectLazyAny) Size() int {
size := 0
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
iter.Skip()
size++
return true
})
return size
}
func (any *objectLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *objectLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}
type objectAny struct {
baseAny
err error
val reflect.Value
}
func wrapStruct(val interface{}) *objectAny {
return &objectAny{baseAny{}, nil, reflect.ValueOf(val)}
}
func (any *objectAny) ValueType() ValueType {
return ObjectValue
}
func (any *objectAny) MustBeValid() Any {
return any
}
func (any *objectAny) Parse() *Iterator {
return nil
}
func (any *objectAny) LastError() error {
return any.err
}
func (any *objectAny) ToBool() bool {
return any.val.NumField() != 0
}
func (any *objectAny) ToInt() int {
return 0
}
func (any *objectAny) ToInt32() int32 {
return 0
}
func (any *objectAny) ToInt64() int64 {
return 0
}
func (any *objectAny) ToUint() uint {
return 0
}
func (any *objectAny) ToUint32() uint32 {
return 0
}
func (any *objectAny) ToUint64() uint64 {
return 0
}
func (any *objectAny) ToFloat32() float32 {
return 0
}
func (any *objectAny) ToFloat64() float64 {
return 0
}
func (any *objectAny) ToString() string {
str, err := MarshalToString(any.val.Interface())
any.err = err
return str
}
func (any *objectAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case string:
field := any.val.FieldByName(firstPath)
if !field.IsValid() {
return newInvalidAny(path)
}
return Wrap(field.Interface())
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
for i := 0; i < any.val.NumField(); i++ {
field := any.val.Field(i)
if field.CanInterface() {
mapped := Wrap(field.Interface()).Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll[any.val.Type().Field(i).Name] = mapped
}
}
}
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *objectAny) Keys() []string {
keys := make([]string, 0, any.val.NumField())
for i := 0; i < any.val.NumField(); i++ {
keys = append(keys, any.val.Type().Field(i).Name)
}
return keys
}
func (any *objectAny) Size() int {
return any.val.NumField()
}
func (any *objectAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *objectAny) GetInterface() interface{} {
return any.val.Interface()
}
type mapAny struct {
baseAny
err error
val reflect.Value
}
func wrapMap(val interface{}) *mapAny {
return &mapAny{baseAny{}, nil, reflect.ValueOf(val)}
}
func (any *mapAny) ValueType() ValueType {
return ObjectValue
}
func (any *mapAny) MustBeValid() Any {
return any
}
func (any *mapAny) Parse() *Iterator {
return nil
}
func (any *mapAny) LastError() error {
return any.err
}
func (any *mapAny) ToBool() bool {
return true
}
func (any *mapAny) ToInt() int {
return 0
}
func (any *mapAny) ToInt32() int32 {
return 0
}
func (any *mapAny) ToInt64() int64 {
return 0
}
func (any *mapAny) ToUint() uint {
return 0
}
func (any *mapAny) ToUint32() uint32 {
return 0
}
func (any *mapAny) ToUint64() uint64 {
return 0
}
func (any *mapAny) ToFloat32() float32 {
return 0
}
func (any *mapAny) ToFloat64() float64 {
return 0
}
func (any *mapAny) ToString() string {
str, err := MarshalToString(any.val.Interface())
any.err = err
return str
}
func (any *mapAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
for _, key := range any.val.MapKeys() {
keyAsStr := key.String()
element := Wrap(any.val.MapIndex(key).Interface())
mapped := element.Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll[keyAsStr] = mapped
}
}
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
value := any.val.MapIndex(reflect.ValueOf(firstPath))
if !value.IsValid() {
return newInvalidAny(path)
}
return Wrap(value.Interface())
}
}
func (any *mapAny) Keys() []string {
keys := make([]string, 0, any.val.Len())
for _, key := range any.val.MapKeys() {
keys = append(keys, key.String())
}
return keys
}
func (any *mapAny) Size() int {
return any.val.Len()
}
func (any *mapAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *mapAny) GetInterface() interface{} {
return any.val.Interface()
}
================================================
FILE: any_str.go
================================================
package jsoniter
import (
"fmt"
"strconv"
)
type stringAny struct {
baseAny
val string
}
func (any *stringAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)}
}
func (any *stringAny) Parse() *Iterator {
return nil
}
func (any *stringAny) ValueType() ValueType {
return StringValue
}
func (any *stringAny) MustBeValid() Any {
return any
}
func (any *stringAny) LastError() error {
return nil
}
func (any *stringAny) ToBool() bool {
str := any.ToString()
if str == "0" {
return false
}
for _, c := range str {
switch c {
case ' ', '\n', '\r', '\t':
default:
return true
}
}
return false
}
func (any *stringAny) ToInt() int {
return int(any.ToInt64())
}
func (any *stringAny) ToInt32() int32 {
return int32(any.ToInt64())
}
func (any *stringAny) ToInt64() int64 {
if any.val == "" {
return 0
}
flag := 1
startPos := 0
if any.val[0] == '+' || any.val[0] == '-' {
startPos = 1
}
if any.val[0] == '-' {
flag = -1
}
endPos := startPos
for i := startPos; i < len(any.val); i++ {
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
break
}
}
parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64)
return int64(flag) * parsed
}
func (any *stringAny) ToUint() uint {
return uint(any.ToUint64())
}
func (any *stringAny) ToUint32() uint32 {
return uint32(any.ToUint64())
}
func (any *stringAny) ToUint64() uint64 {
if any.val == "" {
return 0
}
startPos := 0
if any.val[0] == '-' {
return 0
}
if any.val[0] == '+' {
startPos = 1
}
endPos := startPos
for i := startPos; i < len(any.val); i++ {
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
break
}
}
parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64)
return parsed
}
func (any *stringAny) ToFloat32() float32 {
return float32(any.ToFloat64())
}
func (any *stringAny) ToFloat64() float64 {
if len(any.val) == 0 {
return 0
}
// first char invalid
if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') {
return 0
}
// extract valid num expression from string
// eg 123true => 123, -12.12xxa => -12.12
endPos := 1
for i := 1; i < len(any.val); i++ {
if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' {
endPos = i + 1
continue
}
// end position is the first char which is not digit
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
endPos = i
break
}
}
parsed, _ := strconv.ParseFloat(any.val[:endPos], 64)
return parsed
}
func (any *stringAny) ToString() string {
return any.val
}
func (any *stringAny) WriteTo(stream *Stream) {
stream.WriteString(any.val)
}
func (any *stringAny) GetInterface() interface{} {
return any.val
}
================================================
FILE: any_tests/jsoniter_any_array_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func Test_read_empty_array_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[]"))
should.Equal(jsoniter.ArrayValue, any.Get().ValueType())
should.Equal(jsoniter.InvalidValue, any.Get(0.3).ValueType())
should.Equal(0, any.Size())
should.Equal(jsoniter.ArrayValue, any.ValueType())
should.Nil(any.LastError())
should.Equal(0, any.ToInt())
should.Equal(int32(0), any.ToInt32())
should.Equal(int64(0), any.ToInt64())
should.Equal(uint(0), any.ToUint())
should.Equal(uint32(0), any.ToUint32())
should.Equal(uint64(0), any.ToUint64())
should.Equal(float32(0), any.ToFloat32())
should.Equal(float64(0), any.ToFloat64())
}
func Test_read_one_element_array_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[1]"))
should.Equal(1, any.Size())
}
func Test_read_two_element_array_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[1,2]"))
should.Equal(1, any.Get(0).ToInt())
should.Equal(2, any.Size())
should.True(any.ToBool())
should.Equal(1, any.ToInt())
should.Equal([]interface{}{float64(1), float64(2)}, any.GetInterface())
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("[1,2]", string(stream.Buffer()))
arr := []int{}
any.ToVal(&arr)
should.Equal([]int{1, 2}, arr)
}
func Test_wrap_array_and_convert_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap([]int{1, 2, 3})
any2 := jsoniter.Wrap([]int{})
should.Equal("[1,2,3]", any.ToString())
should.True(any.ToBool())
should.False(any2.ToBool())
should.Equal(1, any.ToInt())
should.Equal(0, any2.ToInt())
should.Equal(int32(1), any.ToInt32())
should.Equal(int32(0), any2.ToInt32())
should.Equal(int64(1), any.ToInt64())
should.Equal(int64(0), any2.ToInt64())
should.Equal(uint(1), any.ToUint())
should.Equal(uint(0), any2.ToUint())
should.Equal(uint32(1), any.ToUint32())
should.Equal(uint32(0), any2.ToUint32())
should.Equal(uint64(1), any.ToUint64())
should.Equal(uint64(0), any2.ToUint64())
should.Equal(float32(1), any.ToFloat32())
should.Equal(float32(0), any2.ToFloat32())
should.Equal(float64(1), any.ToFloat64())
should.Equal(float64(0), any2.ToFloat64())
should.Equal(3, any.Size())
should.Equal(0, any2.Size())
var i interface{} = []int{1, 2, 3}
should.Equal(i, any.GetInterface())
}
func Test_array_lazy_any_get(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[1,[2,3],4]"))
should.Equal(3, any.Get(1, 1).ToInt())
should.Equal("[1,[2,3],4]", any.ToString())
}
func Test_array_lazy_any_get_all(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[[1],[2],[3,4]]"))
should.Equal("[1,2,3]", any.Get('*', 0).ToString())
any = jsoniter.Get([]byte("[[[1],[2],[3,4]]]"), 0, '*', 0)
should.Equal("[1,2,3]", any.ToString())
}
func Test_array_wrapper_any_get_all(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap([][]int{
{1, 2},
{3, 4},
{5, 6},
})
should.Equal("[1,3,5]", any.Get('*', 0).ToString())
should.Equal(jsoniter.ArrayValue, any.ValueType())
should.True(any.ToBool())
should.Equal(1, any.Get(0, 0).ToInt())
}
func Test_array_lazy_any_get_invalid(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("[]"))
should.Equal(jsoniter.InvalidValue, any.Get(1, 1).ValueType())
should.NotNil(any.Get(1, 1).LastError())
should.Equal(jsoniter.InvalidValue, any.Get("1").ValueType())
should.NotNil(any.Get("1").LastError())
}
func Test_invalid_array(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("["), 0)
should.Equal(jsoniter.InvalidValue, any.ValueType())
}
================================================
FILE: any_tests/jsoniter_any_bool_test.go
================================================
package any_tests
import (
"fmt"
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
var boolConvertMap = map[string]bool{
"null": false,
"true": true,
"false": false,
`"true"`: true,
`"false"`: true,
"123": true,
`"123"`: true,
"0": false,
`"0"`: false,
"-1": true,
`"-1"`: true,
"1.1": true,
"0.0": false,
"-1.1": true,
`""`: false,
"[1,2]": true,
"[]": false,
"{}": true,
`{"abc":1}`: true,
}
func Test_read_bool_as_any(t *testing.T) {
should := require.New(t)
var any jsoniter.Any
for k, v := range boolConvertMap {
any = jsoniter.Get([]byte(k))
if v {
should.True(any.ToBool(), fmt.Sprintf("origin val is %v", k))
} else {
should.False(any.ToBool(), fmt.Sprintf("origin val is %v", k))
}
}
}
func Test_write_bool_to_stream(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("true"))
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("true", string(stream.Buffer()))
should.Equal(any.ValueType(), jsoniter.BoolValue)
any = jsoniter.Get([]byte("false"))
stream = jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("false", string(stream.Buffer()))
should.Equal(any.ValueType(), jsoniter.BoolValue)
}
================================================
FILE: any_tests/jsoniter_any_float_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
var floatConvertMap = map[string]float64{
"null": 0,
"true": 1,
"false": 0,
`"true"`: 0,
`"false"`: 0,
"1e1": 10,
"1e+1": 10,
"1e-1": .1,
"1E1": 10,
"1E+1": 10,
"1E-1": .1,
"-1e1": -10,
"-1e+1": -10,
"-1e-1": -.1,
"-1E1": -10,
"-1E+1": -10,
"-1E-1": -.1,
`"1e1"`: 10,
`"1e+1"`: 10,
`"1e-1"`: .1,
`"1E1"`: 10,
`"1E+1"`: 10,
`"1E-1"`: .1,
`"-1e1"`: -10,
`"-1e+1"`: -10,
`"-1e-1"`: -.1,
`"-1E1"`: -10,
`"-1E+1"`: -10,
`"-1E-1"`: -.1,
"123": 123,
`"123true"`: 123,
`"+"`: 0,
`"-"`: 0,
`"-123true"`: -123,
`"-99.9true"`: -99.9,
"0": 0,
`"0"`: 0,
"-1": -1,
"1.1": 1.1,
"0.0": 0,
"-1.1": -1.1,
`"+1.1"`: 1.1,
`""`: 0,
"[1,2]": 1,
"[]": 0,
"{}": 0,
`{"abc":1}`: 0,
}
func Test_read_any_to_float(t *testing.T) {
should := require.New(t)
for k, v := range floatConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(float64(v), any.ToFloat64(), "the original val is "+k)
}
for k, v := range floatConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(float32(v), any.ToFloat32(), "the original val is "+k)
}
}
func Test_read_float_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.WrapFloat64(12.3)
anyFloat64 := float64(12.3)
any2 := jsoniter.WrapFloat64(-1.1)
should.Equal(float64(12.3), any.ToFloat64())
should.True(any.ToBool())
should.Equal(float32(anyFloat64), any.ToFloat32())
should.Equal(int(anyFloat64), any.ToInt())
should.Equal(int32(anyFloat64), any.ToInt32())
should.Equal(int64(anyFloat64), any.ToInt64())
should.Equal(uint(anyFloat64), any.ToUint())
should.Equal(uint32(anyFloat64), any.ToUint32())
should.Equal(uint64(anyFloat64), any.ToUint64())
should.Equal(uint(0), any2.ToUint())
should.Equal(uint32(0), any2.ToUint32())
should.Equal(uint64(0), any2.ToUint64())
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal("1.23E+01", any.ToString())
}
================================================
FILE: any_tests/jsoniter_any_int_test.go
================================================
package any_tests
import (
"fmt"
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
var intConvertMap = map[string]int{
"null": 0,
"321.1": 321,
"-321.1": -321,
`"1.1"`: 1,
`"-321.1"`: -321,
"0.0": 0,
"0": 0,
`"0"`: 0,
`"0.0"`: 0,
"-1.1": -1,
"true": 1,
"false": 0,
`"true"`: 0,
`"false"`: 0,
`"true123"`: 0,
`"123true"`: 123,
`"-123true"`: -123,
`"1.2332e6"`: 1,
`""`: 0,
"+": 0,
"-": 0,
"[]": 0,
"[1,2]": 1,
`["1","2"]`: 1,
// object in php cannot convert to int
"{}": 0,
}
func Test_read_any_to_int(t *testing.T) {
should := require.New(t)
// int
for k, v := range intConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(v, any.ToInt(), fmt.Sprintf("origin val %v", k))
}
// int32
for k, v := range intConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(int32(v), any.ToInt32(), fmt.Sprintf("original val is %v", k))
}
// int64
for k, v := range intConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(int64(v), any.ToInt64(), fmt.Sprintf("original val is %v", k))
}
}
var uintConvertMap = map[string]int{
"null": 0,
"321.1": 321,
`"1.1"`: 1,
`"-123.1"`: 0,
"0.0": 0,
"0": 0,
`"0"`: 0,
`"0.0"`: 0,
`"00.0"`: 0,
"true": 1,
"false": 0,
`"true"`: 0,
`"false"`: 0,
`"true123"`: 0,
`"+1"`: 1,
`"123true"`: 123,
`"-123true"`: 0,
`"1.2332e6"`: 1,
`""`: 0,
"+": 0,
"-": 0,
".": 0,
"[]": 0,
"[1,2]": 1,
"{}": 0,
"{1,2}": 0,
"-1.1": 0,
"-321.1": 0,
}
func Test_read_any_to_uint(t *testing.T) {
should := require.New(t)
for k, v := range uintConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(uint64(v), any.ToUint64(), fmt.Sprintf("origin val %v", k))
}
for k, v := range uintConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
}
for k, v := range uintConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(uint(v), any.ToUint(), fmt.Sprintf("origin val %v", k))
}
}
func Test_read_int64_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.WrapInt64(12345)
should.Equal(12345, any.ToInt())
should.Equal(int32(12345), any.ToInt32())
should.Equal(int64(12345), any.ToInt64())
should.Equal(uint(12345), any.ToUint())
should.Equal(uint32(12345), any.ToUint32())
should.Equal(uint64(12345), any.ToUint64())
should.Equal(float32(12345), any.ToFloat32())
should.Equal(float64(12345), any.ToFloat64())
should.Equal("12345", any.ToString())
should.Equal(true, any.ToBool())
should.Equal(any.ValueType(), jsoniter.NumberValue)
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("12345", string(stream.Buffer()))
}
func Test_read_int32_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.WrapInt32(12345)
should.Equal(12345, any.ToInt())
should.Equal(int32(12345), any.ToInt32())
should.Equal(int64(12345), any.ToInt64())
should.Equal(uint(12345), any.ToUint())
should.Equal(uint32(12345), any.ToUint32())
should.Equal(uint64(12345), any.ToUint64())
should.Equal(float32(12345), any.ToFloat32())
should.Equal(float64(12345), any.ToFloat64())
should.Equal("12345", any.ToString())
should.Equal(true, any.ToBool())
should.Equal(any.ValueType(), jsoniter.NumberValue)
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("12345", string(stream.Buffer()))
}
func Test_read_uint32_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.WrapUint32(12345)
should.Equal(12345, any.ToInt())
should.Equal(int32(12345), any.ToInt32())
should.Equal(int64(12345), any.ToInt64())
should.Equal(uint(12345), any.ToUint())
should.Equal(uint32(12345), any.ToUint32())
should.Equal(uint64(12345), any.ToUint64())
should.Equal(float32(12345), any.ToFloat32())
should.Equal(float64(12345), any.ToFloat64())
should.Equal("12345", any.ToString())
should.Equal(true, any.ToBool())
should.Equal(any.ValueType(), jsoniter.NumberValue)
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("12345", string(stream.Buffer()))
}
func Test_read_uint64_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.WrapUint64(12345)
should.Equal(12345, any.ToInt())
should.Equal(int32(12345), any.ToInt32())
should.Equal(int64(12345), any.ToInt64())
should.Equal(uint(12345), any.ToUint())
should.Equal(uint32(12345), any.ToUint32())
should.Equal(uint64(12345), any.ToUint64())
should.Equal(float32(12345), any.ToFloat32())
should.Equal(float64(12345), any.ToFloat64())
should.Equal("12345", any.ToString())
should.Equal(true, any.ToBool())
should.Equal(any.ValueType(), jsoniter.NumberValue)
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("12345", string(stream.Buffer()))
stream = jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
stream.WriteUint(uint(123))
should.Equal("123", string(stream.Buffer()))
}
func Test_int_lazy_any_get(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("1234"))
// panic!!
//should.Equal(any.LastError(), io.EOF)
should.Equal(jsoniter.InvalidValue, any.Get(1, "2").ValueType())
}
================================================
FILE: any_tests/jsoniter_any_map_test.go
================================================
package any_tests
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func Test_wrap_map(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap(map[string]string{"Field1": "hello"})
should.Equal("hello", any.Get("Field1").ToString())
any = jsoniter.Wrap(map[string]string{"Field1": "hello"})
should.Equal(1, any.Size())
}
func Test_map_wrapper_any_get_all(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap(map[string][]int{"Field1": {1, 2}})
should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString())
should.Contains(any.Keys(), "Field1")
// map write to
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 0)
any.WriteTo(stream)
// TODO cannot pass
//should.Equal(string(stream.buf), "")
}
================================================
FILE: any_tests/jsoniter_any_null_test.go
================================================
package any_tests
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func Test_read_null_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`null`))
should.Equal(0, any.ToInt())
should.Equal(float64(0), any.ToFloat64())
should.Equal("", any.ToString())
should.False(any.ToBool())
}
================================================
FILE: any_tests/jsoniter_any_object_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func Test_read_object_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`{"a":"stream","c":"d"}`))
should.Equal(`{"a":"stream","c":"d"}`, any.ToString())
// partial parse
should.Equal("stream", any.Get("a").ToString())
should.Equal("d", any.Get("c").ToString())
should.Equal(2, len(any.Keys()))
any = jsoniter.Get([]byte(`{"a":"stream","c":"d"}`))
// full parse
should.Equal(2, len(any.Keys()))
should.Equal(2, any.Size())
should.True(any.ToBool())
should.Equal(0, any.ToInt())
should.Equal(jsoniter.ObjectValue, any.ValueType())
should.Nil(any.LastError())
obj := struct {
A string
}{}
any.ToVal(&obj)
should.Equal("stream", obj.A)
}
func Test_object_lazy_any_get(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`{"a":{"stream":{"c":"d"}}}`))
should.Equal("d", any.Get("a", "stream", "c").ToString())
}
func Test_object_lazy_any_get_all(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`{"a":[0],"stream":[1]}`))
should.Contains(any.Get('*', 0).ToString(), `"a":0`)
}
func Test_object_lazy_any_get_invalid(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`{}`))
should.Equal(jsoniter.InvalidValue, any.Get("a", "stream", "c").ValueType())
should.Equal(jsoniter.InvalidValue, any.Get(1).ValueType())
}
func Test_wrap_map_and_convert_to_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap(map[string]interface{}{"a": 1})
should.True(any.ToBool())
should.Equal(0, any.ToInt())
should.Equal(int32(0), any.ToInt32())
should.Equal(int64(0), any.ToInt64())
should.Equal(float32(0), any.ToFloat32())
should.Equal(float64(0), any.ToFloat64())
should.Equal(uint(0), any.ToUint())
should.Equal(uint32(0), any.ToUint32())
should.Equal(uint64(0), any.ToUint64())
}
func Test_wrap_object_and_convert_to_any(t *testing.T) {
should := require.New(t)
type TestObject struct {
Field1 string
field2 string
}
any := jsoniter.Wrap(TestObject{"hello", "world"})
should.Equal("hello", any.Get("Field1").ToString())
any = jsoniter.Wrap(TestObject{"hello", "world"})
should.Equal(2, any.Size())
should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString())
should.Equal(0, any.ToInt())
should.Equal(int32(0), any.ToInt32())
should.Equal(int64(0), any.ToInt64())
should.Equal(float32(0), any.ToFloat32())
should.Equal(float64(0), any.ToFloat64())
should.Equal(uint(0), any.ToUint())
should.Equal(uint32(0), any.ToUint32())
should.Equal(uint64(0), any.ToUint64())
should.True(any.ToBool())
should.Equal(`{"Field1":"hello"}`, any.ToString())
// cannot pass!
//stream := NewStream(ConfigDefault, nil, 32)
//any.WriteTo(stream)
//should.Equal(`{"Field1":"hello"}`, string(stream.Buffer()))
// cannot pass!
}
func Test_any_within_struct(t *testing.T) {
should := require.New(t)
type TestObject struct {
Field1 jsoniter.Any
Field2 jsoniter.Any
}
obj := TestObject{}
err := jsoniter.UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj)
should.Nil(err)
should.Equal("hello", obj.Field1.ToString())
should.Equal("[1,2,3]", obj.Field2.ToString())
}
func Test_object_wrapper_any_get_all(t *testing.T) {
should := require.New(t)
type TestObject struct {
Field1 []int
Field2 []int
}
any := jsoniter.Wrap(TestObject{[]int{1, 2}, []int{3, 4}})
should.Contains(any.Get('*', 0).ToString(), `"Field2":3`)
should.Contains(any.Keys(), "Field1")
should.Contains(any.Keys(), "Field2")
should.NotContains(any.Keys(), "Field3")
}
================================================
FILE: any_tests/jsoniter_any_string_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
var stringConvertMap = map[string]string{
"null": "",
"321.1": "321.1",
`"1.1"`: "1.1",
`"-123.1"`: "-123.1",
"0.0": "0.0",
"0": "0",
`"0"`: "0",
`"0.0"`: "0.0",
`"00.0"`: "00.0",
"true": "true",
"false": "false",
`"true"`: "true",
`"false"`: "false",
`"true123"`: "true123",
`"+1"`: "+1",
"[]": "[]",
"[1,2]": "[1,2]",
"{}": "{}",
`{"a":1, "stream":true}`: `{"a":1, "stream":true}`,
}
func Test_read_any_to_string(t *testing.T) {
should := require.New(t)
for k, v := range stringConvertMap {
any := jsoniter.Get([]byte(k))
should.Equal(v, any.ToString(), "original val "+k)
}
}
func Test_read_string_as_any(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte(`"hello"`))
should.Equal("hello", any.ToString())
should.True(any.ToBool())
any = jsoniter.Get([]byte(`" "`))
should.False(any.ToBool())
any = jsoniter.Get([]byte(`"false"`))
should.True(any.ToBool())
any = jsoniter.Get([]byte(`"123"`))
should.Equal(123, any.ToInt())
}
func Test_wrap_string(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("-32000")).MustBeValid()
should.Equal(-32000, any.ToInt())
should.NoError(any.LastError())
}
================================================
FILE: any_tests/jsoniter_must_be_valid_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
// if must be valid is useless, just drop this test
func Test_must_be_valid(t *testing.T) {
should := require.New(t)
any := jsoniter.Get([]byte("123"))
should.Equal(any.MustBeValid().ToInt(), 123)
any = jsoniter.Wrap(int8(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(int16(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(int32(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(int64(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(uint(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(uint8(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(uint16(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(uint32(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(uint64(10))
should.Equal(any.MustBeValid().ToInt(), 10)
any = jsoniter.Wrap(float32(10))
should.Equal(any.MustBeValid().ToFloat64(), float64(10))
any = jsoniter.Wrap(float64(10))
should.Equal(any.MustBeValid().ToFloat64(), float64(10))
any = jsoniter.Wrap(true)
should.Equal(any.MustBeValid().ToFloat64(), float64(1))
any = jsoniter.Wrap(false)
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap(nil)
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap(struct{ age int }{age: 1})
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap(map[string]interface{}{"abc": 1})
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap("abc")
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap([]int{})
should.Equal(any.MustBeValid().ToFloat64(), float64(0))
any = jsoniter.Wrap([]int{1, 2})
should.Equal(any.MustBeValid().ToFloat64(), float64(1))
}
================================================
FILE: any_tests/jsoniter_wrap_test.go
================================================
package any_tests
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func Test_wrap_and_valuetype_everything(t *testing.T) {
should := require.New(t)
var i interface{}
any := jsoniter.Get([]byte("123"))
// default of number type is float64
i = float64(123)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(int8(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
// get interface is not int8 interface
// i = int8(10)
// should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(int16(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
//i = int16(10)
//should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(int32(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
i = int32(10)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(int64(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
i = int64(10)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(uint(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
// not equal
//i = uint(10)
//should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(uint8(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
// not equal
// i = uint8(10)
// should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(uint16(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
any = jsoniter.Wrap(uint32(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
i = uint32(10)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(uint64(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
i = uint64(10)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(float32(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
// not equal
//i = float32(10)
//should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(float64(10))
should.Equal(any.ValueType(), jsoniter.NumberValue)
should.Equal(any.LastError(), nil)
i = float64(10)
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(true)
should.Equal(any.ValueType(), jsoniter.BoolValue)
should.Equal(any.LastError(), nil)
i = true
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(false)
should.Equal(any.ValueType(), jsoniter.BoolValue)
should.Equal(any.LastError(), nil)
i = false
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(nil)
should.Equal(any.ValueType(), jsoniter.NilValue)
should.Equal(any.LastError(), nil)
i = nil
should.Equal(i, any.GetInterface())
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("null", string(stream.Buffer()))
should.Equal(any.LastError(), nil)
any = jsoniter.Wrap(struct{ age int }{age: 1})
should.Equal(any.ValueType(), jsoniter.ObjectValue)
should.Equal(any.LastError(), nil)
i = struct{ age int }{age: 1}
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap(map[string]interface{}{"abc": 1})
should.Equal(any.ValueType(), jsoniter.ObjectValue)
should.Equal(any.LastError(), nil)
i = map[string]interface{}{"abc": 1}
should.Equal(i, any.GetInterface())
any = jsoniter.Wrap("abc")
i = "abc"
should.Equal(i, any.GetInterface())
should.Equal(nil, any.LastError())
}
================================================
FILE: any_uint32.go
================================================
package jsoniter
import (
"strconv"
)
type uint32Any struct {
baseAny
val uint32
}
func (any *uint32Any) LastError() error {
return nil
}
func (any *uint32Any) ValueType() ValueType {
return NumberValue
}
func (any *uint32Any) MustBeValid() Any {
return any
}
func (any *uint32Any) ToBool() bool {
return any.val != 0
}
func (any *uint32Any) ToInt() int {
return int(any.val)
}
func (any *uint32Any) ToInt32() int32 {
return int32(any.val)
}
func (any *uint32Any) ToInt64() int64 {
return int64(any.val)
}
func (any *uint32Any) ToUint() uint {
return uint(any.val)
}
func (any *uint32Any) ToUint32() uint32 {
return any.val
}
func (any *uint32Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *uint32Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *uint32Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *uint32Any) ToString() string {
return strconv.FormatInt(int64(any.val), 10)
}
func (any *uint32Any) WriteTo(stream *Stream) {
stream.WriteUint32(any.val)
}
func (any *uint32Any) Parse() *Iterator {
return nil
}
func (any *uint32Any) GetInterface() interface{} {
return any.val
}
================================================
FILE: any_uint64.go
================================================
package jsoniter
import (
"strconv"
)
type uint64Any struct {
baseAny
val uint64
}
func (any *uint64Any) LastError() error {
return nil
}
func (any *uint64Any) ValueType() ValueType {
return NumberValue
}
func (any *uint64Any) MustBeValid() Any {
return any
}
func (any *uint64Any) ToBool() bool {
return any.val != 0
}
func (any *uint64Any) ToInt() int {
return int(any.val)
}
func (any *uint64Any) ToInt32() int32 {
return int32(any.val)
}
func (any *uint64Any) ToInt64() int64 {
return int64(any.val)
}
func (any *uint64Any) ToUint() uint {
return uint(any.val)
}
func (any *uint64Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *uint64Any) ToUint64() uint64 {
return any.val
}
func (any *uint64Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *uint64Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *uint64Any) ToString() string {
return strconv.FormatUint(any.val, 10)
}
func (any *uint64Any) WriteTo(stream *Stream) {
stream.WriteUint64(any.val)
}
func (any *uint64Any) Parse() *Iterator {
return nil
}
func (any *uint64Any) GetInterface() interface{} {
return any.val
}
================================================
FILE: api_tests/config_test.go
================================================
package test
import (
"encoding/json"
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func Test_use_number_for_unmarshal(t *testing.T) {
should := require.New(t)
api := jsoniter.Config{UseNumber: true}.Froze()
var obj interface{}
should.Nil(api.UnmarshalFromString("123", &obj))
should.Equal(json.Number("123"), obj)
}
func Test_customize_float_marshal(t *testing.T) {
should := require.New(t)
json := jsoniter.Config{MarshalFloatWith6Digits: true}.Froze()
str, err := json.MarshalToString(float32(1.23456789))
should.Nil(err)
should.Equal("1.234568", str)
}
func Test_customize_tag_key(t *testing.T) {
type TestObject struct {
Field string `orm:"field"`
}
should := require.New(t)
json := jsoniter.Config{TagKey: "orm"}.Froze()
str, err := json.MarshalToString(TestObject{"hello"})
should.Nil(err)
should.Equal(`{"field":"hello"}`, str)
}
func Test_read_large_number_as_interface(t *testing.T) {
should := require.New(t)
var val interface{}
err := jsoniter.Config{UseNumber: true}.Froze().UnmarshalFromString(`123456789123456789123456789`, &val)
should.Nil(err)
output, err := jsoniter.MarshalToString(val)
should.Nil(err)
should.Equal(`123456789123456789123456789`, output)
}
type caseSensitiveStruct struct {
A string `json:"a"`
B string `json:"b,omitempty"`
C *C `json:"C,omitempty"`
}
type C struct {
D int64 `json:"D,omitempty"`
E *E `json:"e,omitempty"`
}
type E struct {
F string `json:"F,omitempty"`
}
func Test_CaseSensitive(t *testing.T) {
should := require.New(t)
testCases := []struct {
input string
expectedOutput string
caseSensitive bool
}{
{
input: `{"A":"foo","B":"bar"}`,
expectedOutput: `{"a":"foo","b":"bar"}`,
caseSensitive: false,
},
{
input: `{"a":"foo","b":"bar"}`,
expectedOutput: `{"a":"foo","b":"bar"}`,
caseSensitive: true,
},
{
input: `{"a":"foo","b":"bar","C":{"D":10}}`,
expectedOutput: `{"a":"foo","b":"bar","C":{"D":10}}`,
caseSensitive: true,
},
{
input: `{"a":"foo","B":"bar","c":{"d":10}}`,
expectedOutput: `{"a":"foo"}`,
caseSensitive: true,
},
{
input: `{"a":"foo","C":{"d":10}}`,
expectedOutput: `{"a":"foo","C":{}}`,
caseSensitive: true,
},
{
input: `{"a":"foo","C":{"D":10,"e":{"f":"baz"}}}`,
expectedOutput: `{"a":"foo","C":{"D":10,"e":{}}}`,
caseSensitive: true,
},
{
input: `{"a":"foo","C":{"D":10,"e":{"F":"baz"}}}`,
expectedOutput: `{"a":"foo","C":{"D":10,"e":{"F":"baz"}}}`,
caseSensitive: true,
},
{
input: `{"A":"foo","c":{"d":10,"E":{"f":"baz"}}}`,
expectedOutput: `{"a":"foo","C":{"D":10,"e":{"F":"baz"}}}`,
caseSensitive: false,
},
}
for _, tc := range testCases {
val := caseSensitiveStruct{}
err := jsoniter.Config{CaseSensitive: tc.caseSensitive}.Froze().UnmarshalFromString(tc.input, &val)
should.Nil(err)
output, err := jsoniter.MarshalToString(val)
should.Nil(err)
should.Equal(tc.expectedOutput, output)
}
}
type structWithElevenFields struct {
A string `json:"A,omitempty"`
B string `json:"B,omitempty"`
C string `json:"C,omitempty"`
D string `json:"d,omitempty"`
E string `json:"e,omitempty"`
F string `json:"f,omitempty"`
G string `json:"g,omitempty"`
H string `json:"h,omitempty"`
I string `json:"i,omitempty"`
J string `json:"j,omitempty"`
K string `json:"k,omitempty"`
}
func Test_CaseSensitive_MoreThanTenFields(t *testing.T) {
should := require.New(t)
testCases := []struct {
input string
expectedOutput string
caseSensitive bool
}{
{
input: `{"A":"1","B":"2","C":"3","d":"4","e":"5","f":"6","g":"7","h":"8","i":"9","j":"10","k":"11"}`,
expectedOutput: `{"A":"1","B":"2","C":"3","d":"4","e":"5","f":"6","g":"7","h":"8","i":"9","j":"10","k":"11"}`,
caseSensitive: true,
},
{
input: `{"a":"1","b":"2","c":"3","D":"4","E":"5","F":"6"}`,
expectedOutput: `{"A":"1","B":"2","C":"3","d":"4","e":"5","f":"6"}`,
caseSensitive: false,
},
{
input: `{"A":"1","b":"2","d":"4","E":"5"}`,
expectedOutput: `{"A":"1","d":"4"}`,
caseSensitive: true,
},
}
for _, tc := range testCases {
val := structWithElevenFields{}
err := jsoniter.Config{CaseSensitive: tc.caseSensitive}.Froze().UnmarshalFromString(tc.input, &val)
should.Nil(err)
output, err := jsoniter.MarshalToString(val)
should.Nil(err)
should.Equal(tc.expectedOutput, output)
}
}
type onlyTaggedFieldStruct struct {
A string `json:"a"`
B string
FSimpl F `json:"f_simpl"`
ISimpl I
FPtr *F `json:"f_ptr"`
IPtr *I
F
*I
}
type F struct {
G string `json:"g"`
H string
}
type I struct {
J string `json:"j"`
K string
}
func Test_OnlyTaggedField(t *testing.T) {
should := require.New(t)
obj := onlyTaggedFieldStruct{
A: "a",
B: "b",
FSimpl: F{G: "g", H: "h"},
ISimpl: I{J: "j", K: "k"},
FPtr: &F{G: "g", H: "h"},
IPtr: &I{J: "j", K: "k"},
F: F{G: "g", H: "h"},
I: &I{J: "j", K: "k"},
}
output, err := jsoniter.Config{OnlyTaggedField: true}.Froze().Marshal(obj)
should.Nil(err)
m := make(map[string]interface{})
err = jsoniter.Unmarshal(output, &m)
should.Nil(err)
should.Equal(map[string]interface{}{
"a": "a",
"f_simpl": map[string]interface{}{
"g": "g",
},
"f_ptr": map[string]interface{}{
"g": "g",
},
"g": "g",
"j": "j",
}, m)
}
================================================
FILE: api_tests/decoder_test.go
================================================
package test
import (
"bytes"
"encoding/json"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"io/ioutil"
"testing"
)
func Test_disallowUnknownFields(t *testing.T) {
should := require.New(t)
type TestObject struct{}
var obj TestObject
decoder := jsoniter.NewDecoder(bytes.NewBufferString(`{"field1":100}`))
decoder.DisallowUnknownFields()
should.Error(decoder.Decode(&obj))
}
func Test_new_decoder(t *testing.T) {
should := require.New(t)
decoder1 := json.NewDecoder(bytes.NewBufferString(`[1][2]`))
decoder2 := jsoniter.NewDecoder(bytes.NewBufferString(`[1][2]`))
arr1 := []int{}
should.Nil(decoder1.Decode(&arr1))
should.Equal([]int{1}, arr1)
arr2 := []int{}
should.True(decoder1.More())
buffered, _ := ioutil.ReadAll(decoder1.Buffered())
should.Equal("[2]", string(buffered))
should.Nil(decoder2.Decode(&arr2))
should.Equal([]int{1}, arr2)
should.True(decoder2.More())
buffered, _ = ioutil.ReadAll(decoder2.Buffered())
should.Equal("[2]", string(buffered))
should.Nil(decoder1.Decode(&arr1))
should.Equal([]int{2}, arr1)
should.False(decoder1.More())
should.Nil(decoder2.Decode(&arr2))
should.Equal([]int{2}, arr2)
should.False(decoder2.More())
}
func Test_use_number(t *testing.T) {
should := require.New(t)
decoder1 := json.NewDecoder(bytes.NewBufferString(`123`))
decoder1.UseNumber()
decoder2 := jsoniter.NewDecoder(bytes.NewBufferString(`123`))
decoder2.UseNumber()
var obj1 interface{}
should.Nil(decoder1.Decode(&obj1))
should.Equal(json.Number("123"), obj1)
var obj2 interface{}
should.Nil(decoder2.Decode(&obj2))
should.Equal(json.Number("123"), obj2)
}
func Test_decoder_more(t *testing.T) {
should := require.New(t)
decoder := jsoniter.NewDecoder(bytes.NewBufferString("abcde"))
should.True(decoder.More())
}
================================================
FILE: api_tests/encoder_18_test.go
================================================
//+build go1.8
package test
import (
"bytes"
"encoding/json"
"testing"
"unicode/utf8"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func Test_new_encoder(t *testing.T) {
should := require.New(t)
buf1 := &bytes.Buffer{}
encoder1 := json.NewEncoder(buf1)
encoder1.SetEscapeHTML(false)
encoder1.Encode([]int{1})
should.Equal("[1]\n", buf1.String())
buf2 := &bytes.Buffer{}
encoder2 := jsoniter.NewEncoder(buf2)
encoder2.SetEscapeHTML(false)
encoder2.Encode([]int{1})
should.Equal("[1]\n", buf2.String())
}
func Test_string_encode_with_std_without_html_escape(t *testing.T) {
api := jsoniter.Config{EscapeHTML: false}.Froze()
should := require.New(t)
for i := 0; i < utf8.RuneSelf; i++ {
input := string([]byte{byte(i)})
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
encoder.SetEscapeHTML(false)
err := encoder.Encode(input)
should.Nil(err)
stdOutput := buf.String()
stdOutput = stdOutput[:len(stdOutput)-1]
jsoniterOutputBytes, err := api.Marshal(input)
should.Nil(err)
jsoniterOutput := string(jsoniterOutputBytes)
should.Equal(stdOutput, jsoniterOutput)
}
}
================================================
FILE: api_tests/encoder_test.go
================================================
package test
import (
"bytes"
"encoding/json"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
// Standard Encoder has trailing newline.
func TestEncoderHasTrailingNewline(t *testing.T) {
should := require.New(t)
var buf, stdbuf bytes.Buffer
enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf)
enc.Encode(1)
stdenc := json.NewEncoder(&stdbuf)
stdenc.Encode(1)
should.Equal(stdbuf.Bytes(), buf.Bytes())
}
================================================
FILE: api_tests/marshal_indent_test.go
================================================
package test
import (
"encoding/json"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func Test_marshal_indent(t *testing.T) {
should := require.New(t)
obj := struct {
F1 int
F2 []int
}{1, []int{2, 3, 4}}
output, err := json.MarshalIndent(obj, "", " ")
should.Nil(err)
should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output))
output, err = jsoniter.MarshalIndent(obj, "", " ")
should.Nil(err)
should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output))
}
func Test_marshal_indent_map(t *testing.T) {
should := require.New(t)
obj := map[int]int{1: 2}
output, err := json.MarshalIndent(obj, "", " ")
should.Nil(err)
should.Equal("{\n \"1\": 2\n}", string(output))
output, err = jsoniter.MarshalIndent(obj, "", " ")
should.Nil(err)
should.Equal("{\n \"1\": 2\n}", string(output))
output, err = jsoniter.ConfigCompatibleWithStandardLibrary.MarshalIndent(obj, "", " ")
should.Nil(err)
should.Equal("{\n \"1\": 2\n}", string(output))
}
================================================
FILE: api_tests/marshal_json_escape_test.go
================================================
package test
import (
"bytes"
"encoding/json"
"testing"
jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
var marshalConfig = jsoniter.Config{
EscapeHTML: false,
SortMapKeys: true,
ValidateJsonRawMessage: true,
}.Froze()
type Container struct {
Bar interface{}
}
func (c *Container) MarshalJSON() ([]byte, error) {
return marshalConfig.Marshal(&c.Bar)
}
func TestEncodeEscape(t *testing.T) {
should := require.New(t)
container := &Container{
Bar: []string{"123<ab>", "ooo"},
}
out, err := marshalConfig.Marshal(container)
should.Nil(err)
bufout := string(out)
var stdbuf bytes.Buffer
stdenc := json.NewEncoder(&stdbuf)
stdenc.SetEscapeHTML(false)
err = stdenc.Encode(container)
should.Nil(err)
stdout := string(stdbuf.Bytes())
if stdout[len(stdout)-1:] == "\n" {
stdout = stdout[:len(stdout)-1]
}
should.Equal(stdout, bufout)
}
================================================
FILE: api_tests/marshal_json_test.go
================================================
package test
import (
"bytes"
"encoding/json"
"github.com/json-iterator/go"
"testing"
"github.com/stretchr/testify/require"
)
type Foo struct {
Bar interface{}
}
func (f Foo) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(f.Bar)
return buf.Bytes(), err
}
// Standard Encoder has trailing newline.
func TestEncodeMarshalJSON(t *testing.T) {
foo := Foo {
Bar: 123,
}
should := require.New(t)
var buf, stdbuf bytes.Buffer
enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf)
enc.Encode(foo)
stdenc := json.NewEncoder(&stdbuf)
stdenc.Encode(foo)
should.Equal(stdbuf.Bytes(), buf.Bytes())
}
================================================
FILE: benchmarks/encode_string_test.go
================================================
package test
import (
"bytes"
"github.com/json-iterator/go"
"testing"
)
func Benchmark_encode_string_with_SetEscapeHTML(b *testing.B) {
type V struct {
S string
B bool
I int
}
var json = jsoniter.ConfigCompatibleWithStandardLibrary
b.ReportAllocs()
for i := 0; i < b.N; i++ {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
if err := enc.Encode(V{S: "s", B: true, I: 233}); err != nil {
b.Fatal(err)
}
}
}
================================================
FILE: benchmarks/jsoniter_large_file_test.go
================================================
package test
import (
"encoding/json"
"github.com/json-iterator/go"
"io/ioutil"
"os"
"testing"
)
//func Test_large_file(t *testing.T) {
// file, err := os.Open("/tmp/large-file.json")
// if err != nil {
// t.Fatal(err)
// }
// iter := Parse(file, 4096)
// count := 0
// for iter.ReadArray() {
// iter.Skip()
// count++
// }
// if count != 11351 {
// t.Fatal(count)
// }
//}
func init() {
ioutil.WriteFile("/tmp/large-file.json", []byte(`[{
"person": {
"id": "d50887ca-a6ce-4e59-b89f-14f0b5d03b03",
"name": {
"fullName": "Leonid Bugaev",
"givenName": "Leonid",
"familyName": "Bugaev"
},
"email": "leonsbox@gmail.com",
"gender": "male",
"location": "Saint Petersburg, Saint Petersburg, RU",
"geo": {
"city": "Saint Petersburg",
"state": "Saint Petersburg",
"country": "Russia",
"lat": 59.9342802,
"lng": 30.3350986
},
"bio": "Senior engineer at Granify.com",
"site": "http://flickfaver.com",
"avatar": "https://d1ts43dypk8bqh.cloudfront.net/v1/avatars/d50887ca-a6ce-4e59-b89f-14f0b5d03b03",
"employment": {
"name": "www.latera.ru",
"title": "Software Engineer",
"domain": "gmail.com"
},
"facebook": {
"handle": "leonid.bugaev"
},
"github": {
"handle": "buger",
"id": 14009,
"avatar": "https://avatars.githubusercontent.com/u/14009?v=3",
"company": "Granify",
"blog": "http://leonsbox.com",
"followers": 95,
"following": 10
},
"twitter": {
"handle": "flickfaver",
"id": 77004410,
"bio": null,
"followers": 2,
"following": 1,
"statuses": 5,
"favorites": 0,
"location": "",
"site": "http://flickfaver.com",
"avatar": null
},
"linkedin": {
"handle": "in/leonidbugaev"
},
"googleplus": {
"handle": null
},
"angellist": {
"handle": "leonid-bugaev",
"id": 61541,
"bio": "Senior engineer at Granify.com",
"blog": "http://buger.github.com",
"site": "http://buger.github.com",
"followers": 41,
"avatar": "https://d1qb2nb5cznatu.cloudfront.net/users/61541-medium_jpg?1405474390"
},
"klout": {
"handle": null,
"score": null
},
"foursquare": {
"handle": null
},
"aboutme": {
"handle": "leonid.bugaev",
"bio": null,
"avatar": null
},
"gravatar": {
"handle": "buger",
"urls": [
],
"avatar": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510",
"avatars": [
{
"url": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510",
"type": "thumbnail"
}
]
},
"fuzzy": false
},
"company": "hello"
}]`), 0666)
}
/*
200000 8886 ns/op 4336 B/op 6 allocs/op
50000 34244 ns/op 6744 B/op 14 allocs/op
*/
func Benchmark_jsoniter_large_file(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
file, _ := os.Open("/tmp/large-file.json")
iter := jsoniter.Parse(jsoniter.ConfigDefault, file, 4096)
count := 0
iter.ReadArrayCB(func(iter *jsoniter.Iterator) bool {
// Skip() is strict by default, use --tags jsoniter-sloppy to skip without validation
iter.Skip()
count++
return true
})
file.Close()
if iter.Error != nil {
b.Error(iter.Error)
}
}
}
func Benchmark_json_large_file(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
file, _ := os.Open("/tmp/large-file.json")
bytes, _ := ioutil.ReadAll(file)
file.Close()
result := []struct{}{}
err := json.Unmarshal(bytes, &result)
if err != nil {
b.Error(err)
}
}
}
================================================
FILE: benchmarks/stream_test.go
================================================
package test
import (
"bytes"
"strconv"
"testing"
jsoniter "github.com/json-iterator/go"
)
func Benchmark_stream_encode_big_object(b *testing.B) {
var buf bytes.Buffer
var stream = jsoniter.NewStream(jsoniter.ConfigDefault, &buf, 100)
for i := 0; i < b.N; i++ {
buf.Reset()
stream.Reset(&buf)
encodeObject(stream)
if stream.Error != nil {
b.Errorf("error: %+v", stream.Error)
}
}
}
func TestEncodeObject(t *testing.T) {
var stream = jsoniter.NewStream(jsoniter.ConfigDefault, nil, 100)
encodeObject(stream)
if stream.Error != nil {
t.Errorf("error encoding a test object: %+v", stream.Error)
return
}
var m = make(map[string]interface{})
if err := jsoniter.Unmarshal(stream.Buffer(), &m); err != nil {
t.Errorf("error unmarshaling a test object: %+v", err)
return
}
}
func encodeObject(stream *jsoniter.Stream) {
stream.WriteObjectStart()
stream.WriteObjectField("objectId")
stream.WriteUint64(8838243212)
stream.WriteMore()
stream.WriteObjectField("name")
stream.WriteString("Jane Doe")
stream.WriteMore()
stream.WriteObjectField("address")
stream.WriteObjectStart()
for i, field := range addressFields {
if i != 0 {
stream.WriteMore()
}
stream.WriteObjectField(field.key)
stream.WriteString(field.val)
}
stream.WriteMore()
stream.WriteObjectField("geo")
{
stream.WriteObjectStart()
stream.WriteObjectField("latitude")
stream.WriteFloat64(-154.550817)
stream.WriteMore()
stream.WriteObjectField("longitude")
stream.WriteFloat64(-84.176159)
stream.WriteObjectEnd()
}
stream.WriteObjectEnd()
stream.WriteMore()
stream.WriteObjectField("specialties")
stream.WriteArrayStart()
for i, s := range specialties {
if i != 0 {
stream.WriteMore()
}
stream.WriteString(s)
}
stream.WriteArrayEnd()
stream.WriteMore()
for i, text := range longText {
if i != 0 {
stream.WriteMore()
}
stream.WriteObjectField("longText" + strconv.Itoa(i))
stream.WriteString(text)
}
for i := 0; i < 25; i++ {
num := i * 18328
stream.WriteMore()
stream.WriteObjectField("integerField" + strconv.Itoa(i))
stream.WriteInt64(int64(num))
}
stream.WriteObjectEnd()
}
type field struct{ key, val string }
var (
addressFields = []field{
{"address1", "123 Example St"},
{"address2", "Apartment 5D, Suite 3"},
{"city", "Miami"},
{"state", "FL"},
{"postalCode", "33133"},
{"country", "US"},
}
specialties = []string{
"Web Design",
"Go Programming",
"Tennis",
"Cycling",
"Mixed martial arts",
}
longText = []string{
`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`,
`Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?`,
`But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?`,
`At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.`,
`On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.`,
}
)
================================================
FILE: build.sh
================================================
#!/bin/bash
set -e
set -x
if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then
mkdir -p /tmp/build-golang/src/github.com/json-iterator
ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go
fi
export GOPATH=/tmp/build-golang
go get -u github.com/golang/dep/cmd/dep
cd /tmp/build-golang/src/github.com/json-iterator/go
exec $GOPATH/bin/dep ensure -update
================================================
FILE: config.go
================================================
package jsoniter
import (
"encoding/json"
"io"
"reflect"
"sync"
"unsafe"
"github.com/modern-go/concurrent"
"github.com/modern-go/reflect2"
)
// Config customize how the API should behave.
// The API is created from Config by Froze.
type Config struct {
IndentionStep int
MarshalFloatWith6Digits bool
EscapeHTML bool
SortMapKeys bool
UseNumber bool
DisallowUnknownFields bool
TagKey string
OnlyTaggedField bool
ValidateJsonRawMessage bool
ObjectFieldMustBeSimpleString bool
CaseSensitive bool
}
// API the public interface of this package.
// Primary Marshal and Unmarshal.
type API interface {
IteratorPool
StreamPool
MarshalToString(v interface{}) (string, error)
Marshal(v interface{}) ([]byte, error)
MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
UnmarshalFromString(str string, v interface{}) error
Unmarshal(data []byte, v interface{}) error
Get(data []byte, path ...interface{}) Any
NewEncoder(writer io.Writer) *Encoder
NewDecoder(reader io.Reader) *Decoder
Valid(data []byte) bool
RegisterExtension(extension Extension)
DecoderOf(typ reflect2.Type) ValDecoder
EncoderOf(typ reflect2.Type) ValEncoder
}
// ConfigDefault the default API
var ConfigDefault = Config{
EscapeHTML: true,
}.Froze()
// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
var ConfigCompatibleWithStandardLibrary = Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
}.Froze()
// ConfigFastest marshals float with only 6 digits precision
var ConfigFastest = Config{
EscapeHTML: false,
MarshalFloatWith6Digits: true, // will lose precession
ObjectFieldMustBeSimpleString: true, // do not unescape object field
}.Froze()
type frozenConfig struct {
configBeforeFrozen Config
sortMapKeys bool
indentionStep int
objectFieldMustBeSimpleString bool
onlyTaggedField bool
disallowUnknownFields bool
decoderCache *concurrent.Map
encoderCache *concurrent.Map
encoderExtension Extension
decoderExtension Extension
extraExtensions []Extension
streamPool *sync.Pool
iteratorPool *sync.Pool
caseSensitive bool
}
func (cfg *frozenConfig) initCache() {
cfg.decoderCache = concurrent.NewMap()
cfg.encoderCache = concurrent.NewMap()
}
func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) {
cfg.decoderCache.Store(cacheKey, decoder)
}
func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) {
cfg.encoderCache.Store(cacheKey, encoder)
}
func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder {
decoder, found := cfg.decoderCache.Load(cacheKey)
if found {
return decoder.(ValDecoder)
}
return nil
}
func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder {
encoder, found := cfg.encoderCache.Load(cacheKey)
if found {
return encoder.(ValEncoder)
}
return nil
}
var cfgCache = concurrent.NewMap()
func getFrozenConfigFromCache(cfg Config) *frozenConfig {
obj, found := cfgCache.Load(cfg)
if found {
return obj.(*frozenConfig)
}
return nil
}
func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) {
cfgCache.Store(cfg, frozenConfig)
}
// Froze forge API from config
func (cfg Config) Froze() API {
api := &frozenConfig{
sortMapKeys: cfg.SortMapKeys,
indentionStep: cfg.IndentionStep,
objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
onlyTaggedField: cfg.OnlyTaggedField,
disallowUnknownFields: cfg.DisallowUnknownFields,
caseSensitive: cfg.CaseSensitive,
}
api.streamPool = &sync.Pool{
New: func() interface{} {
return NewStream(api, nil, 512)
},
}
api.iteratorPool = &sync.Pool{
New: func() interface{} {
return NewIterator(api)
},
}
api.initCache()
encoderExtension := EncoderExtension{}
decoderExtension := DecoderExtension{}
if cfg.MarshalFloatWith6Digits {
api.marshalFloatWith6Digits(encoderExtension)
}
if cfg.EscapeHTML {
api.escapeHTML(encoderExtension)
}
if cfg.UseNumber {
api.useNumber(decoderExtension)
}
if cfg.ValidateJsonRawMessage {
api.validateJsonRawMessage(encoderExtension)
}
api.encoderExtension = encoderExtension
api.decoderExtension = decoderExtension
api.configBeforeFrozen = cfg
return api
}
func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig {
api := getFrozenConfigFromCache(cfg)
if api != nil {
return api
}
api = cfg.Froze().(*frozenConfig)
for _, extension := range extraExtensions {
api.RegisterExtension(extension)
}
addFrozenConfigToCache(cfg, api)
return api
}
func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) {
encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
rawMessage := *(*json.RawMessage)(ptr)
iter := cfg.BorrowIterator([]byte(rawMessage))
defer cfg.ReturnIterator(iter)
iter.Read()
if iter.Error != nil && iter.Error != io.EOF {
stream.WriteRaw("null")
} else {
stream.WriteRaw(string(rawMessage))
}
}, func(ptr unsafe.Pointer) bool {
return len(*((*json.RawMessage)(ptr))) == 0
}}
extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder
extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder
}
func (cfg *frozenConfig) useNumber(extension DecoderExtension) {
extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
exitingValue := *((*interface{})(ptr))
if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr {
iter.ReadVal(exitingValue)
return
}
if iter.WhatIsNext() == NumberValue {
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
} else {
*((*interface{})(ptr)) = iter.Read()
}
}}
}
func (cfg *frozenConfig) getTagKey() string {
tagKey := cfg.configBeforeFrozen.TagKey
if tagKey == "" {
return "json"
}
return tagKey
}
func (cfg *frozenConfig) RegisterExtension(extension Extension) {
cfg.extraExtensions = append(cfg.extraExtensions, extension)
copied := cfg.configBeforeFrozen
cfg.configBeforeFrozen = copied
}
type lossyFloat32Encoder struct {
}
func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
stream.WriteFloat32Lossy(*((*float32)(ptr)))
}
func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*float32)(ptr)) == 0
}
type lossyFloat64Encoder struct {
}
func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
stream.WriteFloat64Lossy(*((*float64)(ptr)))
}
func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*float64)(ptr)) == 0
}
// EnableLossyFloatMarshalling keeps 10**(-6) precision
// for float variables for better performance.
func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) {
// for better performance
extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{}
extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{}
}
type htmlEscapedStringEncoder struct {
}
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
str := *((*string)(ptr))
stream.WriteStringWithHTMLEscaped(str)
}
func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*string)(ptr)) == ""
}
func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) {
encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{}
}
func (cfg *frozenConfig) cleanDecoders() {
typeDecoders = map[string]ValDecoder{}
fieldDecoders = map[string]ValDecoder{}
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
}
func (cfg *frozenConfig) cleanEncoders() {
typeEncoders = map[string]ValEncoder{}
fieldEncoders = map[string]ValEncoder{}
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
}
func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
stream.WriteVal(v)
if stream.Error != nil {
return "", stream.Error
}
return string(stream.Buffer()), nil
}
func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
stream.WriteVal(v)
if stream.Error != nil {
return nil, stream.Error
}
result := stream.Buffer()
copied := make([]byte, len(result))
copy(copied, result)
return copied, nil
}
func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
if prefix != "" {
panic("prefix is not supported")
}
for _, r := range indent {
if r != ' ' {
panic("indent can only be space")
}
}
newCfg := cfg.configBeforeFrozen
newCfg.IndentionStep = len(indent)
return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v)
}
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
data := []byte(str)
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}
func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
return locatePath(iter, path)
}
func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}
func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
stream := NewStream(cfg, writer, 512)
return &Encoder{stream}
}
func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
iter := Parse(cfg, reader, 512)
return &Decoder{iter}
}
func (cfg *frozenConfig) Valid(data []byte) bool {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.Skip()
return iter.Error == nil
}
================================================
FILE: example_test.go
================================================
package jsoniter
import (
"fmt"
"os"
"strings"
)
func ExampleMarshal() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
// Output:
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
}
func ExampleUnmarshal() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
// Output:
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
}
func ExampleConfigFastest_Marshal() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
stream := ConfigFastest.BorrowStream(nil)
defer ConfigFastest.ReturnStream(stream)
stream.WriteVal(group)
if stream.Error != nil {
fmt.Println("error:", stream.Error)
}
os.Stdout.Write(stream.Buffer())
// Output:
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
}
func ExampleConfigFastest_Unmarshal() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
iter := ConfigFastest.BorrowIterator(jsonBlob)
defer ConfigFastest.ReturnIterator(iter)
iter.ReadVal(&animals)
if iter.Error != nil {
fmt.Println("error:", iter.Error)
}
fmt.Printf("%+v", animals)
// Output:
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
}
func ExampleGet() {
val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`)
fmt.Printf(Get(val, "Colors", 0).ToString())
// Output:
// Crimson
}
func ExampleMyKey() {
hello := MyKey("hello")
output, _ := Marshal(map[*MyKey]string{&hello: "world"})
fmt.Println(string(output))
obj := map[*MyKey]string{}
Unmarshal(output, &obj)
for k, v := range obj {
fmt.Println(*k, v)
}
// Output:
// {"Hello":"world"}
// Hel world
}
type MyKey string
func (m *MyKey) MarshalText() ([]byte, error) {
return []byte(strings.Replace(string(*m), "h", "H", -1)), nil
}
func (m *MyKey) UnmarshalText(text []byte) error {
*m = MyKey(text[:3])
return nil
}
================================================
FILE: extension_tests/decoder_test.go
================================================
package test
import (
"bytes"
"fmt"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"strconv"
"testing"
"time"
"unsafe"
)
func Test_customize_type_decoder(t *testing.T) {
t.Skip()
jsoniter.RegisterTypeDecoderFunc("time.Time", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC)
if err != nil {
iter.Error = err
return
}
*((*time.Time)(ptr)) = t
})
//defer jsoniter.ConfigDefault.(*frozenConfig).cleanDecoders()
val := time.Time{}
err := jsoniter.Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
if err != nil {
t.Fatal(err)
}
year, month, day := val.Date()
if year != 2016 || month != 12 || day != 5 {
t.Fatal(val)
}
}
func Test_customize_byte_array_encoder(t *testing.T) {
t.Skip()
//jsoniter.ConfigDefault.(*frozenConfig).cleanEncoders()
should := require.New(t)
jsoniter.RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
t := *((*[]byte)(ptr))
stream.WriteString(string(t))
}, nil)
//defer jsoniter.ConfigDefault.(*frozenConfig).cleanEncoders()
val := []byte("abc")
str, err := jsoniter.MarshalToString(val)
should.Nil(err)
should.Equal(`"abc"`, str)
}
type CustomEncoderAttachmentTestStruct struct {
Value int32 `json:"value"`
}
type CustomEncoderAttachmentTestStructEncoder struct {}
func (c *CustomEncoderAttachmentTestStructEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
attachVal, ok := stream.Attachment.(int)
stream.WriteRaw(`"`)
stream.WriteRaw(fmt.Sprintf("%t %d", ok, attachVal))
stream.WriteRaw(`"`)
}
func (c *CustomEncoderAttachmentTestStructEncoder) IsEmpty(ptr unsafe.Pointer) bool {
return false
}
func Test_custom_encoder_attachment(t *testing.T) {
jsoniter.RegisterTypeEncoder("test.CustomEncoderAttachmentTestStruct", &CustomEncoderAttachmentTestStructEncoder{})
expectedValue := 17
should := require.New(t)
buf := &bytes.Buffer{}
stream := jsoniter.NewStream(jsoniter.Config{SortMapKeys: true}.Froze(), buf, 4096)
stream.Attachment = expectedValue
val := map[string]CustomEncoderAttachmentTestStruct{"a": {}}
stream.WriteVal(val)
stream.Flush()
should.Nil(stream.Error)
should.Equal("{\"a\":\"true 17\"}", buf.String())
}
func Test_customize_field_decoder(t *testing.T) {
type Tom struct {
field1 string
}
jsoniter.RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
})
//defer jsoniter.ConfigDefault.(*frozenConfig).cleanDecoders()
tom := Tom{}
err := jsoniter.Unmarshal([]byte(`{"field1": 100}`), &tom)
if err != nil {
t.Fatal(err)
}
}
func Test_recursive_empty_interface_customization(t *testing.T) {
t.Skip()
var obj interface{}
jsoniter.RegisterTypeDecoderFunc("interface {}", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
switch iter.WhatIsNext() {
case jsoniter.NumberValue:
*(*interface{})(ptr) = iter.ReadInt64()
default:
*(*interface{})(ptr) = iter.Read()
}
})
should := require.New(t)
jsoniter.Unmarshal([]byte("[100]"), &obj)
should.Equal([]interface{}{int64(100)}, obj)
}
type MyInterface interface {
Hello() string
}
type MyString string
func (ms MyString) Hello() string {
return string(ms)
}
func Test_read_custom_interface(t *testing.T) {
t.Skip()
should := require.New(t)
var val MyInterface
jsoniter.RegisterTypeDecoderFunc("jsoniter.MyInterface", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
*((*MyInterface)(ptr)) = MyString(iter.ReadString())
})
err := jsoniter.UnmarshalFromString(`"hello"`, &val)
should.Nil(err)
should.Equal("hello", val.Hello())
}
const flow1 = `
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}`
const flow2 = `
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}
{"A":"hello"}
`
type (
Type1 struct {
A string
}
Type2 struct {
A string
}
)
func (t *Type2) UnmarshalJSON(data []byte) error {
return nil
}
func (t *Type2) MarshalJSON() ([]byte, error) {
return nil, nil
}
func TestType1NoFinalLF(t *testing.T) {
reader := bytes.NewReader([]byte(flow1))
dec := jsoniter.NewDecoder(reader)
i := 0
for dec.More() {
data := &Type1{}
if err := dec.Decode(data); err != nil {
t.Errorf("at %v got %v", i, err)
}
i++
}
}
func TestType1FinalLF(t *testing.T) {
reader := bytes.NewReader([]byte(flow2))
dec := jsoniter.NewDecoder(reader)
i := 0
for dec.More() {
data := &Type1{}
if err := dec.Decode(data); err != nil {
t.Errorf("at %v got %v", i, err)
}
i++
}
}
func TestType2NoFinalLF(t *testing.T) {
reader := bytes.NewReader([]byte(flow1))
dec := jsoniter.NewDecoder(reader)
i := 0
for dec.More() {
data := &Type2{}
if err := dec.Decode(data); err != nil {
t.Errorf("at %v got %v", i, err)
}
i++
}
}
func TestType2FinalLF(t *testing.T) {
reader := bytes.NewReader([]byte(flow2))
dec := jsoniter.NewDecoder(reader)
i := 0
for dec.More() {
data := &Type2{}
if err := dec.Decode(data); err != nil {
t.Errorf("at %v got %v", i, err)
}
i++
}
}
================================================
FILE: extension_tests/extension_test.go
================================================
package test
import (
"github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"github.com/stretchr/testify/require"
"reflect"
"strconv"
"testing"
"unsafe"
)
type TestObject1 struct {
Field1 string
}
type testExtension struct {
jsoniter.DummyExtension
}
func (extension *testExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
if structDescriptor.Type.String() != "test.TestObject1" {
return
}
binding := structDescriptor.GetField("Field1")
binding.Encoder = &funcEncoder{fun: func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
str := *((*string)(ptr))
val, _ := strconv.Atoi(str)
stream.WriteInt(val)
}}
binding.Decoder = &funcDecoder{func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
*((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
}}
binding.ToNames = []string{"field-1"}
binding.FromNames = []string{"field-1"}
}
func Test_customize_field_by_extension(t *testing.T) {
should := require.New(t)
cfg := jsoniter.Config{}.Froze()
cfg.RegisterExtension(&testExtension{})
obj := TestObject1{}
err := cfg.UnmarshalFromString(`{"field-1": 100}`, &obj)
should.Nil(err)
should.Equal("100", obj.Field1)
str, err := cfg.MarshalToString(obj)
should.Nil(err)
should.Equal(`{"field-1":100}`, str)
}
func Test_customize_map_key_encoder(t *testing.T) {
should := require.New(t)
cfg := jsoniter.Config{}.Froze()
cfg.RegisterExtension(&testMapKeyExtension{})
m := map[int]int{1: 2}
output, err := cfg.MarshalToString(m)
should.NoError(err)
should.Equal(`{"2":2}`, output)
m = map[int]int{}
should.NoError(cfg.UnmarshalFromString(output, &m))
should.Equal(map[int]int{1: 2}, m)
}
type testMapKeyExtension struct {
jsoniter.DummyExtension
}
func (extension *testMapKeyExtension) CreateMapKeyEncoder(typ reflect2.Type) jsoniter.ValEncoder {
if typ.Kind() == reflect.Int {
return &funcEncoder{
fun: func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
stream.WriteRaw(`"`)
stream.WriteInt(*(*int)(ptr) + 1)
stream.WriteRaw(`"`)
},
}
}
return nil
}
func (extension *testMapKeyExtension) CreateMapKeyDecoder(typ reflect2.Type) jsoniter.ValDecoder {
if typ.Kind() == reflect.Int {
return &funcDecoder{
fun: func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
i, err := strconv.Atoi(iter.ReadString())
if err != nil {
iter.ReportError("read map key", err.Error())
return
}
i--
*(*int)(ptr) = i
},
}
}
return nil
}
type funcDecoder struct {
fun jsoniter.DecoderFunc
}
func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
decoder.fun(ptr, iter)
}
type funcEncoder struct {
fun jsoniter.EncoderFunc
isEmptyFunc func(ptr unsafe.Pointer) bool
}
func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
encoder.fun(ptr, stream)
}
func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
if encoder.isEmptyFunc == nil {
return false
}
return encoder.isEmptyFunc(ptr)
}
================================================
FILE: extra/binary_as_string_codec.go
================================================
package extra
import (
"github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"unicode/utf8"
"unsafe"
)
// safeSet holds the value true if the ASCII character with the given array
// position can be represented inside a JSON string without any further
// escaping.
//
// All values are true except for the ASCII control characters (0-31), the
// double quote ("), and the backslash character ("\").
var safeSet = [utf8.RuneSelf]bool{
' ': true,
'!': true,
'"': false,
'#': true,
'$': true,
'%': true,
'&': true,
'\'': true,
'(': true,
')': true,
'*': true,
'+': true,
',': true,
'-': true,
'.': true,
'/': true,
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
':': true,
';': true,
'<': true,
'=': true,
'>': true,
'?': true,
'@': true,
'A': true,
'B': true,
'C': true,
'D': true,
'E': true,
'F': true,
'G': true,
'H': true,
'I': true,
'J': true,
'K': true,
'L': true,
'M': true,
'N': true,
'O': true,
'P': true,
'Q': true,
'R': true,
'S': true,
'T': true,
'U': true,
'V': true,
'W': true,
'X': true,
'Y': true,
'Z': true,
'[': true,
'\\': false,
']': true,
'^': true,
'_': true,
'`': true,
'a': true,
'b': true,
'c': true,
'd': true,
'e': true,
'f': true,
'g': true,
'h': true,
'i': true,
'j': true,
'k': true,
'l': true,
'm': true,
'n': true,
'o': true,
'p': true,
'q': true,
'r': true,
's': true,
't': true,
'u': true,
'v': true,
'w': true,
'x': true,
'y': true,
'z': true,
'{': true,
'|': true,
'}': true,
'~': true,
'\u007f': true,
}
var binaryType = reflect2.TypeOfPtr((*[]byte)(nil)).Elem()
type BinaryAsStringExtension struct {
jsoniter.DummyExtension
}
func (extension *BinaryAsStringExtension) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {
if typ == binaryType {
return &binaryAsStringCodec{}
}
return nil
}
func (extension *BinaryAsStringExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
if typ == binaryType {
return &binaryAsStringCodec{}
}
return nil
}
type binaryAsStringCodec struct {
}
func (codec *binaryAsStringCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
rawBytes := iter.ReadStringAsSlice()
bytes := make([]byte, 0, len(rawBytes))
for i := 0; i < len(rawBytes); i++ {
b := rawBytes[i]
if b == '\\' {
b2 := rawBytes[i+1]
if b2 != '\\' {
iter.ReportError("decode binary as string", `\\x is only supported escape`)
return
}
b3 := rawBytes[i+2]
if b3 != 'x' {
iter.ReportError("decode binary as string", `\\x is only supported escape`)
return
}
b4 := rawBytes[i+3]
b5 := rawBytes[i+4]
i += 4
b = readHex(iter, b4, b5)
}
bytes = append(bytes, b)
}
*(*[]byte)(ptr) = bytes
}
func (codec *binaryAsStringCodec) IsEmpty(ptr unsafe.Pointer) bool {
return len(*((*[]byte)(ptr))) == 0
}
func (codec *binaryAsStringCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
newBuffer := writeBytes(stream.Buffer(), *(*[]byte)(ptr))
stream.SetBuffer(newBuffer)
}
func readHex(iter *jsoniter.Iterator, b1, b2 byte) byte {
var ret byte
if b1 >= '0' && b1 <= '9' {
ret = b1 - '0'
} else if b1 >= 'a' && b1 <= 'f' {
ret = b1 - 'a' + 10
} else {
iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b1}))
return 0
}
ret *= 16
if b2 >= '0' && b2 <= '9' {
ret += b2 - '0'
} else if b2 >= 'a' && b2 <= 'f' {
ret += b2 - 'a' + 10
} else {
iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b2}))
return 0
}
return ret
}
var hex = "0123456789abcdef"
func writeBytes(space []byte, s []byte) []byte {
space = append(space, '"')
// write string, the fast path, without utf8 and escape support
var i int
var c byte
for i, c = range s {
if c < utf8.RuneSelf && safeSet[c] {
space = append(space, c)
} else {
break
}
}
if i == len(s)-1 {
space = append(space, '"')
return space
}
return writeBytesSlowPath(space, s[i:])
}
func writeBytesSlowPath(space []byte, s []byte) []byte {
start := 0
// for the remaining parts, we process them char by char
var i int
var b byte
for i, b = range s {
if b >= utf8.RuneSelf {
space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF])
start = i + 1
continue
}
if safeSet[b] {
continue
}
if start < i {
space = append(space, s[start:i]...)
}
space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF])
start = i + 1
}
if start < len(s) {
space = append(space, s[start:]...)
}
return append(space, '"')
}
================================================
FILE: extra/binary_as_string_codec_test.go
================================================
package extra
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func init() {
jsoniter.RegisterExtension(&BinaryAsStringExtension{})
}
func TestBinaryAsStringCodec(t *testing.T) {
t.Run("safe set", func(t *testing.T) {
should := require.New(t)
output, err := jsoniter.Marshal([]byte("hello"))
should.NoError(err)
should.Equal(`"hello"`, string(output))
var val []byte
should.NoError(jsoniter.Unmarshal(output, &val))
should.Equal(`hello`, string(val))
})
t.Run("non safe set", func(t *testing.T) {
should := require.New(t)
output, err := jsoniter.Marshal([]byte{1, 2, 3, 23})
should.NoError(err)
should.Equal(`"\\x01\\x02\\x03\\x17"`, string(output))
var val []byte
should.NoError(jsoniter.Unmarshal(output, &val))
should.Equal([]byte{1, 2, 3, 23}, val)
})
}
================================================
FILE: extra/fuzzy_decoder.go
================================================
package extra
import (
"encoding/json"
"io"
"math"
"reflect"
"strings"
"unsafe"
"github.com/json-iterator/go"
"github.com/modern-go/reflect2"
)
const maxUint = ^uint(0)
const maxInt = int(maxUint >> 1)
const minInt = -maxInt - 1
// RegisterFuzzyDecoders decode input from PHP with tolerance.
// It will handle string/number auto conversation, and treat empty [] as empty struct.
func RegisterFuzzyDecoders() {
jsoniter.RegisterExtension(&tolerateEmptyArrayExtension{})
jsoniter.RegisterTypeDecoder("string", &fuzzyStringDecoder{})
jsoniter.RegisterTypeDecoder("float32", &fuzzyFloat32Decoder{})
jsoniter.RegisterTypeDecoder("float64", &fuzzyFloat64Decoder{})
jsoniter.RegisterTypeDecoder("int", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxInt) || val < float64(minInt) {
iter.ReportError("fuzzy decode int", "exceed range")
return
}
*((*int)(ptr)) = int(val)
} else {
*((*int)(ptr)) = iter.ReadInt()
}
}})
jsoniter.RegisterTypeDecoder("uint", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxUint) || val < 0 {
iter.ReportError("fuzzy decode uint", "exceed range")
return
}
*((*uint)(ptr)) = uint(val)
} else {
*((*uint)(ptr)) = iter.ReadUint()
}
}})
jsoniter.RegisterTypeDecoder("int8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
iter.ReportError("fuzzy decode int8", "exceed range")
return
}
*((*int8)(ptr)) = int8(val)
} else {
*((*int8)(ptr)) = iter.ReadInt8()
}
}})
jsoniter.RegisterTypeDecoder("uint8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint8) || val < 0 {
iter.ReportError("fuzzy decode uint8", "exceed range")
return
}
*((*uint8)(ptr)) = uint8(val)
} else {
*((*uint8)(ptr)) = iter.ReadUint8()
}
}})
jsoniter.RegisterTypeDecoder("int16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
iter.ReportError("fuzzy decode int16", "exceed range")
return
}
*((*int16)(ptr)) = int16(val)
} else {
*((*int16)(ptr)) = iter.ReadInt16()
}
}})
jsoniter.RegisterTypeDecoder("uint16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint16) || val < 0 {
iter.ReportError("fuzzy decode uint16", "exceed range")
return
}
*((*uint16)(ptr)) = uint16(val)
} else {
*((*uint16)(ptr)) = iter.ReadUint16()
}
}})
jsoniter.RegisterTypeDecoder("int32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
iter.ReportError("fuzzy decode int32", "exceed range")
return
}
*((*int32)(ptr)) = int32(val)
} else {
*((*int32)(ptr)) = iter.ReadInt32()
}
}})
jsoniter.RegisterTypeDecoder("uint32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint32) || val < 0 {
iter.ReportError("fuzzy decode uint32", "exceed range")
return
}
*((*uint32)(ptr)) = uint32(val)
} else {
*((*uint32)(ptr)) = iter.ReadUint32()
}
}})
jsoniter.RegisterTypeDecoder("int64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
iter.ReportError("fuzzy decode int64", "exceed range")
return
}
*((*int64)(ptr)) = int64(val)
} else {
*((*int64)(ptr)) = iter.ReadInt64()
}
}})
jsoniter.RegisterTypeDecoder("uint64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint64) || val < 0 {
iter.ReportError("fuzzy decode uint64", "exceed range")
return
}
*((*uint64)(ptr)) = uint64(val)
} else {
*((*uint64)(ptr)) = iter.ReadUint64()
}
}})
}
type tolerateEmptyArrayExtension struct {
jsoniter.DummyExtension
}
func (extension *tolerateEmptyArrayExtension) DecorateDecoder(typ reflect2.Type, decoder jsoniter.ValDecoder) jsoniter.ValDecoder {
if typ.Kind() == reflect.Struct || typ.Kind() == reflect.Map {
return &tolerateEmptyArrayDecoder{decoder}
}
return decoder
}
type tolerateEmptyArrayDecoder struct {
valDecoder jsoniter.ValDecoder
}
func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if iter.WhatIsNext() == jsoniter.ArrayValue {
iter.Skip()
newIter := iter.Pool().BorrowIterator([]byte("{}"))
defer iter.Pool().ReturnIterator(newIter)
decoder.valDecoder.Decode(ptr, newIter)
} else {
decoder.valDecoder.Decode(ptr, iter)
}
}
type fuzzyStringDecoder struct {
}
func (decoder *fuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
*((*string)(ptr)) = string(number)
case jsoniter.StringValue:
*((*string)(ptr)) = iter.ReadString()
case jsoniter.NilValue:
iter.Skip()
*((*string)(ptr)) = ""
default:
iter.ReportError("fuzzyStringDecoder", "not number or string")
}
}
type fuzzyIntegerDecoder struct {
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
}
func (decoder *fuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
str = string(number)
case jsoniter.StringValue:
str = iter.ReadString()
case jsoniter.BoolValue:
if iter.ReadBool() {
str = "1"
} else {
str = "0"
}
case jsoniter.NilValue:
iter.Skip()
str = "0"
default:
iter.ReportError("fuzzyIntegerDecoder", "not number or string")
}
if len(str) == 0 {
str = "0"
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
isFloat := strings.IndexByte(str, '.') != -1
decoder.fun(isFloat, ptr, newIter)
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
}
type fuzzyFloat32Decoder struct {
}
func (decoder *fuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float32)(ptr)) = iter.ReadFloat32()
case jsoniter.StringValue:
str = iter.ReadString()
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float32)(ptr)) = newIter.ReadFloat32()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float32
if iter.ReadBool() {
*((*float32)(ptr)) = 1
} else {
*((*float32)(ptr)) = 0
}
case jsoniter.NilValue:
iter.Skip()
*((*float32)(ptr)) = 0
default:
iter.ReportError("fuzzyFloat32Decoder", "not number or string")
}
}
type fuzzyFloat64Decoder struct {
}
func (decoder *fuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float64)(ptr)) = iter.ReadFloat64()
case jsoniter.StringValue:
str = iter.ReadString()
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float64)(ptr)) = newIter.ReadFloat64()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float64
if iter.ReadBool() {
*((*float64)(ptr)) = 1
} else {
*((*float64)(ptr)) = 0
}
case jsoniter.NilValue:
iter.Skip()
*((*float64)(ptr)) = 0
default:
iter.ReportError("fuzzyFloat64Decoder", "not number or string")
}
}
================================================
FILE: extra/fuzzy_decoder_test.go
================================================
package extra
import (
"testing"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)
func init() {
RegisterFuzzyDecoders()
}
func Test_any_to_string(t *testing.T) {
should := require.New(t)
var val string
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal("100", val)
should.Nil(jsoniter.UnmarshalFromString("10", &val))
should.Equal("10", val)
should.Nil(jsoniter.UnmarshalFromString("10.1", &val))
should.Equal("10.1", val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal("10.1", val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
}
func Test_any_to_int64(t *testing.T) {
should := require.New(t)
var val int64
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(int64(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(int64(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(int64(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(int64(10), val)
should.Nil(jsoniter.UnmarshalFromString(`""`, &val))
should.Equal(int64(0), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(int64(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(int64(1), val)
should.Nil(jsoniter.UnmarshalFromString(`-10`, &val))
should.Equal(int64(-10), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_int(t *testing.T) {
should := require.New(t)
var val int
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(100, val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(10, val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(10, val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(10, val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(0, val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(1, val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_int16(t *testing.T) {
should := require.New(t)
var val int16
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(int16(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(int16(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(int16(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(int16(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(int16(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(int16(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_int32(t *testing.T) {
should := require.New(t)
var val int32
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(int32(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(int32(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(int32(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(int32(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(int32(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(int32(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_int8(t *testing.T) {
should := require.New(t)
var val int8
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(int8(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(int8(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(int8(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(int8(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(int8(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(int8(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_uint8(t *testing.T) {
should := require.New(t)
var val uint8
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(uint8(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(uint8(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(uint8(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(uint8(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(uint8(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(uint8(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_uint64(t *testing.T) {
should := require.New(t)
var val uint64
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(uint64(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(uint64(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(uint64(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(uint64(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(uint64(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(uint64(1), val)
// TODO fix?
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
should.Equal(uint64(0), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_uint32(t *testing.T) {
should := require.New(t)
var val uint32
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(uint32(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(uint32(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(uint32(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(uint32(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(uint32(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(uint32(1), val)
// TODO fix?
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
should.Equal(uint32(0), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_uint16(t *testing.T) {
should := require.New(t)
var val uint16
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(uint16(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(uint16(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(uint16(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(uint16(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(uint16(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(uint16(1), val)
// TODO fix?
should.NotNil(jsoniter.UnmarshalFromString(`-10`, &val))
should.Equal(uint16(0), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_uint(t *testing.T) {
should := require.New(t)
var val uint
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(uint(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(uint(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(uint(10), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(uint(10), val)
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(uint(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(uint(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
// large float to int
should.NotNil(jsoniter.UnmarshalFromString(`1234512345123451234512345.0`, &val))
}
func Test_any_to_float32(t *testing.T) {
should := require.New(t)
var val float32
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(float32(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(float32(10.1), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(float32(10.1), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(float32(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(float32(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(float32(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
}
func Test_any_to_float64(t *testing.T) {
should := require.New(t)
var val float64
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
should.Equal(float64(100), val)
should.Nil(jsoniter.UnmarshalFromString(`"10.1"`, &val))
should.Equal(float64(10.1), val)
should.Nil(jsoniter.UnmarshalFromString(`10.1`, &val))
should.Equal(float64(10.1), val)
should.Nil(jsoniter.UnmarshalFromString(`10`, &val))
should.Equal(float64(10), val)
// bool part
should.Nil(jsoniter.UnmarshalFromString(`false`, &val))
should.Equal(float64(0), val)
should.Nil(jsoniter.UnmarshalFromString(`true`, &val))
should.Equal(float64(1), val)
should.NotNil(jsoniter.UnmarshalFromString("{}", &val))
should.NotNil(jsoniter.UnmarshalFromString("[]", &val))
}
func Test_empty_array_as_map(t *testing.T) {
should := require.New(t)
var val map[string]interface{}
should.Nil(jsoniter.UnmarshalFromString(`[]`, &val))
should.Equal(map[string]interface{}{}, val)
}
func Test_empty_array_as_object(t *testing.T) {
should := require.New(t)
var val struct{}
should.Nil(jsoniter.UnmarshalFromString(`[]`, &val))
should.Equal(struct{}{}, val)
}
func Test_bad_case(t *testing.T) {
var jsonstr = `
{
"extra_type": 181760,
"combo_type": 0,
"trigger_time_ms": 1498800398000,
"_create_time": "2017-06-16 11:21:39",
"_msg_type": 41000
}
`
type OrderEventRequestParams struct {
ExtraType uint64 `json:"extra_type"`
}
var a OrderEventRequestParams
err := jsoniter.UnmarshalFromString(jsonstr, &a)
should := require.New(t)
should.Nil(err)
}
func Test_null_to_string(t *testing.T) {
should := require.New(t)
body := []byte(`null`)
var message string
err := jsoniter.Unmarshal(body, &message)
should.NoError(err)
}
func Test_null_to_int(t *testing.T) {
should := require.New(t)
body := []byte(`null`)
var message int
err := jsoniter.Unmarshal(body, &message)
should.NoError(err)
}
func Test_null_to_float32(t *testing.T) {
should := require.New(t)
body := []byte(`null`)
var message float32
err := jsoniter.Unmarshal(body, &message)
should.NoError(err)
}
func Test_null_to_float64(t *testing.T) {
should := require.New(t)
body := []byte(`null`)
var message float64
err := jsoniter.Unmarshal(body, &message)
should.NoError(err)
}
================================================
FILE: extra/naming_strategy.go
================================================
package extra
import (
"github.com/json-iterator/go"
"strings"
"unicode"
)
// SetNamingStrategy rename struct fields uniformly
func SetNamingStrategy(translate func(string) string) {
jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})
}
type namingStrategyExtension struct {
jsoniter.DummyExtension
translate func(string) string
}
func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
for _, binding := range structDescriptor.Fields {
if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{
continue
}
tag, hastag := binding.Field.Tag().Lookup("json")
if hastag {
tagParts := strings.Split(tag, ",")
if tagParts[0] == "-" {
continue // hidden field
}
if tagParts[0] != "" {
continue // field explicitly named
}
}
binding.ToNames = []string{extension.translate(binding.Field.Name())}
binding.FromNames = []string{extension.translate(binding.Field.Name())}
}
}
// LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
func LowerCaseWithUnderscores(name string) string {
newName := []rune{}
for i, c := range name {
if i == 0 {
newName = append(newName, unicode.ToLower(c))
} else {
if unicode.IsUpper(c) {
newName = append(newName, '_')
newName = append(newName, unicode.ToLower(c))
} else {
newName = append(newName, c)
}
}
}
return string(newName)
}
================================================
FILE: extra/naming_strategy_test.go
================================================
package extra
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func Test_lower_case_with_underscores(t *testing.T) {
should := require.New(t)
should.Equal("hello_world", LowerCaseWithUnderscores("helloWorld"))
should.Equal("hello_world", LowerCaseWithUnderscores("HelloWorld"))
SetNamingStrategy(LowerCaseWithUnderscores)
output, err := jsoniter.Marshal(struct {
UserName string
FirstLanguage string
}{
UserName: "taowen",
FirstLanguage: "Chinese",
})
should.Nil(err)
should.Equal(`{"user_name":"taowen","first_language":"Chinese"}`, string(output))
}
func Test_set_naming_strategy_with_overrides(t *testing.T) {
should := require.New(t)
SetNamingStrategy(LowerCaseWithUnderscores)
output, err := jsoniter.Marshal(struct {
UserName string `json:"UserName"`
FirstLanguage string
}{
UserName: "taowen",
FirstLanguage: "Chinese",
})
should.Nil(err)
should.Equal(`{"UserName":"taowen","first_language":"Chinese"}`, string(output))
}
func Test_set_naming_strategy_with_omitempty(t *testing.T) {
should := require.New(t)
SetNamingStrategy(LowerCaseWithUnderscores)
output, err := jsoniter.Marshal(struct {
UserName string
FirstLanguage string `json:",omitempty"`
}{
UserName: "taowen",
})
should.Nil(err)
should.Equal(`{"user_name":"taowen"}`, string(output))
}
func Test_set_naming_strategy_with_private_field(t *testing.T) {
should := require.New(t)
SetNamingStrategy(LowerCaseWithUnderscores)
output, err := jsoniter.Marshal(struct {
UserName string
userId int
_UserAge int
}{
UserName: "allen",
userId: 100,
_UserAge: 30,
})
should.Nil(err)
should.Equal(`{"user_name":"allen"}`, string(output))
}
================================================
FILE: extra/privat_fields.go
================================================
package extra
import (
"github.com/json-iterator/go"
"strings"
"unicode"
)
// SupportPrivateFields include private fields when encoding/decoding
func SupportPrivateFields() {
jsoniter.RegisterExtension(&privateFieldsExtension{})
}
type privateFieldsExtension struct {
jsoniter.DummyExtension
}
func (extension *privateFieldsExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
for _, binding := range structDescriptor.Fields {
isPrivate := unicode.IsLower(rune(binding.Field.Name()[0]))
if isPrivate {
tag, hastag := binding.Field.Tag().Lookup("json")
if !hastag {
binding.FromNames = []string{binding.Field.Name()}
binding.ToNames = []string{binding.Field.Name()}
continue
}
tagParts := strings.Split(tag, ",")
names := calcFieldNames(binding.Field.Name(), tagParts[0], tag)
binding.FromNames = names
binding.ToNames = names
}
}
}
func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
// ignore?
if wholeTag == "-" {
return []string{}
}
// rename?
var fieldNames []string
if tagProvidedFieldName == "" {
fieldNames = []string{originalFieldName}
} else {
fieldNames = []string{tagProvidedFieldName}
}
// private?
isNotExported := unicode.IsLower(rune(originalFieldName[0]))
if isNotExported {
fieldNames = []string{}
}
return fieldNames
}
================================================
FILE: extra/private_fields_test.go
================================================
package extra
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
)
func Test_private_fields(t *testing.T) {
type TestObject struct {
field1 string
}
SupportPrivateFields()
should := require.New(t)
obj := TestObject{}
should.Nil(jsoniter.UnmarshalFromString(`{"field1":"Hello"}`, &obj))
should.Equal("Hello", obj.field1)
}
================================================
FILE: extra/time_as_int64_codec.go
================================================
package extra
import (
"github.com/json-iterator/go"
"time"
"unsafe"
)
// RegisterTimeAsInt64Codec encode/decode time since number of unit since epoch. the precision is the unit.
func RegisterTimeAsInt64Codec(precision time.Duration) {
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
}
type timeAsInt64Codec struct {
precision time.Duration
}
func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
nanoseconds := iter.ReadInt64() * codec.precision.Nanoseconds()
*((*time.Time)(ptr)) = time.Unix(0, nanoseconds)
}
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
ts := *((*time.Time)(ptr))
return ts.UnixNano() == 0
}
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
ts := *((*time.Time)(ptr))
stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
}
================================================
FILE: extra/time_as_int64_codec_test.go
================================================
package extra
import (
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"testing"
"time"
)
func Test_time_as_int64(t *testing.T) {
should := require.New(t)
RegisterTimeAsInt64Codec(time.Nanosecond)
output, err := jsoniter.Marshal(time.Unix(1497952257, 1002))
should.Nil(err)
should.Equal("1497952257000001002", string(output))
var val time.Time
should.Nil(jsoniter.Unmarshal(output, &val))
should.Equal(int64(1497952257000001002), val.UnixNano())
}
func Test_time_as_int64_keep_microsecond(t *testing.T) {
t.Skip("conflict")
should := require.New(t)
RegisterTimeAsInt64Codec(time.Microsecond)
output, err := jsoniter.Marshal(time.Unix(1, 1002))
should.Nil(err)
should.Equal("1000001", string(output))
var val time.Time
should.Nil(jsoniter.Unmarshal(output, &val))
should.Equal(int64(1000001000), val.UnixNano())
}
================================================
FILE: fuzzy_mode_convert_table.md
================================================
| json type \ dest type | bool | int | uint | float |string|
| --- | --- | --- | --- |--|--|
| number | positive => true <br/> negative => true <br/> zero => false| 23.2 => 23 <br/> -32.1 => -32| 12.1 => 12 <br/> -12.1 => 0|as normal|same as origin|
| string | empty string => false <br/> string "0" => false <br/> other strings => true | "123.32" => 123 <br/> "-123.4" => -123 <br/> "123.23xxxw" => 123 <br/> "abcde12" => 0 <br/> "-32.1" => -32| 13.2 => 13 <br/> -1.1 => 0 |12.1 => 12.1 <br/> -12.3 => -12.3<br/> 12.4xxa => 12.4 <br/> +1.1e2 =>110 |same as origin|
| bool | true => true <br/> false => false| true => 1 <br/> false => 0 | true => 1 <br/> false => 0 |true => 1 <br/>false => 0|true => "true" <br/> false => "false"|
| object | true | 0 | 0 |0|originnal json|
| array | empty array => false <br/> nonempty array => true| [] => 0 <br/> [1,2] => 1 | [] => 0 <br/> [1,2] => 1 |[] => 0<br/>[1,2] => 1|original json|
================================================
FILE: go.mod
================================================
module github.com/json-iterator/go
go 1.12
require (
github.com/davecgh/go-spew v1.1.1
github.com/google/gofuzz v1.0.0
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421
github.com/modern-go/reflect2 v1.0.2
github.com/stretchr/testify v1.8.0
)
================================================
FILE: go.sum
================================================
github.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 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: iter.go
================================================
package jsoniter
import (
"encoding/json"
"fmt"
"io"
)
// ValueType the type for JSON element
type ValueType int
const (
// InvalidValue invalid JSON element
InvalidValue ValueType = iota
// StringValue JSON element "string"
StringValue
// NumberValue JSON element 100 or 0.10
NumberValue
// NilValue JSON element null
NilValue
// BoolValue JSON element true or false
BoolValue
// ArrayValue JSON element []
ArrayValue
// ObjectValue JSON element {}
ObjectValue
)
var hexDigits []byte
var valueTypes []ValueType
func init() {
hexDigits = make([]byte, 256)
for i := 0; i < len(hexDigits); i++ {
hexDigits[i] = 255
}
for i := '0'; i <= '9'; i++ {
hexDigits[i] = byte(i - '0')
}
for i := 'a'; i <= 'f'; i++ {
hexDigits[i] = byte((i - 'a') + 10)
}
for i := 'A'; i <= 'F'; i++ {
hexDigits[i] = byte((i - 'A') + 10)
}
valueTypes = make([]ValueType, 256)
for i := 0; i < len(valueTypes); i++ {
valueTypes[i] = InvalidValue
}
valueTypes['"'] = StringValue
valueTypes['-'] = NumberValue
valueTypes['0'] = NumberValue
valueTypes['1'] = NumberValue
valueTypes['2'] = NumberValue
valueTypes['3'] = NumberValue
valueTypes['4'] = NumberValue
valueTypes['5'] = NumberValue
valueTypes['6'] = NumberValue
valueTypes['7'] = NumberValue
valueTypes['8'] = NumberValue
valueTypes['9'] = NumberValue
valueTypes['t'] = BoolValue
valueTypes['f'] = BoolValue
valueTypes['n'] = NilValue
valueTypes['['] = ArrayValue
valueTypes['{'] = ObjectValue
}
// Iterator is a io.Reader like object, with JSON specific read functions.
// Error is not returned as return value, but stored as Error member on this iterator instance.
type Iterator struct {
cfg *frozenConfig
reader io.Reader
buf []byte
head int
tail int
depth int
captureStartedAt int
captured []byte
Error error
Attachment interface{} // open for customized decoder
}
// NewIterator creates an empty Iterator instance
func NewIterator(cfg API) *Iterator {
return &Iterator{
cfg: cfg.(*frozenConfig),
reader: nil,
buf: nil,
head: 0,
tail: 0,
depth: 0,
}
}
// Parse creates an Iterator instance from io.Reader
func Parse(cfg API, reader io.Reader, bufSize int) *Iterator {
return &Iterator{
cfg: cfg.(*frozenConfig),
reader: reader,
buf: make([]byte, bufSize),
head: 0,
tail: 0,
depth: 0,
}
}
// ParseBytes creates an Iterator instance from byte array
func ParseBytes(cfg API, input []byte) *Iterator {
return &Iterator{
cfg: cfg.(*frozenConfig),
reader: nil,
buf: input,
head: 0,
tail: len(input),
depth: 0,
}
}
// ParseString creates an Iterator instance from string
func ParseString(cfg API, input string) *Iterator {
return ParseBytes(cfg, []byte(input))
}
// Pool returns a pool can provide more iterator with same configuration
func (iter *Iterator) Pool() IteratorPool {
return iter.cfg
}
// Reset reuse iterator instance by specifying another reader
func (iter *Iterator) Reset(reader io.Reader) *Iterator {
iter.reader = reader
iter.head = 0
iter.tail = 0
iter.depth = 0
return iter
}
// ResetBytes reuse iterator instance by specifying another byte array as input
func (iter *Iterator) ResetBytes(input []byte) *Iterator {
iter.reader = nil
iter.buf = input
iter.head = 0
iter.tail = len(input)
iter.depth = 0
return iter
}
// WhatIsNext gets ValueType of relatively next json element
func (iter *Iterator) WhatIsNext() ValueType {
valueType := valueTypes[iter.nextToken()]
iter.unreadByte()
return valueType
}
func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool {
for i := iter.head; i < iter.tail; i++ {
c := iter.buf[i]
switch c {
case ' ', '\n', '\t', '\r':
continue
}
iter.head = i
return false
}
return true
}
func (iter *Iterator) isObjectEnd() bool {
c := iter.nextToken()
if c == ',' {
return false
}
if c == '}' {
return true
}
iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c}))
return true
}
func (iter *Iterator) nextToken() byte {
// a variation of skip whitespaces, returning the next non-whitespace token
for {
for i := iter.head; i < iter.tail; i++ {
c := iter.buf[i]
switch c {
case ' ', '\n', '\t', '\r':
continue
}
iter.head = i + 1
return c
}
if !iter.loadMore() {
return 0
}
}
}
// ReportError record a error in iterator instance with current position.
func (iter *Iterator) ReportError(operation string, msg string) {
if iter.Error != nil {
if iter.Error != io.EOF {
return
}
}
peekStart := iter.head - 10
if peekStart < 0 {
peekStart = 0
}
peekEnd := iter.head + 10
if peekEnd > iter.tail {
peekEnd = iter.tail
}
parsing := string(iter.buf[peekStart:peekEnd])
contextStart := iter.head - 50
if contextStart < 0 {
contextStart = 0
}
contextEnd := iter.head + 50
if contextEnd > iter.tail {
contextEnd = iter.tail
}
context := string(iter.buf[contextStart:contextEnd])
iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...",
operation, msg, iter.head-peekStart, parsing, context)
}
// CurrentBuffer gets current buffer as string for debugging purpose
func (iter *Iterator) CurrentBuffer() string {
peekStart := iter.head - 10
if peekStart < 0 {
peekStart = 0
}
return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head,
string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail]))
}
func (iter *Iterator) readByte() (ret byte) {
if iter.head == iter.tail {
if iter.loadMore() {
ret = iter.buf[iter.head]
iter.head++
return ret
}
return 0
}
ret = iter.buf[iter.head]
iter.head++
return ret
}
func (iter *Iterator) loadMore() bool {
if iter.reader == nil {
if iter.Error == nil {
iter.head = iter.tail
iter.Error = io.EOF
}
return false
}
if iter.captured != nil {
iter.captured = append(iter.captured,
iter.buf[iter.captureStartedAt:iter.tail]...)
iter.captureStartedAt = 0
}
for {
n, err := iter.reader.Read(iter.buf)
if n == 0 {
if err != nil {
if iter.Error == nil {
iter.Error = err
}
return false
}
} else {
iter.head = 0
iter.tail = n
return true
}
}
}
func (iter *Iterator) unreadByte() {
if iter.Error != nil {
return
}
iter.head--
return
}
// Read read the next JSON element as generic interface{}.
func (iter *Iterator) Read() interface{} {
valueType := iter.WhatIsNext()
switch valueType {
case StringValue:
return iter.ReadString()
case NumberValue:
if iter.cfg.configBeforeFrozen.UseNumber {
return json.Number(iter.readNumberAsString())
}
return iter.ReadFloat64()
case NilValue:
iter.skipFourBytes('n', 'u', 'l', 'l')
return nil
case BoolValue:
return iter.ReadBool()
case ArrayValue:
arr := []interface{}{}
iter.ReadArrayCB(func(iter *Iterator) bool {
var elem interface{}
iter.ReadVal(&elem)
arr = append(arr, elem)
return true
})
return arr
case ObjectValue:
obj := map[string]interface{}{}
iter.ReadMapCB(func(Iter *Iterator, field string) bool {
var elem interface{}
iter.ReadVal(&elem)
obj[field] = elem
return true
})
return obj
default:
iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType))
return nil
}
}
// limit maximum depth of nesting, as allowed by https://tools.ietf.org/html/rfc7159#section-9
const maxDepth = 10000
func (iter *Iterator) incrementDepth() (success bool) {
iter.depth++
if iter.depth <= maxDepth {
return true
}
iter.ReportError("incrementDepth", "exceeded max depth")
return false
}
func (iter *Iterator) decrementDepth() (success bool) {
iter.depth--
if iter.depth >= 0 {
return true
}
iter.ReportError("decrementDepth", "unexpected negative nesting")
return false
}
================================================
FILE: iter_array.go
================================================
package jsoniter
// ReadArray read array element, tells if the array has more element to read.
func (iter *Iterator) ReadArray() (ret bool) {
c := iter.nextToken()
switch c {
case 'n':
iter.skipThreeBytes('u', 'l', 'l')
return false // null
case '[':
c = iter.nextToken()
if c != ']' {
iter.unreadByte()
return true
}
return false
case ']':
return false
case ',':
return true
default:
iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c}))
return
}
}
// ReadArrayCB read array with callback
func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) {
c := iter.nextToken()
if c == '[' {
if !iter.incrementDepth() {
return false
}
c = iter.nextToken()
if c != ']' {
iter.unreadByte()
if !callback(iter) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
for c == ',' {
if !callback(iter) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
}
if c != ']' {
iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c}))
iter.decrementDepth()
return false
}
return iter.decrementDepth()
}
return iter.decrementDepth()
}
if c == 'n' {
iter.skipThreeBytes('u', 'l', 'l')
return true // null
}
iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c}))
return false
}
================================================
FILE: iter_float.go
================================================
package jsoniter
import (
"encoding/json"
"io"
"math/big"
"strconv"
"strings"
"unsafe"
)
var floatDigits []int8
const invalidCharForNumber = int8(-1)
const endOfNumber = int8(-2)
const dotInNumber = int8(-3)
func init() {
floatDigits = make([]int8, 256)
for i := 0; i < len(floatDigits); i++ {
floatDigits[i] = invalidCharForNumber
}
for i := int8('0'); i <= int8('9'); i++ {
floatDigits[i] = i - int8('0')
}
floatDigits[','] = endOfNumber
floatDigits[']'] = endOfNumber
floatDigits['}'] = endOfNumber
floatDigits[' '] = endOfNumber
floatDigits['\t'] = endOfNumber
floatDigits['\n'] = endOfNumber
floatDigits['.'] = dotInNumber
}
// ReadBigFloat read big.Float
func (iter *Iterator) ReadBigFloat() (ret *big.Float) {
str := iter.readNumberAsString()
if iter.Error != nil && iter.Error != io.EOF {
return nil
}
prec := 64
if len(str) > prec {
prec = len(str)
}
val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero)
if err != nil {
iter.Error = err
return nil
}
return val
}
// ReadBigInt read big.Int
func (iter *Iterator) ReadBigInt() (ret *big.Int) {
str := iter.readNumberAsString()
if iter.Error != nil && iter.Error != io.EOF {
return nil
}
ret = big.NewInt(0)
var success bool
ret, success = ret.SetString(str, 10)
if !success {
iter.ReportError("ReadBigInt", "invalid big int")
return nil
}
return ret
}
//ReadFloat32 read float32
func (iter *Iterator) ReadFloat32() (ret float32) {
c := iter.nextToken()
if c == '-' {
return -iter.readPositiveFloat32()
}
iter.unreadByte()
return iter.readPositiveFloat32()
}
func (iter *Iterator) readPositiveFloat32() (ret float32) {
i := iter.head
// first char
if i == iter.tail {
return iter.readFloat32SlowPath()
}
c := iter.buf[i]
i++
ind := floatDigits[c]
switch ind {
case invalidCharForNumber:
return iter.readFloat32SlowPath()
case endOfNumber:
iter.ReportError("readFloat32", "empty number")
return
case dotInNumber:
iter.ReportError("readFloat32", "leading dot is invalid")
return
case 0:
if i == iter.tail {
return iter.readFloat32SlowPath()
}
c = iter.buf[i]
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
iter.ReportError("readFloat32", "leading zero is invalid")
return
}
}
value := uint64(ind)
// chars before dot
non_decimal_loop:
for ; i < iter.tail; i++ {
c = iter.buf[i]
ind := floatDigits[c]
switch ind {
case invalidCharForNumber:
return iter.readFloat32SlowPath()
case endOfNumber:
iter.head = i
return float32(value)
case dotInNumber:
break non_decimal_loop
}
if value > uint64SafeToMultiple10 {
return iter.readFloat32SlowPath()
}
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
}
// chars after dot
if c == '.' {
i++
decimalPlaces := 0
if i == iter.tail {
return iter.readFloat32SlowPath()
}
for ; i < iter.tail; i++ {
c = iter.buf[i]
ind := floatDigits[c]
switch ind {
case endOfNumber:
if decimalPlaces > 0 && decimalPlaces < len(pow10) {
iter.head = i
return float32(float64(value) / float64(pow10[decimalPlaces]))
}
// too many decimal places
return iter.readFloat32SlowPath()
case invalidCharForNumber, dotInNumber:
return iter.readFloat32SlowPath()
}
decimalPlaces++
if value > uint64SafeToMultiple10 {
return iter.readFloat32SlowPath()
}
value = (value << 3) + (value << 1) + uint64(ind)
}
}
return iter.readFloat32SlowPath()
}
func (iter *Iterator) readNumberAsString() (ret string) {
strBuf := [16]byte{}
str := strBuf[0:0]
load_loop:
for {
for i := iter.head; i < iter.tail; i++ {
c := iter.buf[i]
switch c {
case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
str = append(str, c)
continue
default:
iter.head = i
break load_loop
}
}
if !iter.loadMore() {
break
}
}
if iter.Error != nil && iter.Error != io.EOF {
return
}
if len(str) == 0 {
iter.ReportError("readNumberAsString", "invalid number")
}
return *(*string)(unsafe.Pointer(&str))
}
func (iter *Iterator) readFloat32SlowPath() (ret float32) {
str := iter.readNumberAsString()
if iter.Error != nil && iter.Error != io.EOF {
return
}
errMsg := validateFloat(str)
if errMsg != "" {
iter.ReportError("readFloat32SlowPath", errMsg)
return
}
val, err := strconv.ParseFloat(str, 32)
if err != nil {
iter.Error = err
return
}
return float32(val)
}
// ReadFloat64 read float64
func (iter *Iterator) ReadFloat64() (ret float64) {
c := iter.nextToken()
if c == '-' {
return -iter.readPositiveFloat64()
}
iter.unreadByte()
return iter.readPositiveFloat64()
}
func (iter *Iterator) readPositiveFloat64() (ret float64) {
i := iter.head
// first char
if i == iter.tail {
return iter.readFloat64SlowPath()
}
c := iter.buf[i]
i++
ind := floatDigits[c]
switch ind {
case invalidCharForNumber:
return iter.readFloat64SlowPath()
case endOfNumber:
iter.ReportError("readFloat64", "empty number")
return
case dotInNumber:
iter.ReportError("readFloat64", "leading dot is invalid")
return
case 0:
if i == iter.tail {
return iter.readFloat64SlowPath()
}
c = iter.buf[i]
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
iter.ReportError("readFloat64", "leading zero is invalid")
return
}
}
value := uint64(ind)
// chars before dot
non_decimal_loop:
for ; i < iter.tail; i++ {
c = iter.buf[i]
ind := floatDigits[c]
switch ind {
case invalidCharForNumber:
return iter.readFloat64SlowPath()
case endOfNumber:
iter.head = i
return float64(value)
case dotInNumber:
break non_decimal_loop
}
if value > uint64SafeToMultiple10 {
return iter.readFloat64SlowPath()
}
value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind;
}
// chars after dot
if c == '.' {
i++
decimalPlaces := 0
if i == iter.tail {
return iter.readFloat64SlowPath()
}
for ; i < iter.tail; i++ {
c = iter.buf[i]
ind := floatDigits[c]
switch ind {
case endOfNumber:
if decimalPlaces > 0 && decimalPlaces < len(pow10) {
iter.head = i
return float64(value) / float64(pow10[decimalPlaces])
}
// too many decimal places
return iter.readFloat64SlowPath()
case invalidCharForNumber, dotInNumber:
return iter.readFloat64SlowPath()
}
decimalPlaces++
if value > uint64SafeToMultiple10 {
return iter.readFloat64SlowPath()
}
value = (value << 3) + (value << 1) + uint64(ind)
if value > maxFloat64 {
return iter.readFloat64SlowPath()
}
}
}
return iter.readFloat64SlowPath()
}
func (iter *Iterator) readFloat64SlowPath() (ret float64) {
str := iter.readNumberAsString()
if iter.Error != nil && iter.Error != io.EOF {
return
}
errMsg := validateFloat(str)
if errMsg != "" {
iter.ReportError("readFloat64SlowPath", errMsg)
return
}
val, err := strconv.ParseFloat(str, 64)
if err != nil {
iter.Error = err
return
}
return val
}
func validateFloat(str string) string {
// strconv.ParseFloat is not validating `1.` or `1.e1`
if len(str) == 0 {
return "empty number"
}
if str[0] == '-' {
return "-- is not valid"
}
dotPos := strings.IndexByte(str, '.')
if dotPos != -1 {
if dotPos == len(str)-1 {
return "dot can not be last character"
}
switch str[dotPos+1] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
default:
return "missing digit after dot"
}
}
return ""
}
// ReadNumber read json.Number
func (iter *Iterator) ReadNumber() (ret json.Number) {
return json.Number(iter.readNumberAsString())
}
================================================
FILE: iter_int.go
================================================
package jsoniter
import (
"math"
"strconv"
)
var intDigits []int8
const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1
const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1
const maxFloat64 = 1<<53 - 1
func init() {
intDigits = make([]int8, 256)
for i := 0; i < len(intDigits); i++ {
intDigits[i] = invalidCharForNumber
}
for i := int8('0'); i <= int8('9'); i++ {
intDigits[i] = i - int8('0')
}
}
// ReadUint read uint
func (iter *Iterator) ReadUint() uint {
if strconv.IntSize == 32 {
return uint(iter.ReadUint32())
}
return uint(iter.ReadUint64())
}
// ReadInt read int
func (iter *Iterator) ReadInt() int {
if strconv.IntSize == 32 {
return int(iter.ReadInt32())
}
return int(iter.ReadInt64())
}
// ReadInt8 read int8
func (iter *Iterator) ReadInt8() (ret int8) {
c := iter.nextToken()
if c == '-' {
val := iter.readUint32(iter.readByte())
if val > math.MaxInt8+1 {
iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return -int8(val)
}
val := iter.readUint32(c)
if val > math.MaxInt8 {
iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return int8(val)
}
// ReadUint8 read uint8
func (iter *Iterator) ReadUint8() (ret uint8) {
val := iter.readUint32(iter.nextToken())
if val > math.MaxUint8 {
iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return uint8(val)
}
// ReadInt16 read int16
func (iter *Iterator) ReadInt16() (ret int16) {
c := iter.nextToken()
if c == '-' {
val := iter.readUint32(iter.readByte())
if val > math.MaxInt16+1 {
iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return -int16(val)
}
val := iter.readUint32(c)
if val > math.MaxInt16 {
iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return int16(val)
}
// ReadUint16 read uint16
func (iter *Iterator) ReadUint16() (ret uint16) {
val := iter.readUint32(iter.nextToken())
if val > math.MaxUint16 {
iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return uint16(val)
}
// ReadInt32 read int32
func (iter *Iterator) ReadInt32() (ret int32) {
c := iter.nextToken()
if c == '-' {
val := iter.readUint32(iter.readByte())
if val > math.MaxInt32+1 {
iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return -int32(val)
}
val := iter.readUint32(c)
if val > math.MaxInt32 {
iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10))
return
}
return int32(val)
}
// ReadUint32 read uint32
func (iter *Iterator) ReadUint32() (ret uint32) {
return iter.readUint32(iter.nextToken())
}
func (iter *Iterator) readUint32(c byte) (ret uint32) {
ind := intDigits[c]
if ind == 0 {
iter.assertInteger()
return 0 // single zero
}
if ind == invalidCharForNumber {
iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)}))
return
}
value := uint32(ind)
if iter.tail-iter.head > 10 {
i := iter.head
ind2 := intDigits[iter.buf[i]]
if ind2 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value
}
i++
ind3 := intDigits[iter.buf[i]]
if ind3 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*10 + uint32(ind2)
}
//iter.head = i + 1
//value = value * 100 + uint32(ind2) * 10 + uint32(ind3)
i++
ind4 := intDigits[iter.buf[i]]
if ind4 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*100 + uint32(ind2)*10 + uint32(ind3)
}
i++
ind5 := intDigits[iter.buf[i]]
if ind5 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4)
}
i++
ind6 := intDigits[iter.buf[i]]
if ind6 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5)
}
i++
ind7 := intDigits[iter.buf[i]]
if ind7 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6)
}
i++
ind8 := intDigits[iter.buf[i]]
if ind8 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7)
}
i++
ind9 := intDigits[iter.buf[i]]
value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8)
iter.head = i
if ind9 == invalidCharForNumber {
iter.assertInteger()
return value
}
}
for {
for i := iter.head; i < iter.tail; i++ {
ind = intDigits[iter.buf[i]]
if ind == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value
}
if value > uint32SafeToMultiply10 {
value2 := (value << 3) + (value << 1) + uint32(ind)
if value2 < value {
iter.ReportError("readUint32", "overflow")
return
}
value = value2
continue
}
value = (value << 3) + (value << 1) + uint32(ind)
}
if !iter.loadMore() {
iter.assertInteger()
return value
}
}
}
// ReadInt64 read int64
func (iter *Iterator) ReadInt64() (ret int64) {
c := iter.nextToken()
if c == '-' {
val := iter.readUint64(iter.readByte())
if val > math.MaxInt64+1 {
iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10))
return
}
return -int64(val)
}
val := iter.readUint64(c)
if val > math.MaxInt64 {
iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10))
return
}
return int64(val)
}
// ReadUint64 read uint64
func (iter *Iterator) ReadUint64() uint64 {
return iter.readUint64(iter.nextToken())
}
func (iter *Iterator) readUint64(c byte) (ret uint64) {
ind := intDigits[c]
if ind == 0 {
iter.assertInteger()
return 0 // single zero
}
if ind == invalidCharForNumber {
iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)}))
return
}
value := uint64(ind)
if iter.tail-iter.head > 10 {
i := iter.head
ind2 := intDigits[iter.buf[i]]
if ind2 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value
}
i++
ind3 := intDigits[iter.buf[i]]
if ind3 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*10 + uint64(ind2)
}
//iter.head = i + 1
//value = value * 100 + uint32(ind2) * 10 + uint32(ind3)
i++
ind4 := intDigits[iter.buf[i]]
if ind4 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*100 + uint64(ind2)*10 + uint64(ind3)
}
i++
ind5 := intDigits[iter.buf[i]]
if ind5 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4)
}
i++
ind6 := intDigits[iter.buf[i]]
if ind6 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5)
}
i++
ind7 := intDigits[iter.buf[i]]
if ind7 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6)
}
i++
ind8 := intDigits[iter.buf[i]]
if ind8 == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7)
}
i++
ind9 := intDigits[iter.buf[i]]
value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8)
iter.head = i
if ind9 == invalidCharForNumber {
iter.assertInteger()
return value
}
}
for {
for i := iter.head; i < iter.tail; i++ {
ind = intDigits[iter.buf[i]]
if ind == invalidCharForNumber {
iter.head = i
iter.assertInteger()
return value
}
if value > uint64SafeToMultiple10 {
value2 := (value << 3) + (value << 1) + uint64(ind)
if value2 < value {
iter.ReportError("readUint64", "overflow")
return
}
value = value2
continue
}
value = (value << 3) + (value << 1) + uint64(ind)
}
if !iter.loadMore() {
iter.assertInteger()
return value
}
}
}
func (iter *Iterator) assertInteger() {
if iter.head < iter.tail && iter.buf[iter.head] == '.' {
iter.ReportError("assertInteger", "can not decode float as int")
}
}
================================================
FILE: iter_object.go
================================================
package jsoniter
import (
"fmt"
"strings"
)
// ReadObject read one field from object.
// If object ended, returns empty string.
// Otherwise, returns the field name.
func (iter *Iterator) ReadObject() (ret string) {
c := iter.nextToken()
switch c {
case 'n':
iter.skipThreeBytes('u', 'l', 'l')
return "" // null
case '{':
c = iter.nextToken()
if c == '"' {
iter.unreadByte()
field := iter.ReadString()
c = iter.nextToken()
if c != ':' {
iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c}))
}
return field
}
if c == '}' {
return "" // end of object
}
iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c}))
return
case ',':
field := iter.ReadString()
c = iter.nextToken()
if c != ':' {
iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c}))
}
return field
case '}':
return "" // end of object
default:
iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c})))
return
}
}
// CaseInsensitive
func (iter *Iterator) readFieldHash() int64 {
hash := int64(0x811c9dc5)
c := iter.nextToken()
if c != '"' {
iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c}))
return 0
}
for {
for i := iter.head; i < iter.tail; i++ {
// require ascii string and no escape
b := iter.buf[i]
if b == '\\' {
iter.head = i
for _, b := range iter.readStringSlowPath() {
if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive {
b += 'a' - 'A'
}
hash ^= int64(b)
hash *= 0x1000193
}
c = iter.nextToken()
if c != ':' {
iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c}))
return 0
}
return hash
}
if b == '"' {
iter.head = i + 1
c = iter.nextToken()
if c != ':' {
iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c}))
return 0
}
return hash
}
if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive {
b += 'a' - 'A'
}
hash ^= int64(b)
hash *= 0x1000193
}
if !iter.loadMore() {
iter.ReportError("readFieldHash", `incomplete field name`)
return 0
}
}
}
func calcHash(str string, caseSensitive bool) int64 {
if !caseSensitive {
str = strings.ToLower(str)
}
hash := int64(0x811c9dc5)
for _, b := range []byte(str) {
hash ^= int64(b)
hash *= 0x1000193
}
return int64(hash)
}
// ReadObjectCB read object with callback, the key is ascii only and field name not copied
func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool {
c := iter.nextToken()
var field string
if c == '{' {
if !iter.incrementDepth() {
return false
}
c = iter.nextToken()
if c == '"' {
iter.unreadByte()
field = iter.ReadString()
c = iter.nextToken()
if c != ':' {
iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c}))
}
if !callback(iter, field) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
for c == ',' {
field = iter.ReadString()
c = iter.nextToken()
if c != ':' {
iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c}))
}
if !callback(iter, field) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
}
if c != '}' {
iter.ReportError("ReadObjectCB", `object not ended with }`)
iter.decrementDepth()
return false
}
return iter.decrementDepth()
}
if c == '}' {
return iter.decrementDepth()
}
iter.ReportError("ReadObjectCB", `expect " after {, but found `+string([]byte{c}))
iter.decrementDepth()
return false
}
if c == 'n' {
iter.skipThreeBytes('u', 'l', 'l')
return true // null
}
iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c}))
return false
}
// ReadMapCB read map with callback, the key can be any string
func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool {
c := iter.nextToken()
if c == '{' {
if !iter.incrementDepth() {
return false
}
c = iter.nextToken()
if c == '"' {
iter.unreadByte()
field := iter.ReadString()
if iter.nextToken() != ':' {
iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c}))
iter.decrementDepth()
return false
}
if !callback(iter, field) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
for c == ',' {
field = iter.ReadString()
if iter.nextToken() != ':' {
iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c}))
iter.decrementDepth()
return false
}
if !callback(iter, field) {
iter.decrementDepth()
return false
}
c = iter.nextToken()
}
if c != '}' {
iter.ReportError("ReadMapCB", `object not ended with }`)
iter.decrementDepth()
return false
}
return iter.decrementDepth()
}
if c == '}' {
return iter.decrementDepth()
}
iter.ReportError("ReadMapCB", `expect " after {, but found `+string([]byte{c}))
iter.decrementDepth()
return false
}
if c == 'n' {
iter.skipThreeBytes('u', 'l', 'l')
return true // null
}
iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c}))
return false
}
func (iter *Iterator) readObjectStart() bool {
c := iter.nextToken()
if c == '{' {
c = iter.nextToken()
if c == '}' {
return false
}
iter.unreadByte()
return true
} else if c == 'n' {
iter.skipThreeBytes('u', 'l', 'l')
return false
}
iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c}))
return false
}
func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) {
str := iter.ReadStringAsSlice()
if iter.skipWhitespacesWithoutLoadMore() {
if ret == nil {
ret = make([]byte, len(str))
copy(ret, str)
}
if !iter.loadMore() {
return
}
}
if iter.buf[iter.head] != ':' {
iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]}))
return
}
iter.head++
if iter.skipWhitespacesWithoutLoadMore() {
if ret == nil {
ret = make([]byte, len(str))
copy(ret, str)
}
if !iter.loadMore() {
return
}
}
if ret == nil {
return str
}
return ret
}
================================================
FILE: iter_skip.go
================================================
package jsoniter
import "fmt"
// ReadNil reads a json object as nil and
// returns whether it's a nil or not
func (iter *Iterator) ReadNil() (ret bool) {
c := iter.nextToken()
if c == 'n' {
iter.skipThreeBytes('u', 'l', 'l') // null
return true
}
iter.unreadByte()
return false
}
// ReadBool reads a json object as BoolValue
func (iter *Iterator) ReadBool() (ret bool) {
c := iter.nextToken()
if c == 't' {
iter.skipThreeBytes('r', 'u', 'e')
return true
}
if c == 'f' {
iter.skipFourBytes('a', 'l', 's', 'e')
return false
}
iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c}))
return
}
// SkipAndReturnBytes skip next JSON element, and return its content as []byte.
// The []byte can be kept, it is a copy of data.
func (iter *Iterator) SkipAndReturnBytes() []byte {
iter.startCapture(iter.head)
iter.Skip()
return iter.stopCapture()
}
// SkipAndAppendBytes skips next JSON element and appends its content to
// buffer, returning the result.
func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte {
iter.startCaptureTo(buf, iter.head)
iter.Skip()
return iter.stopCapture()
}
func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) {
if iter.captured != nil {
panic("already in capture mode")
}
iter.captureStartedAt = captureStartedAt
iter.captured = buf
}
func (iter *Iterator) startCapture(captureStartedAt int) {
iter.startCaptureTo(make([]byte, 0, 32), captureStartedAt)
}
func (iter *Iterator) stopCapture() []byte {
if iter.captured == nil {
panic("not in capture mode")
}
captured := iter.captured
remaining := iter.buf[iter.captureStartedAt:iter.head]
iter.captureStartedAt = -1
iter.captured = nil
return append(captured, remaining...)
}
// Skip skips a json object and positions to relatively the next json object
func (iter *Iterator) Skip() {
c := iter.nextToken()
switch c {
case '"':
iter.skipString()
case 'n':
iter.skipThreeBytes('u', 'l', 'l') // null
case 't':
iter.skipThreeBytes('r', 'u', 'e') // true
case 'f':
iter.skipFourBytes('a', 'l', 's', 'e') // false
case '0':
iter.unreadByte()
iter.ReadFloat32()
case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9':
iter.skipNumber()
case '[':
iter.skipArray()
case '{':
iter.skipObject()
default:
iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c))
return
}
}
func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) {
if iter.readByte() != b1 {
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
return
}
if iter.readByte() != b2 {
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
return
}
if iter.readByte() != b3 {
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
return
}
if iter.readByte() != b4 {
iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4})))
return
}
}
func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) {
if iter.readByte() != b1 {
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
return
}
if iter.readByte() != b2 {
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
return
}
if iter.readByte() != b3 {
iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3})))
return
}
}
================================================
FILE: iter_skip_sloppy.go
================================================
//+build jsoniter_sloppy
package jsoniter
// sloppy but faster implementation, do not validate the input json
func (iter *Iterator) skipNumber() {
for {
for i := iter.head; i < iter.tail; i++ {
c := iter.buf[i]
switch c {
case ' ', '\n', '\r', '\t', ',', '}', ']':
iter.head = i
return
}
}
if !iter.loadMore() {
return
}
}
}
func (iter *Iterator) skipArray() {
level := 1
if !iter.incrementDepth() {
return
}
for {
for i := iter.head; i < iter.tail; i++ {
switch iter.buf[i] {
case '"': // If inside string, skip it
iter.head = i + 1
iter.skipString()
i = iter.head - 1 // it will be i++ soon
case '[': // If open symbol, increase level
level++
if !iter.incrementDepth() {
return
}
case ']': // If close symbol, increase level
level--
if !iter.decrementDepth() {
return
}
// If we have returned to the original level, we're done
if level == 0 {
iter.head = i + 1
return
}
}
}
if !iter.loadMore() {
iter.ReportError("skipObject", "incomplete array")
return
}
}
}
func (iter *Iterator) skipObject() {
level := 1
if !iter.incrementDepth() {
return
}
for {
for i := iter.head; i < iter.tail; i++ {
switch iter.buf[i] {
case '"': // If inside string, skip it
iter.head = i + 1
iter.skipString()
i = iter.head - 1 // it will be i++ soon
case '{': // If open symbol, increase level
level++
if !iter.incrementDepth() {
return
}
case '}': // If close symbol, increase level
level--
if !iter.decrementDepth() {
return
}
// If we have returned to the original level, we're done
if level == 0 {
iter.head = i + 1
return
}
}
}
if !iter.loadMore() {
iter.ReportError("skipObject", "incomplete object")
return
}
}
}
func (iter *Iterator) skipString() {
for {
end, escaped := iter.findStringEnd()
if end == -1 {
if !iter.loadMore() {
iter.ReportError("skipString", "incomplete string")
return
}
if escaped {
iter.head = 1 // skip the first char as last char read is \
}
} else {
iter.head = end
return
}
}
}
// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go
// Tries to find the end of string
// Support if string contains escaped quote symbols.
func (iter *Iterator) findStringEnd() (int, bool) {
escaped := false
for i := iter.head; i < iter.tail; i++ {
c := iter.buf[i]
if c == '"' {
if !escaped {
return i + 1, false
}
j := i - 1
for {
if j < iter.head || iter.buf[j] != '\\' {
// even number of backslashes
// either end of buffer, or " found
return i + 1, true
}
j--
if j < iter.head || iter.buf[j] != '\\' {
// odd number of backslashes
// it is \" or \\\"
break
}
j--
}
} else if c == '\\' {
escaped = true
}
}
j := iter.tail - 1
for {
if j < iter.head || iter.buf[j] != '\\' {
// even number of backslashes
// either end of buffer, or " found
return -1, false // do not end with \
}
j--
if j < iter.head || iter.buf[j] != '\\' {
// odd number of backslashes
// it is \" or \\\"
break
}
j--
}
return -1, true // end with \
}
================================================
FILE: iter_skip_sloppy_test.go
================================================
//+build jsoniter_sloppy
package jsoniter
import (
"github.com/stretchr/testify/require"
"io"
"testing"
)
func Test_string_end(t *testing.T) {
end, escaped := ParseString(ConfigDefault, `abc"`).findStringEnd()
if end != 4 {
t.Fatal(end)
}
if escaped != false {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `abc\\"`).findStringEnd()
if end != 6 {
t.Fatal(end)
}
if escaped != true {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `abc\\\\"`).findStringEnd()
if end != 8 {
t.Fatal(end)
}
if escaped != true {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `abc\"`).findStringEnd()
if end != -1 {
t.Fatal(end)
}
if escaped != false {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `abc\`).findStringEnd()
if end != -1 {
t.Fatal(end)
}
if escaped != true {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `abc\\`).findStringEnd()
if end != -1 {
t.Fatal(end)
}
if escaped != false {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `\\`).findStringEnd()
if end != -1 {
t.Fatal(end)
}
if escaped != false {
t.Fatal(escaped)
}
end, escaped = ParseString(ConfigDefault, `\`).findStringEnd()
if end != -1 {
t.Fatal(end)
}
if escaped != true {
t.Fatal(escaped)
}
}
type StagedReader struct {
r1 string
r2 string
r3 string
r int
}
func (reader *StagedReader) Read(p []byte) (n int, err error) {
reader.r++
switch reader.r {
case 1:
copy(p, []byte(reader.r1))
return len(reader.r1), nil
case 2:
copy(p, []byte(reader.r2))
return len(reader.r2), nil
case 3:
copy(p, []byte(reader.r3))
return len(reader.r3), nil
default:
return 0, io.EOF
}
}
func Test_skip_string(t *testing.T) {
should := require.New(t)
iter := ParseString(ConfigDefault, `"abc`)
iter.skipString()
should.Equal(1, iter.head)
iter = ParseString(ConfigDefault, `\""abc`)
iter.skipString()
should.Equal(3, iter.head)
reader := &StagedReader{
r1: `abc`,
r2: `"`,
}
iter = Parse(ConfigDefault, reader, 4096)
iter.skipString()
should.Equal(1, iter.head)
reader = &StagedReader{
r1: `abc`,
r2: `1"`,
}
iter = Parse(ConfigDefault, reader, 4096)
iter.skipString()
should.Equal(2, iter.head)
reader = &StagedReader{
r1: `abc\`,
r2: `"`,
}
iter = Parse(ConfigDefault, reader, 4096)
iter.skipString()
should.NotNil(iter.Error)
reader = &StagedReader{
r1: `abc\`,
r2: `""`,
}
iter = Parse(ConfigDefault, reader, 4096)
iter.skipString()
should.Equal(2, iter.head)
}
func Test_skip_object(t *testing.T) {
iter := ParseString(ConfigDefault, `}`)
iter.skipObject()
if iter.head != 1 {
t.Fatal(iter.head)
}
iter = ParseString(ConfigDefault, `a}`)
iter.skipObject()
if iter.head != 2 {
t.Fatal(iter.head)
}
iter = ParseString(ConfigDefault, `{}}a`)
iter.skipObject()
if iter.head != 3 {
t.Fatal(iter.head)
}
reader := &StagedReader{
r1: `{`,
r2: `}}a`,
}
iter = Parse(ConfigDefault, reader, 4096)
iter.skipObject()
if iter.head != 2 {
t.Fatal(iter.head)
}
iter = ParseString(ConfigDefault, `"}"}a`)
iter.skipObject()
if iter.head != 4 {
t.Fatal(iter.head)
}
}
================================================
FILE: iter_skip_strict.go
================================================
//+build !jsoniter_sloppy
package jsoniter
import (
"fmt"
"io"
)
func (iter *Iterator) skipNumber() {
if !iter.trySkipNumber() {
iter.unreadByte()
if iter.Error != nil && iter.Error != io.EOF {
return
}
iter.ReadFloat64()
gitextract_ugnavu_c/
├── .codecov.yml
├── .gitignore
├── .travis.yml
├── Gopkg.toml
├── LICENSE
├── README.md
├── adapter.go
├── any.go
├── any_array.go
├── any_bool.go
├── any_float.go
├── any_int32.go
├── any_int64.go
├── any_invalid.go
├── any_nil.go
├── any_number.go
├── any_object.go
├── any_str.go
├── any_tests/
│ ├── jsoniter_any_array_test.go
│ ├── jsoniter_any_bool_test.go
│ ├── jsoniter_any_float_test.go
│ ├── jsoniter_any_int_test.go
│ ├── jsoniter_any_map_test.go
│ ├── jsoniter_any_null_test.go
│ ├── jsoniter_any_object_test.go
│ ├── jsoniter_any_string_test.go
│ ├── jsoniter_must_be_valid_test.go
│ └── jsoniter_wrap_test.go
├── any_uint32.go
├── any_uint64.go
├── api_tests/
│ ├── config_test.go
│ ├── decoder_test.go
│ ├── encoder_18_test.go
│ ├── encoder_test.go
│ ├── marshal_indent_test.go
│ ├── marshal_json_escape_test.go
│ └── marshal_json_test.go
├── benchmarks/
│ ├── encode_string_test.go
│ ├── jsoniter_large_file_test.go
│ └── stream_test.go
├── build.sh
├── config.go
├── example_test.go
├── extension_tests/
│ ├── decoder_test.go
│ └── extension_test.go
├── extra/
│ ├── binary_as_string_codec.go
│ ├── binary_as_string_codec_test.go
│ ├── fuzzy_decoder.go
│ ├── fuzzy_decoder_test.go
│ ├── naming_strategy.go
│ ├── naming_strategy_test.go
│ ├── privat_fields.go
│ ├── private_fields_test.go
│ ├── time_as_int64_codec.go
│ └── time_as_int64_codec_test.go
├── fuzzy_mode_convert_table.md
├── go.mod
├── go.sum
├── iter.go
├── iter_array.go
├── iter_float.go
├── iter_int.go
├── iter_object.go
├── iter_skip.go
├── iter_skip_sloppy.go
├── iter_skip_sloppy_test.go
├── iter_skip_strict.go
├── iter_str.go
├── jsoniter.go
├── misc_tests/
│ ├── jsoniter_array_test.go
│ ├── jsoniter_bool_test.go
│ ├── jsoniter_float_test.go
│ ├── jsoniter_int_test.go
│ ├── jsoniter_interface_test.go
│ ├── jsoniter_iterator_test.go
│ ├── jsoniter_map_test.go
│ ├── jsoniter_nested_test.go
│ ├── jsoniter_null_test.go
│ ├── jsoniter_object_test.go
│ └── jsoniter_raw_message_test.go
├── pool.go
├── reflect.go
├── reflect_array.go
├── reflect_dynamic.go
├── reflect_extension.go
├── reflect_json_number.go
├── reflect_json_raw_message.go
├── reflect_map.go
├── reflect_marshaler.go
├── reflect_native.go
├── reflect_optional.go
├── reflect_slice.go
├── reflect_struct_decoder.go
├── reflect_struct_encoder.go
├── skip_tests/
│ ├── array_test.go
│ ├── float64_test.go
│ ├── jsoniter_skip_test.go
│ ├── skip_test.go
│ ├── string_test.go
│ └── struct_test.go
├── stream.go
├── stream_float.go
├── stream_int.go
├── stream_str.go
├── stream_test.go
├── test.sh
├── type_tests/
│ ├── array_test.go
│ ├── builtin_test.go
│ ├── map_key_test.go
│ ├── map_test.go
│ ├── marshaler_string_test.go
│ ├── marshaler_struct_test.go
│ ├── slice_test.go
│ ├── struct_embedded_test.go
│ ├── struct_field_case_test.go
│ ├── struct_tags_test.go
│ ├── struct_test.go
│ ├── text_marshaler_string_test.go
│ ├── text_marshaler_struct_test.go
│ └── type_test.go
└── value_tests/
├── array_test.go
├── bool_test.go
├── eface_test.go
├── error_test.go
├── float_test.go
├── iface_test.go
├── int_test.go
├── invalid_test.go
├── map_test.go
├── marshaler_test.go
├── number_test.go
├── ptr_114_test.go
├── ptr_test.go
├── raw_message_test.go
├── slice_test.go
├── string_test.go
├── struct_test.go
└── value_test.go
SYMBOL INDEX (1425 symbols across 126 files)
FILE: adapter.go
type RawMessage (line 9) | type RawMessage
function Unmarshal (line 15) | func Unmarshal(data []byte, v interface{}) error {
function UnmarshalFromString (line 20) | func UnmarshalFromString(str string, v interface{}) error {
function Get (line 25) | func Get(data []byte, path ...interface{}) Any {
function Marshal (line 33) | func Marshal(v interface{}) ([]byte, error) {
function MarshalIndent (line 38) | func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
function MarshalToString (line 43) | func MarshalToString(v interface{}) (string, error) {
function NewDecoder (line 53) | func NewDecoder(reader io.Reader) *Decoder {
type Decoder (line 59) | type Decoder struct
method Decode (line 64) | func (adapter *Decoder) Decode(obj interface{}) error {
method More (line 79) | func (adapter *Decoder) More() bool {
method Buffered (line 93) | func (adapter *Decoder) Buffered() io.Reader {
method UseNumber (line 100) | func (adapter *Decoder) UseNumber() {
method DisallowUnknownFields (line 109) | func (adapter *Decoder) DisallowUnknownFields() {
function NewEncoder (line 116) | func NewEncoder(writer io.Writer) *Encoder {
type Encoder (line 121) | type Encoder struct
method Encode (line 126) | func (adapter *Encoder) Encode(val interface{}) error {
method SetIndent (line 134) | func (adapter *Encoder) SetIndent(prefix, indent string) {
method SetEscapeHTML (line 141) | func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) {
function Valid (line 148) | func Valid(data []byte) bool {
FILE: any.go
type Any (line 15) | type Any interface
type baseAny (line 37) | type baseAny struct
method Get (line 39) | func (any *baseAny) Get(path ...interface{}) Any {
method Size (line 43) | func (any *baseAny) Size() int {
method Keys (line 47) | func (any *baseAny) Keys() []string {
method ToVal (line 51) | func (any *baseAny) ToVal(obj interface{}) {
function WrapInt32 (line 56) | func WrapInt32(val int32) Any {
function WrapInt64 (line 61) | func WrapInt64(val int64) Any {
function WrapUint32 (line 66) | func WrapUint32(val uint32) Any {
function WrapUint64 (line 71) | func WrapUint64(val uint64) Any {
function WrapFloat64 (line 76) | func WrapFloat64(val float64) Any {
function WrapString (line 81) | func WrapString(val string) Any {
function Wrap (line 86) | func Wrap(val interface{}) Any {
method ReadAny (line 149) | func (iter *Iterator) ReadAny() Any {
method readAny (line 153) | func (iter *Iterator) readAny() Any {
method readNumberAny (line 181) | func (iter *Iterator) readNumberAny(positive bool) Any {
method readObjectAny (line 188) | func (iter *Iterator) readObjectAny() Any {
method readArrayAny (line 195) | func (iter *Iterator) readArrayAny() Any {
function locateObjectField (line 202) | func locateObjectField(iter *Iterator, target string) []byte {
function locateArrayElement (line 215) | func locateArrayElement(iter *Iterator, target int) []byte {
function locatePath (line 230) | func locatePath(iter *Iterator, path []interface{}) Any {
function createDecoderOfAny (line 262) | func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder {
function createEncoderOfAny (line 274) | func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder {
type anyCodec (line 286) | type anyCodec struct
method Decode (line 290) | func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 294) | func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 300) | func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
type directAnyCodec (line 306) | type directAnyCodec struct
method Decode (line 309) | func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 313) | func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 322) | func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool {
FILE: any_array.go
type arrayLazyAny (line 8) | type arrayLazyAny struct
method ValueType (line 15) | func (any *arrayLazyAny) ValueType() ValueType {
method MustBeValid (line 19) | func (any *arrayLazyAny) MustBeValid() Any {
method LastError (line 23) | func (any *arrayLazyAny) LastError() error {
method ToBool (line 27) | func (any *arrayLazyAny) ToBool() bool {
method ToInt (line 33) | func (any *arrayLazyAny) ToInt() int {
method ToInt32 (line 40) | func (any *arrayLazyAny) ToInt32() int32 {
method ToInt64 (line 47) | func (any *arrayLazyAny) ToInt64() int64 {
method ToUint (line 54) | func (any *arrayLazyAny) ToUint() uint {
method ToUint32 (line 61) | func (any *arrayLazyAny) ToUint32() uint32 {
method ToUint64 (line 68) | func (any *arrayLazyAny) ToUint64() uint64 {
method ToFloat32 (line 75) | func (any *arrayLazyAny) ToFloat32() float32 {
method ToFloat64 (line 82) | func (any *arrayLazyAny) ToFloat64() float64 {
method ToString (line 89) | func (any *arrayLazyAny) ToString() string {
method ToVal (line 93) | func (any *arrayLazyAny) ToVal(val interface{}) {
method Get (line 99) | func (any *arrayLazyAny) Get(path ...interface{}) Any {
method Size (line 133) | func (any *arrayLazyAny) Size() int {
method WriteTo (line 145) | func (any *arrayLazyAny) WriteTo(stream *Stream) {
method GetInterface (line 149) | func (any *arrayLazyAny) GetInterface() interface{} {
type arrayAny (line 155) | type arrayAny struct
method ValueType (line 164) | func (any *arrayAny) ValueType() ValueType {
method MustBeValid (line 168) | func (any *arrayAny) MustBeValid() Any {
method LastError (line 172) | func (any *arrayAny) LastError() error {
method ToBool (line 176) | func (any *arrayAny) ToBool() bool {
method ToInt (line 180) | func (any *arrayAny) ToInt() int {
method ToInt32 (line 187) | func (any *arrayAny) ToInt32() int32 {
method ToInt64 (line 194) | func (any *arrayAny) ToInt64() int64 {
method ToUint (line 201) | func (any *arrayAny) ToUint() uint {
method ToUint32 (line 208) | func (any *arrayAny) ToUint32() uint32 {
method ToUint64 (line 215) | func (any *arrayAny) ToUint64() uint64 {
method ToFloat32 (line 222) | func (any *arrayAny) ToFloat32() float32 {
method ToFloat64 (line 229) | func (any *arrayAny) ToFloat64() float64 {
method ToString (line 236) | func (any *arrayAny) ToString() string {
method Get (line 241) | func (any *arrayAny) Get(path ...interface{}) Any {
method Size (line 268) | func (any *arrayAny) Size() int {
method WriteTo (line 272) | func (any *arrayAny) WriteTo(stream *Stream) {
method GetInterface (line 276) | func (any *arrayAny) GetInterface() interface{} {
function wrapArray (line 160) | func wrapArray(val interface{}) *arrayAny {
FILE: any_bool.go
type trueAny (line 3) | type trueAny struct
method LastError (line 7) | func (any *trueAny) LastError() error {
method ToBool (line 11) | func (any *trueAny) ToBool() bool {
method ToInt (line 15) | func (any *trueAny) ToInt() int {
method ToInt32 (line 19) | func (any *trueAny) ToInt32() int32 {
method ToInt64 (line 23) | func (any *trueAny) ToInt64() int64 {
method ToUint (line 27) | func (any *trueAny) ToUint() uint {
method ToUint32 (line 31) | func (any *trueAny) ToUint32() uint32 {
method ToUint64 (line 35) | func (any *trueAny) ToUint64() uint64 {
method ToFloat32 (line 39) | func (any *trueAny) ToFloat32() float32 {
method ToFloat64 (line 43) | func (any *trueAny) ToFloat64() float64 {
method ToString (line 47) | func (any *trueAny) ToString() string {
method WriteTo (line 51) | func (any *trueAny) WriteTo(stream *Stream) {
method Parse (line 55) | func (any *trueAny) Parse() *Iterator {
method GetInterface (line 59) | func (any *trueAny) GetInterface() interface{} {
method ValueType (line 63) | func (any *trueAny) ValueType() ValueType {
method MustBeValid (line 67) | func (any *trueAny) MustBeValid() Any {
type falseAny (line 71) | type falseAny struct
method LastError (line 75) | func (any *falseAny) LastError() error {
method ToBool (line 79) | func (any *falseAny) ToBool() bool {
method ToInt (line 83) | func (any *falseAny) ToInt() int {
method ToInt32 (line 87) | func (any *falseAny) ToInt32() int32 {
method ToInt64 (line 91) | func (any *falseAny) ToInt64() int64 {
method ToUint (line 95) | func (any *falseAny) ToUint() uint {
method ToUint32 (line 99) | func (any *falseAny) ToUint32() uint32 {
method ToUint64 (line 103) | func (any *falseAny) ToUint64() uint64 {
method ToFloat32 (line 107) | func (any *falseAny) ToFloat32() float32 {
method ToFloat64 (line 111) | func (any *falseAny) ToFloat64() float64 {
method ToString (line 115) | func (any *falseAny) ToString() string {
method WriteTo (line 119) | func (any *falseAny) WriteTo(stream *Stream) {
method Parse (line 123) | func (any *falseAny) Parse() *Iterator {
method GetInterface (line 127) | func (any *falseAny) GetInterface() interface{} {
method ValueType (line 131) | func (any *falseAny) ValueType() ValueType {
method MustBeValid (line 135) | func (any *falseAny) MustBeValid() Any {
FILE: any_float.go
type floatAny (line 7) | type floatAny struct
method Parse (line 12) | func (any *floatAny) Parse() *Iterator {
method ValueType (line 16) | func (any *floatAny) ValueType() ValueType {
method MustBeValid (line 20) | func (any *floatAny) MustBeValid() Any {
method LastError (line 24) | func (any *floatAny) LastError() error {
method ToBool (line 28) | func (any *floatAny) ToBool() bool {
method ToInt (line 32) | func (any *floatAny) ToInt() int {
method ToInt32 (line 36) | func (any *floatAny) ToInt32() int32 {
method ToInt64 (line 40) | func (any *floatAny) ToInt64() int64 {
method ToUint (line 44) | func (any *floatAny) ToUint() uint {
method ToUint32 (line 51) | func (any *floatAny) ToUint32() uint32 {
method ToUint64 (line 58) | func (any *floatAny) ToUint64() uint64 {
method ToFloat32 (line 65) | func (any *floatAny) ToFloat32() float32 {
method ToFloat64 (line 69) | func (any *floatAny) ToFloat64() float64 {
method ToString (line 73) | func (any *floatAny) ToString() string {
method WriteTo (line 77) | func (any *floatAny) WriteTo(stream *Stream) {
method GetInterface (line 81) | func (any *floatAny) GetInterface() interface{} {
FILE: any_int32.go
type int32Any (line 7) | type int32Any struct
method LastError (line 12) | func (any *int32Any) LastError() error {
method ValueType (line 16) | func (any *int32Any) ValueType() ValueType {
method MustBeValid (line 20) | func (any *int32Any) MustBeValid() Any {
method ToBool (line 24) | func (any *int32Any) ToBool() bool {
method ToInt (line 28) | func (any *int32Any) ToInt() int {
method ToInt32 (line 32) | func (any *int32Any) ToInt32() int32 {
method ToInt64 (line 36) | func (any *int32Any) ToInt64() int64 {
method ToUint (line 40) | func (any *int32Any) ToUint() uint {
method ToUint32 (line 44) | func (any *int32Any) ToUint32() uint32 {
method ToUint64 (line 48) | func (any *int32Any) ToUint64() uint64 {
method ToFloat32 (line 52) | func (any *int32Any) ToFloat32() float32 {
method ToFloat64 (line 56) | func (any *int32Any) ToFloat64() float64 {
method ToString (line 60) | func (any *int32Any) ToString() string {
method WriteTo (line 64) | func (any *int32Any) WriteTo(stream *Stream) {
method Parse (line 68) | func (any *int32Any) Parse() *Iterator {
method GetInterface (line 72) | func (any *int32Any) GetInterface() interface{} {
FILE: any_int64.go
type int64Any (line 7) | type int64Any struct
method LastError (line 12) | func (any *int64Any) LastError() error {
method ValueType (line 16) | func (any *int64Any) ValueType() ValueType {
method MustBeValid (line 20) | func (any *int64Any) MustBeValid() Any {
method ToBool (line 24) | func (any *int64Any) ToBool() bool {
method ToInt (line 28) | func (any *int64Any) ToInt() int {
method ToInt32 (line 32) | func (any *int64Any) ToInt32() int32 {
method ToInt64 (line 36) | func (any *int64Any) ToInt64() int64 {
method ToUint (line 40) | func (any *int64Any) ToUint() uint {
method ToUint32 (line 44) | func (any *int64Any) ToUint32() uint32 {
method ToUint64 (line 48) | func (any *int64Any) ToUint64() uint64 {
method ToFloat32 (line 52) | func (any *int64Any) ToFloat32() float32 {
method ToFloat64 (line 56) | func (any *int64Any) ToFloat64() float64 {
method ToString (line 60) | func (any *int64Any) ToString() string {
method WriteTo (line 64) | func (any *int64Any) WriteTo(stream *Stream) {
method Parse (line 68) | func (any *int64Any) Parse() *Iterator {
method GetInterface (line 72) | func (any *int64Any) GetInterface() interface{} {
FILE: any_invalid.go
type invalidAny (line 5) | type invalidAny struct
method LastError (line 14) | func (any *invalidAny) LastError() error {
method ValueType (line 18) | func (any *invalidAny) ValueType() ValueType {
method MustBeValid (line 22) | func (any *invalidAny) MustBeValid() Any {
method ToBool (line 26) | func (any *invalidAny) ToBool() bool {
method ToInt (line 30) | func (any *invalidAny) ToInt() int {
method ToInt32 (line 34) | func (any *invalidAny) ToInt32() int32 {
method ToInt64 (line 38) | func (any *invalidAny) ToInt64() int64 {
method ToUint (line 42) | func (any *invalidAny) ToUint() uint {
method ToUint32 (line 46) | func (any *invalidAny) ToUint32() uint32 {
method ToUint64 (line 50) | func (any *invalidAny) ToUint64() uint64 {
method ToFloat32 (line 54) | func (any *invalidAny) ToFloat32() float32 {
method ToFloat64 (line 58) | func (any *invalidAny) ToFloat64() float64 {
method ToString (line 62) | func (any *invalidAny) ToString() string {
method WriteTo (line 66) | func (any *invalidAny) WriteTo(stream *Stream) {
method Get (line 69) | func (any *invalidAny) Get(path ...interface{}) Any {
method Parse (line 76) | func (any *invalidAny) Parse() *Iterator {
method GetInterface (line 80) | func (any *invalidAny) GetInterface() interface{} {
function newInvalidAny (line 10) | func newInvalidAny(path []interface{}) *invalidAny {
FILE: any_nil.go
type nilAny (line 3) | type nilAny struct
method LastError (line 7) | func (any *nilAny) LastError() error {
method ValueType (line 11) | func (any *nilAny) ValueType() ValueType {
method MustBeValid (line 15) | func (any *nilAny) MustBeValid() Any {
method ToBool (line 19) | func (any *nilAny) ToBool() bool {
method ToInt (line 23) | func (any *nilAny) ToInt() int {
method ToInt32 (line 27) | func (any *nilAny) ToInt32() int32 {
method ToInt64 (line 31) | func (any *nilAny) ToInt64() int64 {
method ToUint (line 35) | func (any *nilAny) ToUint() uint {
method ToUint32 (line 39) | func (any *nilAny) ToUint32() uint32 {
method ToUint64 (line 43) | func (any *nilAny) ToUint64() uint64 {
method ToFloat32 (line 47) | func (any *nilAny) ToFloat32() float32 {
method ToFloat64 (line 51) | func (any *nilAny) ToFloat64() float64 {
method ToString (line 55) | func (any *nilAny) ToString() string {
method WriteTo (line 59) | func (any *nilAny) WriteTo(stream *Stream) {
method Parse (line 63) | func (any *nilAny) Parse() *Iterator {
method GetInterface (line 67) | func (any *nilAny) GetInterface() interface{} {
FILE: any_number.go
type numberLazyAny (line 8) | type numberLazyAny struct
method ValueType (line 15) | func (any *numberLazyAny) ValueType() ValueType {
method MustBeValid (line 19) | func (any *numberLazyAny) MustBeValid() Any {
method LastError (line 23) | func (any *numberLazyAny) LastError() error {
method ToBool (line 27) | func (any *numberLazyAny) ToBool() bool {
method ToInt (line 31) | func (any *numberLazyAny) ToInt() int {
method ToInt32 (line 41) | func (any *numberLazyAny) ToInt32() int32 {
method ToInt64 (line 51) | func (any *numberLazyAny) ToInt64() int64 {
method ToUint (line 61) | func (any *numberLazyAny) ToUint() uint {
method ToUint32 (line 71) | func (any *numberLazyAny) ToUint32() uint32 {
method ToUint64 (line 81) | func (any *numberLazyAny) ToUint64() uint64 {
method ToFloat32 (line 91) | func (any *numberLazyAny) ToFloat32() float32 {
method ToFloat64 (line 101) | func (any *numberLazyAny) ToFloat64() float64 {
method ToString (line 111) | func (any *numberLazyAny) ToString() string {
method WriteTo (line 115) | func (any *numberLazyAny) WriteTo(stream *Stream) {
method GetInterface (line 119) | func (any *numberLazyAny) GetInterface() interface{} {
FILE: any_object.go
type objectLazyAny (line 8) | type objectLazyAny struct
method ValueType (line 15) | func (any *objectLazyAny) ValueType() ValueType {
method MustBeValid (line 19) | func (any *objectLazyAny) MustBeValid() Any {
method LastError (line 23) | func (any *objectLazyAny) LastError() error {
method ToBool (line 27) | func (any *objectLazyAny) ToBool() bool {
method ToInt (line 31) | func (any *objectLazyAny) ToInt() int {
method ToInt32 (line 35) | func (any *objectLazyAny) ToInt32() int32 {
method ToInt64 (line 39) | func (any *objectLazyAny) ToInt64() int64 {
method ToUint (line 43) | func (any *objectLazyAny) ToUint() uint {
method ToUint32 (line 47) | func (any *objectLazyAny) ToUint32() uint32 {
method ToUint64 (line 51) | func (any *objectLazyAny) ToUint64() uint64 {
method ToFloat32 (line 55) | func (any *objectLazyAny) ToFloat32() float32 {
method ToFloat64 (line 59) | func (any *objectLazyAny) ToFloat64() float64 {
method ToString (line 63) | func (any *objectLazyAny) ToString() string {
method ToVal (line 67) | func (any *objectLazyAny) ToVal(obj interface{}) {
method Get (line 73) | func (any *objectLazyAny) Get(path ...interface{}) Any {
method Keys (line 107) | func (any *objectLazyAny) Keys() []string {
method Size (line 119) | func (any *objectLazyAny) Size() int {
method WriteTo (line 131) | func (any *objectLazyAny) WriteTo(stream *Stream) {
method GetInterface (line 135) | func (any *objectLazyAny) GetInterface() interface{} {
type objectAny (line 141) | type objectAny struct
method ValueType (line 151) | func (any *objectAny) ValueType() ValueType {
method MustBeValid (line 155) | func (any *objectAny) MustBeValid() Any {
method Parse (line 159) | func (any *objectAny) Parse() *Iterator {
method LastError (line 163) | func (any *objectAny) LastError() error {
method ToBool (line 167) | func (any *objectAny) ToBool() bool {
method ToInt (line 171) | func (any *objectAny) ToInt() int {
method ToInt32 (line 175) | func (any *objectAny) ToInt32() int32 {
method ToInt64 (line 179) | func (any *objectAny) ToInt64() int64 {
method ToUint (line 183) | func (any *objectAny) ToUint() uint {
method ToUint32 (line 187) | func (any *objectAny) ToUint32() uint32 {
method ToUint64 (line 191) | func (any *objectAny) ToUint64() uint64 {
method ToFloat32 (line 195) | func (any *objectAny) ToFloat32() float32 {
method ToFloat64 (line 199) | func (any *objectAny) ToFloat64() float64 {
method ToString (line 203) | func (any *objectAny) ToString() string {
method Get (line 209) | func (any *objectAny) Get(path ...interface{}) Any {
method Keys (line 240) | func (any *objectAny) Keys() []string {
method Size (line 248) | func (any *objectAny) Size() int {
method WriteTo (line 252) | func (any *objectAny) WriteTo(stream *Stream) {
method GetInterface (line 256) | func (any *objectAny) GetInterface() interface{} {
function wrapStruct (line 147) | func wrapStruct(val interface{}) *objectAny {
type mapAny (line 260) | type mapAny struct
method ValueType (line 270) | func (any *mapAny) ValueType() ValueType {
method MustBeValid (line 274) | func (any *mapAny) MustBeValid() Any {
method Parse (line 278) | func (any *mapAny) Parse() *Iterator {
method LastError (line 282) | func (any *mapAny) LastError() error {
method ToBool (line 286) | func (any *mapAny) ToBool() bool {
method ToInt (line 290) | func (any *mapAny) ToInt() int {
method ToInt32 (line 294) | func (any *mapAny) ToInt32() int32 {
method ToInt64 (line 298) | func (any *mapAny) ToInt64() int64 {
method ToUint (line 302) | func (any *mapAny) ToUint() uint {
method ToUint32 (line 306) | func (any *mapAny) ToUint32() uint32 {
method ToUint64 (line 310) | func (any *mapAny) ToUint64() uint64 {
method ToFloat32 (line 314) | func (any *mapAny) ToFloat32() float32 {
method ToFloat64 (line 318) | func (any *mapAny) ToFloat64() float64 {
method ToString (line 322) | func (any *mapAny) ToString() string {
method Get (line 328) | func (any *mapAny) Get(path ...interface{}) Any {
method Keys (line 356) | func (any *mapAny) Keys() []string {
method Size (line 364) | func (any *mapAny) Size() int {
method WriteTo (line 368) | func (any *mapAny) WriteTo(stream *Stream) {
method GetInterface (line 372) | func (any *mapAny) GetInterface() interface{} {
function wrapMap (line 266) | func wrapMap(val interface{}) *mapAny {
FILE: any_str.go
type stringAny (line 8) | type stringAny struct
method Get (line 13) | func (any *stringAny) Get(path ...interface{}) Any {
method Parse (line 20) | func (any *stringAny) Parse() *Iterator {
method ValueType (line 24) | func (any *stringAny) ValueType() ValueType {
method MustBeValid (line 28) | func (any *stringAny) MustBeValid() Any {
method LastError (line 32) | func (any *stringAny) LastError() error {
method ToBool (line 36) | func (any *stringAny) ToBool() bool {
method ToInt (line 51) | func (any *stringAny) ToInt() int {
method ToInt32 (line 56) | func (any *stringAny) ToInt32() int32 {
method ToInt64 (line 60) | func (any *stringAny) ToInt64() int64 {
method ToUint (line 87) | func (any *stringAny) ToUint() uint {
method ToUint32 (line 91) | func (any *stringAny) ToUint32() uint32 {
method ToUint64 (line 95) | func (any *stringAny) ToUint64() uint64 {
method ToFloat32 (line 121) | func (any *stringAny) ToFloat32() float32 {
method ToFloat64 (line 125) | func (any *stringAny) ToFloat64() float64 {
method ToString (line 156) | func (any *stringAny) ToString() string {
method WriteTo (line 160) | func (any *stringAny) WriteTo(stream *Stream) {
method GetInterface (line 164) | func (any *stringAny) GetInterface() interface{} {
FILE: any_tests/jsoniter_any_array_test.go
function Test_read_empty_array_as_any (line 10) | func Test_read_empty_array_as_any(t *testing.T) {
function Test_read_one_element_array_as_any (line 28) | func Test_read_one_element_array_as_any(t *testing.T) {
function Test_read_two_element_array_as_any (line 34) | func Test_read_two_element_array_as_any(t *testing.T) {
function Test_wrap_array_and_convert_to_any (line 50) | func Test_wrap_array_and_convert_to_any(t *testing.T) {
function Test_array_lazy_any_get (line 82) | func Test_array_lazy_any_get(t *testing.T) {
function Test_array_lazy_any_get_all (line 89) | func Test_array_lazy_any_get_all(t *testing.T) {
function Test_array_wrapper_any_get_all (line 97) | func Test_array_wrapper_any_get_all(t *testing.T) {
function Test_array_lazy_any_get_invalid (line 110) | func Test_array_lazy_any_get_invalid(t *testing.T) {
function Test_invalid_array (line 119) | func Test_invalid_array(t *testing.T) {
FILE: any_tests/jsoniter_any_bool_test.go
function Test_read_bool_as_any (line 36) | func Test_read_bool_as_any(t *testing.T) {
function Test_write_bool_to_stream (line 51) | func Test_write_bool_to_stream(t *testing.T) {
FILE: any_tests/jsoniter_any_float_test.go
function Test_read_any_to_float (line 68) | func Test_read_any_to_float(t *testing.T) {
function Test_read_float_to_any (line 81) | func Test_read_float_to_any(t *testing.T) {
FILE: any_tests/jsoniter_any_int_test.go
function Test_read_any_to_int (line 40) | func Test_read_any_to_int(t *testing.T) {
function Test_read_any_to_uint (line 94) | func Test_read_any_to_uint(t *testing.T) {
function Test_read_int64_to_any (line 114) | func Test_read_int64_to_any(t *testing.T) {
function Test_read_int32_to_any (line 132) | func Test_read_int32_to_any(t *testing.T) {
function Test_read_uint32_to_any (line 151) | func Test_read_uint32_to_any(t *testing.T) {
function Test_read_uint64_to_any (line 170) | func Test_read_uint64_to_any(t *testing.T) {
function Test_int_lazy_any_get (line 192) | func Test_int_lazy_any_get(t *testing.T) {
FILE: any_tests/jsoniter_any_map_test.go
function Test_wrap_map (line 9) | func Test_wrap_map(t *testing.T) {
function Test_map_wrapper_any_get_all (line 17) | func Test_map_wrapper_any_get_all(t *testing.T) {
FILE: any_tests/jsoniter_any_null_test.go
function Test_read_null_as_any (line 9) | func Test_read_null_as_any(t *testing.T) {
FILE: any_tests/jsoniter_any_object_test.go
function Test_read_object_as_any (line 10) | func Test_read_object_as_any(t *testing.T) {
function Test_object_lazy_any_get (line 33) | func Test_object_lazy_any_get(t *testing.T) {
function Test_object_lazy_any_get_all (line 39) | func Test_object_lazy_any_get_all(t *testing.T) {
function Test_object_lazy_any_get_invalid (line 45) | func Test_object_lazy_any_get_invalid(t *testing.T) {
function Test_wrap_map_and_convert_to_any (line 52) | func Test_wrap_map_and_convert_to_any(t *testing.T) {
function Test_wrap_object_and_convert_to_any (line 66) | func Test_wrap_object_and_convert_to_any(t *testing.T) {
function Test_any_within_struct (line 97) | func Test_any_within_struct(t *testing.T) {
function Test_object_wrapper_any_get_all (line 110) | func Test_object_wrapper_any_get_all(t *testing.T) {
FILE: any_tests/jsoniter_any_string_test.go
function Test_read_any_to_string (line 32) | func Test_read_any_to_string(t *testing.T) {
function Test_read_string_as_any (line 40) | func Test_read_string_as_any(t *testing.T) {
function Test_wrap_string (line 53) | func Test_wrap_string(t *testing.T) {
FILE: any_tests/jsoniter_must_be_valid_test.go
function Test_must_be_valid (line 11) | func Test_must_be_valid(t *testing.T) {
FILE: any_tests/jsoniter_wrap_test.go
function Test_wrap_and_valuetype_everything (line 10) | func Test_wrap_and_valuetype_everything(t *testing.T) {
FILE: any_uint32.go
type uint32Any (line 7) | type uint32Any struct
method LastError (line 12) | func (any *uint32Any) LastError() error {
method ValueType (line 16) | func (any *uint32Any) ValueType() ValueType {
method MustBeValid (line 20) | func (any *uint32Any) MustBeValid() Any {
method ToBool (line 24) | func (any *uint32Any) ToBool() bool {
method ToInt (line 28) | func (any *uint32Any) ToInt() int {
method ToInt32 (line 32) | func (any *uint32Any) ToInt32() int32 {
method ToInt64 (line 36) | func (any *uint32Any) ToInt64() int64 {
method ToUint (line 40) | func (any *uint32Any) ToUint() uint {
method ToUint32 (line 44) | func (any *uint32Any) ToUint32() uint32 {
method ToUint64 (line 48) | func (any *uint32Any) ToUint64() uint64 {
method ToFloat32 (line 52) | func (any *uint32Any) ToFloat32() float32 {
method ToFloat64 (line 56) | func (any *uint32Any) ToFloat64() float64 {
method ToString (line 60) | func (any *uint32Any) ToString() string {
method WriteTo (line 64) | func (any *uint32Any) WriteTo(stream *Stream) {
method Parse (line 68) | func (any *uint32Any) Parse() *Iterator {
method GetInterface (line 72) | func (any *uint32Any) GetInterface() interface{} {
FILE: any_uint64.go
type uint64Any (line 7) | type uint64Any struct
method LastError (line 12) | func (any *uint64Any) LastError() error {
method ValueType (line 16) | func (any *uint64Any) ValueType() ValueType {
method MustBeValid (line 20) | func (any *uint64Any) MustBeValid() Any {
method ToBool (line 24) | func (any *uint64Any) ToBool() bool {
method ToInt (line 28) | func (any *uint64Any) ToInt() int {
method ToInt32 (line 32) | func (any *uint64Any) ToInt32() int32 {
method ToInt64 (line 36) | func (any *uint64Any) ToInt64() int64 {
method ToUint (line 40) | func (any *uint64Any) ToUint() uint {
method ToUint32 (line 44) | func (any *uint64Any) ToUint32() uint32 {
method ToUint64 (line 48) | func (any *uint64Any) ToUint64() uint64 {
method ToFloat32 (line 52) | func (any *uint64Any) ToFloat32() float32 {
method ToFloat64 (line 56) | func (any *uint64Any) ToFloat64() float64 {
method ToString (line 60) | func (any *uint64Any) ToString() string {
method WriteTo (line 64) | func (any *uint64Any) WriteTo(stream *Stream) {
method Parse (line 68) | func (any *uint64Any) Parse() *Iterator {
method GetInterface (line 72) | func (any *uint64Any) GetInterface() interface{} {
FILE: api_tests/config_test.go
function Test_use_number_for_unmarshal (line 11) | func Test_use_number_for_unmarshal(t *testing.T) {
function Test_customize_float_marshal (line 19) | func Test_customize_float_marshal(t *testing.T) {
function Test_customize_tag_key (line 27) | func Test_customize_tag_key(t *testing.T) {
function Test_read_large_number_as_interface (line 40) | func Test_read_large_number_as_interface(t *testing.T) {
type caseSensitiveStruct (line 50) | type caseSensitiveStruct struct
type C (line 56) | type C struct
type E (line 61) | type E struct
function Test_CaseSensitive (line 65) | func Test_CaseSensitive(t *testing.T) {
type structWithElevenFields (line 126) | type structWithElevenFields struct
function Test_CaseSensitive_MoreThanTenFields (line 140) | func Test_CaseSensitive_MoreThanTenFields(t *testing.T) {
type onlyTaggedFieldStruct (line 176) | type onlyTaggedFieldStruct struct
type F (line 187) | type F struct
type I (line 192) | type I struct
function Test_OnlyTaggedField (line 197) | func Test_OnlyTaggedField(t *testing.T) {
FILE: api_tests/decoder_test.go
function Test_disallowUnknownFields (line 12) | func Test_disallowUnknownFields(t *testing.T) {
function Test_new_decoder (line 21) | func Test_new_decoder(t *testing.T) {
function Test_use_number (line 46) | func Test_use_number(t *testing.T) {
function Test_decoder_more (line 60) | func Test_decoder_more(t *testing.T) {
FILE: api_tests/encoder_18_test.go
function Test_new_encoder (line 15) | func Test_new_encoder(t *testing.T) {
function Test_string_encode_with_std_without_html_escape (line 29) | func Test_string_encode_with_std_without_html_escape(t *testing.T) {
FILE: api_tests/encoder_test.go
function TestEncoderHasTrailingNewline (line 12) | func TestEncoderHasTrailingNewline(t *testing.T) {
FILE: api_tests/marshal_indent_test.go
function Test_marshal_indent (line 10) | func Test_marshal_indent(t *testing.T) {
function Test_marshal_indent_map (line 24) | func Test_marshal_indent_map(t *testing.T) {
FILE: api_tests/marshal_json_escape_test.go
type Container (line 18) | type Container struct
method MarshalJSON (line 22) | func (c *Container) MarshalJSON() ([]byte, error) {
function TestEncodeEscape (line 26) | func TestEncodeEscape(t *testing.T) {
FILE: api_tests/marshal_json_test.go
type Foo (line 12) | type Foo struct
method MarshalJSON (line 16) | func (f Foo) MarshalJSON() ([]byte, error) {
function TestEncodeMarshalJSON (line 24) | func TestEncodeMarshalJSON(t *testing.T) {
FILE: benchmarks/encode_string_test.go
function Benchmark_encode_string_with_SetEscapeHTML (line 9) | func Benchmark_encode_string_with_SetEscapeHTML(b *testing.B) {
FILE: benchmarks/jsoniter_large_file_test.go
function init (line 27) | func init() {
function Benchmark_jsoniter_large_file (line 127) | func Benchmark_jsoniter_large_file(b *testing.B) {
function Benchmark_json_large_file (line 146) | func Benchmark_json_large_file(b *testing.B) {
FILE: benchmarks/stream_test.go
function Benchmark_stream_encode_big_object (line 11) | func Benchmark_stream_encode_big_object(b *testing.B) {
function TestEncodeObject (line 24) | func TestEncodeObject(t *testing.T) {
function encodeObject (line 38) | func encodeObject(stream *jsoniter.Stream) {
type field (line 103) | type field struct
FILE: config.go
type Config (line 16) | type Config struct
method Froze (line 129) | func (cfg Config) Froze() API {
method frozeWithCacheReuse (line 169) | func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *fr...
type API (line 32) | type API interface
type frozenConfig (line 68) | type frozenConfig struct
method initCache (line 85) | func (cfg *frozenConfig) initCache() {
method addDecoderToCache (line 90) | func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder V...
method addEncoderToCache (line 94) | func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder V...
method getDecoderFromCache (line 98) | func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDeco...
method getEncoderFromCache (line 106) | func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEnco...
method validateJsonRawMessage (line 182) | func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExten...
method useNumber (line 200) | func (cfg *frozenConfig) useNumber(extension DecoderExtension) {
method getTagKey (line 214) | func (cfg *frozenConfig) getTagKey() string {
method RegisterExtension (line 222) | func (cfg *frozenConfig) RegisterExtension(extension Extension) {
method marshalFloatWith6Digits (line 252) | func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExte...
method escapeHTML (line 270) | func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) {
method cleanDecoders (line 274) | func (cfg *frozenConfig) cleanDecoders() {
method cleanEncoders (line 280) | func (cfg *frozenConfig) cleanEncoders() {
method MarshalToString (line 286) | func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
method Marshal (line 296) | func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
method MarshalIndent (line 309) | func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent s...
method UnmarshalFromString (line 323) | func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}...
method Get (line 339) | func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
method Unmarshal (line 345) | func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
method NewEncoder (line 360) | func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
method NewDecoder (line 365) | func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
method Valid (line 370) | func (cfg *frozenConfig) Valid(data []byte) bool {
function getFrozenConfigFromCache (line 116) | func getFrozenConfigFromCache(cfg Config) *frozenConfig {
function addFrozenConfigToCache (line 124) | func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) {
type lossyFloat32Encoder (line 228) | type lossyFloat32Encoder struct
method Encode (line 231) | func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream ...
method IsEmpty (line 235) | func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
type lossyFloat64Encoder (line 239) | type lossyFloat64Encoder struct
method Encode (line 242) | func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream ...
method IsEmpty (line 246) | func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
type htmlEscapedStringEncoder (line 258) | type htmlEscapedStringEncoder struct
method Encode (line 261) | func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, st...
method IsEmpty (line 266) | func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) b...
FILE: example_test.go
function ExampleMarshal (line 9) | func ExampleMarshal() {
function ExampleUnmarshal (line 29) | func ExampleUnmarshal() {
function ExampleConfigFastest_Marshal (line 48) | func ExampleConfigFastest_Marshal() {
function ExampleConfigFastest_Unmarshal (line 70) | func ExampleConfigFastest_Unmarshal() {
function ExampleGet (line 91) | func ExampleGet() {
function ExampleMyKey (line 98) | func ExampleMyKey() {
type MyKey (line 112) | type MyKey
method MarshalText (line 114) | func (m *MyKey) MarshalText() ([]byte, error) {
method UnmarshalText (line 118) | func (m *MyKey) UnmarshalText(text []byte) error {
FILE: extension_tests/decoder_test.go
function Test_customize_type_decoder (line 14) | func Test_customize_type_decoder(t *testing.T) {
function Test_customize_byte_array_encoder (line 36) | func Test_customize_byte_array_encoder(t *testing.T) {
type CustomEncoderAttachmentTestStruct (line 51) | type CustomEncoderAttachmentTestStruct struct
type CustomEncoderAttachmentTestStructEncoder (line 55) | type CustomEncoderAttachmentTestStructEncoder struct
method Encode (line 57) | func (c *CustomEncoderAttachmentTestStructEncoder) Encode(ptr unsafe.P...
method IsEmpty (line 64) | func (c *CustomEncoderAttachmentTestStructEncoder) IsEmpty(ptr unsafe....
function Test_custom_encoder_attachment (line 68) | func Test_custom_encoder_attachment(t *testing.T) {
function Test_customize_field_decoder (line 83) | func Test_customize_field_decoder(t *testing.T) {
function Test_recursive_empty_interface_customization (line 98) | func Test_recursive_empty_interface_customization(t *testing.T) {
type MyInterface (line 114) | type MyInterface interface
type MyString (line 118) | type MyString
method Hello (line 120) | func (ms MyString) Hello() string {
function Test_read_custom_interface (line 124) | func Test_read_custom_interface(t *testing.T) {
constant flow1 (line 136) | flow1 = `
constant flow2 (line 143) | flow2 = `
type Type1 (line 152) | type Type1 struct
type Type2 (line 156) | type Type2 struct
method UnmarshalJSON (line 161) | func (t *Type2) UnmarshalJSON(data []byte) error {
method MarshalJSON (line 165) | func (t *Type2) MarshalJSON() ([]byte, error) {
function TestType1NoFinalLF (line 169) | func TestType1NoFinalLF(t *testing.T) {
function TestType1FinalLF (line 183) | func TestType1FinalLF(t *testing.T) {
function TestType2NoFinalLF (line 197) | func TestType2NoFinalLF(t *testing.T) {
function TestType2FinalLF (line 211) | func TestType2FinalLF(t *testing.T) {
FILE: extension_tests/extension_test.go
type TestObject1 (line 13) | type TestObject1 struct
type testExtension (line 17) | type testExtension struct
method UpdateStructDescriptor (line 21) | func (extension *testExtension) UpdateStructDescriptor(structDescripto...
function Test_customize_field_by_extension (line 38) | func Test_customize_field_by_extension(t *testing.T) {
function Test_customize_map_key_encoder (line 51) | func Test_customize_map_key_encoder(t *testing.T) {
type testMapKeyExtension (line 64) | type testMapKeyExtension struct
method CreateMapKeyEncoder (line 68) | func (extension *testMapKeyExtension) CreateMapKeyEncoder(typ reflect2...
method CreateMapKeyDecoder (line 81) | func (extension *testMapKeyExtension) CreateMapKeyDecoder(typ reflect2...
type funcDecoder (line 98) | type funcDecoder struct
method Decode (line 102) | func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter....
type funcEncoder (line 106) | type funcEncoder struct
method Encode (line 111) | func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *jsonite...
method IsEmpty (line 115) | func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
FILE: extra/binary_as_string_codec.go
type BinaryAsStringExtension (line 117) | type BinaryAsStringExtension struct
method CreateEncoder (line 121) | func (extension *BinaryAsStringExtension) CreateEncoder(typ reflect2.T...
method CreateDecoder (line 128) | func (extension *BinaryAsStringExtension) CreateDecoder(typ reflect2.T...
type binaryAsStringCodec (line 135) | type binaryAsStringCodec struct
method Decode (line 138) | func (codec *binaryAsStringCodec) Decode(ptr unsafe.Pointer, iter *jso...
method IsEmpty (line 163) | func (codec *binaryAsStringCodec) IsEmpty(ptr unsafe.Pointer) bool {
method Encode (line 166) | func (codec *binaryAsStringCodec) Encode(ptr unsafe.Pointer, stream *j...
function readHex (line 171) | func readHex(iter *jsoniter.Iterator, b1, b2 byte) byte {
function writeBytes (line 195) | func writeBytes(space []byte, s []byte) []byte {
function writeBytesSlowPath (line 214) | func writeBytesSlowPath(space []byte, s []byte) []byte {
FILE: extra/binary_as_string_codec_test.go
function init (line 9) | func init() {
function TestBinaryAsStringCodec (line 13) | func TestBinaryAsStringCodec(t *testing.T) {
FILE: extra/fuzzy_decoder.go
constant maxUint (line 15) | maxUint = ^uint(0)
constant maxInt (line 16) | maxInt = int(maxUint >> 1)
constant minInt (line 17) | minInt = -maxInt - 1
function RegisterFuzzyDecoders (line 21) | func RegisterFuzzyDecoders() {
type tolerateEmptyArrayExtension (line 148) | type tolerateEmptyArrayExtension struct
method DecorateDecoder (line 152) | func (extension *tolerateEmptyArrayExtension) DecorateDecoder(typ refl...
type tolerateEmptyArrayDecoder (line 159) | type tolerateEmptyArrayDecoder struct
method Decode (line 163) | func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, i...
type fuzzyStringDecoder (line 174) | type fuzzyStringDecoder struct
method Decode (line 177) | func (decoder *fuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *js...
type fuzzyIntegerDecoder (line 194) | type fuzzyIntegerDecoder struct
method Decode (line 198) | func (decoder *fuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *j...
type fuzzyFloat32Decoder (line 232) | type fuzzyFloat32Decoder struct
method Decode (line 235) | func (decoder *fuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *j...
type fuzzyFloat64Decoder (line 264) | type fuzzyFloat64Decoder struct
method Decode (line 267) | func (decoder *fuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *j...
FILE: extra/fuzzy_decoder_test.go
function init (line 10) | func init() {
function Test_any_to_string (line 14) | func Test_any_to_string(t *testing.T) {
function Test_any_to_int64 (line 28) | func Test_any_to_int64(t *testing.T) {
function Test_any_to_int (line 57) | func Test_any_to_int(t *testing.T) {
function Test_any_to_int16 (line 81) | func Test_any_to_int16(t *testing.T) {
function Test_any_to_int32 (line 105) | func Test_any_to_int32(t *testing.T) {
function Test_any_to_int8 (line 129) | func Test_any_to_int8(t *testing.T) {
function Test_any_to_uint8 (line 153) | func Test_any_to_uint8(t *testing.T) {
function Test_any_to_uint64 (line 177) | func Test_any_to_uint64(t *testing.T) {
function Test_any_to_uint32 (line 204) | func Test_any_to_uint32(t *testing.T) {
function Test_any_to_uint16 (line 231) | func Test_any_to_uint16(t *testing.T) {
function Test_any_to_uint (line 258) | func Test_any_to_uint(t *testing.T) {
function Test_any_to_float32 (line 281) | func Test_any_to_float32(t *testing.T) {
function Test_any_to_float64 (line 304) | func Test_any_to_float64(t *testing.T) {
function Test_empty_array_as_map (line 328) | func Test_empty_array_as_map(t *testing.T) {
function Test_empty_array_as_object (line 335) | func Test_empty_array_as_object(t *testing.T) {
function Test_bad_case (line 342) | func Test_bad_case(t *testing.T) {
function Test_null_to_string (line 363) | func Test_null_to_string(t *testing.T) {
function Test_null_to_int (line 371) | func Test_null_to_int(t *testing.T) {
function Test_null_to_float32 (line 379) | func Test_null_to_float32(t *testing.T) {
function Test_null_to_float64 (line 387) | func Test_null_to_float64(t *testing.T) {
FILE: extra/naming_strategy.go
function SetNamingStrategy (line 10) | func SetNamingStrategy(translate func(string) string) {
type namingStrategyExtension (line 14) | type namingStrategyExtension struct
method UpdateStructDescriptor (line 19) | func (extension *namingStrategyExtension) UpdateStructDescriptor(struc...
function LowerCaseWithUnderscores (line 40) | func LowerCaseWithUnderscores(name string) string {
FILE: extra/naming_strategy_test.go
function Test_lower_case_with_underscores (line 9) | func Test_lower_case_with_underscores(t *testing.T) {
function Test_set_naming_strategy_with_overrides (line 25) | func Test_set_naming_strategy_with_overrides(t *testing.T) {
function Test_set_naming_strategy_with_omitempty (line 39) | func Test_set_naming_strategy_with_omitempty(t *testing.T) {
function Test_set_naming_strategy_with_private_field (line 52) | func Test_set_naming_strategy_with_private_field(t *testing.T) {
FILE: extra/privat_fields.go
function SupportPrivateFields (line 10) | func SupportPrivateFields() {
type privateFieldsExtension (line 14) | type privateFieldsExtension struct
method UpdateStructDescriptor (line 18) | func (extension *privateFieldsExtension) UpdateStructDescriptor(struct...
function calcFieldNames (line 36) | func calcFieldNames(originalFieldName string, tagProvidedFieldName strin...
FILE: extra/private_fields_test.go
function Test_private_fields (line 9) | func Test_private_fields(t *testing.T) {
FILE: extra/time_as_int64_codec.go
function RegisterTimeAsInt64Codec (line 10) | func RegisterTimeAsInt64Codec(precision time.Duration) {
type timeAsInt64Codec (line 15) | type timeAsInt64Codec struct
method Decode (line 19) | func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsonit...
method IsEmpty (line 24) | func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
method Encode (line 28) | func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *json...
FILE: extra/time_as_int64_codec_test.go
function Test_time_as_int64 (line 10) | func Test_time_as_int64(t *testing.T) {
function Test_time_as_int64_keep_microsecond (line 21) | func Test_time_as_int64_keep_microsecond(t *testing.T) {
FILE: iter.go
type ValueType (line 10) | type ValueType
constant InvalidValue (line 14) | InvalidValue ValueType = iota
constant StringValue (line 16) | StringValue
constant NumberValue (line 18) | NumberValue
constant NilValue (line 20) | NilValue
constant BoolValue (line 22) | BoolValue
constant ArrayValue (line 24) | ArrayValue
constant ObjectValue (line 26) | ObjectValue
function init (line 32) | func init() {
type Iterator (line 71) | type Iterator struct
method Pool (line 126) | func (iter *Iterator) Pool() IteratorPool {
method Reset (line 131) | func (iter *Iterator) Reset(reader io.Reader) *Iterator {
method ResetBytes (line 140) | func (iter *Iterator) ResetBytes(input []byte) *Iterator {
method WhatIsNext (line 150) | func (iter *Iterator) WhatIsNext() ValueType {
method skipWhitespacesWithoutLoadMore (line 156) | func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool {
method isObjectEnd (line 169) | func (iter *Iterator) isObjectEnd() bool {
method nextToken (line 181) | func (iter *Iterator) nextToken() byte {
method ReportError (line 200) | func (iter *Iterator) ReportError(operation string, msg string) {
method CurrentBuffer (line 229) | func (iter *Iterator) CurrentBuffer() string {
method readByte (line 238) | func (iter *Iterator) readByte() (ret byte) {
method loadMore (line 252) | func (iter *Iterator) loadMore() bool {
method unreadByte (line 282) | func (iter *Iterator) unreadByte() {
method Read (line 291) | func (iter *Iterator) Read() interface{} {
method incrementDepth (line 333) | func (iter *Iterator) incrementDepth() (success bool) {
method decrementDepth (line 342) | func (iter *Iterator) decrementDepth() (success bool) {
function NewIterator (line 85) | func NewIterator(cfg API) *Iterator {
function Parse (line 97) | func Parse(cfg API, reader io.Reader, bufSize int) *Iterator {
function ParseBytes (line 109) | func ParseBytes(cfg API, input []byte) *Iterator {
function ParseString (line 121) | func ParseString(cfg API, input string) *Iterator {
constant maxDepth (line 331) | maxDepth = 10000
FILE: iter_array.go
method ReadArray (line 4) | func (iter *Iterator) ReadArray() (ret bool) {
method ReadArrayCB (line 28) | func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bo...
FILE: iter_float.go
constant invalidCharForNumber (line 14) | invalidCharForNumber = int8(-1)
constant endOfNumber (line 15) | endOfNumber = int8(-2)
constant dotInNumber (line 16) | dotInNumber = int8(-3)
function init (line 18) | func init() {
method ReadBigFloat (line 36) | func (iter *Iterator) ReadBigFloat() (ret *big.Float) {
method ReadBigInt (line 54) | func (iter *Iterator) ReadBigInt() (ret *big.Int) {
method ReadFloat32 (line 70) | func (iter *Iterator) ReadFloat32() (ret float32) {
method readPositiveFloat32 (line 79) | func (iter *Iterator) readPositiveFloat32() (ret float32) {
method readNumberAsString (line 159) | func (iter *Iterator) readNumberAsString() (ret string) {
method readFloat32SlowPath (line 188) | func (iter *Iterator) readFloat32SlowPath() (ret float32) {
method ReadFloat64 (line 207) | func (iter *Iterator) ReadFloat64() (ret float64) {
method readPositiveFloat64 (line 216) | func (iter *Iterator) readPositiveFloat64() (ret float64) {
method readFloat64SlowPath (line 299) | func (iter *Iterator) readFloat64SlowPath() (ret float64) {
function validateFloat (line 317) | func validateFloat(str string) string {
method ReadNumber (line 340) | func (iter *Iterator) ReadNumber() (ret json.Number) {
FILE: iter_int.go
constant uint32SafeToMultiply10 (line 10) | uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1
constant uint64SafeToMultiple10 (line 11) | uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1
constant maxFloat64 (line 12) | maxFloat64 = 1<<53 - 1
function init (line 14) | func init() {
method ReadUint (line 25) | func (iter *Iterator) ReadUint() uint {
method ReadInt (line 33) | func (iter *Iterator) ReadInt() int {
method ReadInt8 (line 41) | func (iter *Iterator) ReadInt8() (ret int8) {
method ReadUint8 (line 60) | func (iter *Iterator) ReadUint8() (ret uint8) {
method ReadInt16 (line 70) | func (iter *Iterator) ReadInt16() (ret int16) {
method ReadUint16 (line 89) | func (iter *Iterator) ReadUint16() (ret uint16) {
method ReadInt32 (line 99) | func (iter *Iterator) ReadInt32() (ret int32) {
method ReadUint32 (line 118) | func (iter *Iterator) ReadUint32() (ret uint32) {
method readUint32 (line 122) | func (iter *Iterator) readUint32(c byte) (ret uint32) {
method ReadInt64 (line 221) | func (iter *Iterator) ReadInt64() (ret int64) {
method ReadUint64 (line 240) | func (iter *Iterator) ReadUint64() uint64 {
method readUint64 (line 244) | func (iter *Iterator) readUint64(c byte) (ret uint64) {
method assertInteger (line 342) | func (iter *Iterator) assertInteger() {
FILE: iter_object.go
method ReadObject (line 11) | func (iter *Iterator) ReadObject() (ret string) {
method readFieldHash (line 49) | func (iter *Iterator) readFieldHash() int64 {
function calcHash (line 98) | func calcHash(str string, caseSensitive bool) int64 {
method ReadObjectCB (line 111) | func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool...
method ReadMapCB (line 166) | func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) b...
method readObjectStart (line 221) | func (iter *Iterator) readObjectStart() bool {
method readObjectFieldAsBytes (line 238) | func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) {
FILE: iter_skip.go
method ReadNil (line 7) | func (iter *Iterator) ReadNil() (ret bool) {
method ReadBool (line 18) | func (iter *Iterator) ReadBool() (ret bool) {
method SkipAndReturnBytes (line 34) | func (iter *Iterator) SkipAndReturnBytes() []byte {
method SkipAndAppendBytes (line 42) | func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte {
method startCaptureTo (line 48) | func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) {
method startCapture (line 56) | func (iter *Iterator) startCapture(captureStartedAt int) {
method stopCapture (line 60) | func (iter *Iterator) stopCapture() []byte {
method Skip (line 72) | func (iter *Iterator) Skip() {
method skipFourBytes (line 98) | func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) {
method skipThreeBytes (line 117) | func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) {
FILE: iter_skip_sloppy.go
method skipNumber (line 7) | func (iter *Iterator) skipNumber() {
method skipArray (line 23) | func (iter *Iterator) skipArray() {
method skipObject (line 60) | func (iter *Iterator) skipObject() {
method skipString (line 98) | func (iter *Iterator) skipString() {
method findStringEnd (line 119) | func (iter *Iterator) findStringEnd() (int, bool) {
FILE: iter_skip_sloppy_test.go
function Test_string_end (line 11) | func Test_string_end(t *testing.T) {
type StagedReader (line 70) | type StagedReader struct
method Read (line 77) | func (reader *StagedReader) Read(p []byte) (n int, err error) {
function Test_skip_string (line 94) | func Test_skip_string(t *testing.T) {
function Test_skip_object (line 132) | func Test_skip_object(t *testing.T) {
FILE: iter_skip_strict.go
method skipNumber (line 10) | func (iter *Iterator) skipNumber() {
method trySkipNumber (line 24) | func (iter *Iterator) trySkipNumber() bool {
method skipString (line 61) | func (iter *Iterator) skipString() {
method trySkipString (line 68) | func (iter *Iterator) trySkipString() bool {
method skipObject (line 85) | func (iter *Iterator) skipObject() {
method skipArray (line 93) | func (iter *Iterator) skipArray() {
FILE: iter_str.go
method ReadString (line 9) | func (iter *Iterator) ReadString() (ret string) {
method readStringSlowPath (line 35) | func (iter *Iterator) readStringSlowPath() (ret string) {
method readEscapedChar (line 54) | func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte {
method ReadStringAsSlice (line 116) | func (iter *Iterator) ReadStringAsSlice() (ret []byte) {
method readU4 (line 146) | func (iter *Iterator) readU4() (ret rune) {
constant t1 (line 167) | t1 = 0x00
constant tx (line 168) | tx = 0x80
constant t2 (line 169) | t2 = 0xC0
constant t3 (line 170) | t3 = 0xE0
constant t4 (line 171) | t4 = 0xF0
constant t5 (line 172) | t5 = 0xF8
constant maskx (line 174) | maskx = 0x3F
constant mask2 (line 175) | mask2 = 0x1F
constant mask3 (line 176) | mask3 = 0x0F
constant mask4 (line 177) | mask4 = 0x07
constant rune1Max (line 179) | rune1Max = 1<<7 - 1
constant rune2Max (line 180) | rune2Max = 1<<11 - 1
constant rune3Max (line 181) | rune3Max = 1<<16 - 1
constant surrogateMin (line 183) | surrogateMin = 0xD800
constant surrogateMax (line 184) | surrogateMax = 0xDFFF
constant maxRune (line 186) | maxRune = '\U0010FFFF'
constant runeError (line 187) | runeError = '\uFFFD'
function appendRune (line 190) | func appendRune(p []byte, r rune) []byte {
FILE: misc_tests/jsoniter_array_test.go
function Test_empty_array (line 12) | func Test_empty_array(t *testing.T) {
function Test_one_element (line 24) | func Test_one_element(t *testing.T) {
function Test_two_elements (line 37) | func Test_two_elements(t *testing.T) {
function Test_whitespace_in_head (line 49) | func Test_whitespace_in_head(t *testing.T) {
function Test_whitespace_after_array_start (line 60) | func Test_whitespace_after_array_start(t *testing.T) {
function Test_whitespace_before_array_end (line 71) | func Test_whitespace_before_array_end(t *testing.T) {
function Test_whitespace_before_comma (line 86) | func Test_whitespace_before_comma(t *testing.T) {
function Test_write_array (line 108) | func Test_write_array(t *testing.T) {
function Test_write_val_array (line 122) | func Test_write_val_array(t *testing.T) {
function Test_write_val_empty_array (line 130) | func Test_write_val_empty_array(t *testing.T) {
function Test_write_array_of_interface_in_struct (line 138) | func Test_write_array_of_interface_in_struct(t *testing.T) {
function Test_encode_byte_array (line 151) | func Test_encode_byte_array(t *testing.T) {
function Test_encode_empty_byte_array (line 161) | func Test_encode_empty_byte_array(t *testing.T) {
function Test_encode_nil_byte_array (line 171) | func Test_encode_nil_byte_array(t *testing.T) {
function Test_decode_byte_array_from_base64 (line 182) | func Test_decode_byte_array_from_base64(t *testing.T) {
function Test_decode_byte_array_from_base64_with_newlines (line 193) | func Test_decode_byte_array_from_base64_with_newlines(t *testing.T) {
function Test_decode_byte_array_from_array (line 204) | func Test_decode_byte_array_from_array(t *testing.T) {
function Test_decode_slice (line 215) | func Test_decode_slice(t *testing.T) {
function Test_decode_large_slice (line 222) | func Test_decode_large_slice(t *testing.T) {
function Benchmark_jsoniter_array (line 229) | func Benchmark_jsoniter_array(b *testing.B) {
function Benchmark_json_array (line 242) | func Benchmark_json_array(b *testing.B) {
FILE: misc_tests/jsoniter_bool_test.go
function Test_true (line 11) | func Test_true(t *testing.T) {
function Test_false (line 19) | func Test_false(t *testing.T) {
function Test_write_true_false (line 25) | func Test_write_true_false(t *testing.T) {
function Test_write_val_bool (line 37) | func Test_write_val_bool(t *testing.T) {
FILE: misc_tests/jsoniter_float_test.go
function Test_read_big_float (line 12) | func Test_read_big_float(t *testing.T) {
function Test_read_big_int (line 20) | func Test_read_big_int(t *testing.T) {
function Test_read_float_as_interface (line 28) | func Test_read_float_as_interface(t *testing.T) {
function Test_wrap_float (line 34) | func Test_wrap_float(t *testing.T) {
function Test_read_float64_cursor (line 41) | func Test_read_float64_cursor(t *testing.T) {
function Test_read_float_scientific (line 50) | func Test_read_float_scientific(t *testing.T) {
function Test_lossy_float_marshal (line 63) | func Test_lossy_float_marshal(t *testing.T) {
function Test_read_number (line 74) | func Test_read_number(t *testing.T) {
function Test_encode_inf (line 81) | func Test_encode_inf(t *testing.T) {
function Test_encode_nan (line 91) | func Test_encode_nan(t *testing.T) {
function Benchmark_jsoniter_float (line 101) | func Benchmark_jsoniter_float(b *testing.B) {
function Benchmark_json_float (line 111) | func Benchmark_json_float(b *testing.B) {
FILE: misc_tests/jsoniter_int_test.go
function Test_read_uint64_invalid (line 18) | func Test_read_uint64_invalid(t *testing.T) {
function Test_read_int32_array (line 25) | func Test_read_int32_array(t *testing.T) {
function Test_read_int64_array (line 33) | func Test_read_int64_array(t *testing.T) {
function Test_wrap_int (line 41) | func Test_wrap_int(t *testing.T) {
function Test_write_val_int (line 48) | func Test_write_val_int(t *testing.T) {
function Test_write_val_int_ptr (line 58) | func Test_write_val_int_ptr(t *testing.T) {
function Test_float_as_int (line 69) | func Test_float_as_int(t *testing.T) {
type chunkedData (line 77) | type chunkedData struct
method Read (line 84) | func (c *chunkedData) Read(p []byte) (n int, err error) {
function TestIterator_ReadInt_chunkedInput (line 102) | func TestIterator_ReadInt_chunkedInput(t *testing.T) {
function jsonFloatIntArray (line 137) | func jsonFloatIntArray(t *testing.T, numberOfItems int) []byte {
function Benchmark_jsoniter_encode_int (line 164) | func Benchmark_jsoniter_encode_int(b *testing.B) {
function Benchmark_itoa (line 172) | func Benchmark_itoa(b *testing.B) {
function Benchmark_jsoniter_int (line 178) | func Benchmark_jsoniter_int(b *testing.B) {
function Benchmark_json_int (line 187) | func Benchmark_json_int(b *testing.B) {
FILE: misc_tests/jsoniter_interface_test.go
function Test_nil_non_empty_interface (line 11) | func Test_nil_non_empty_interface(t *testing.T) {
function Test_nil_out_null_interface (line 22) | func Test_nil_out_null_interface(t *testing.T) {
function Test_overwrite_interface_ptr_value_with_nil (line 59) | func Test_overwrite_interface_ptr_value_with_nil(t *testing.T) {
function Test_overwrite_interface_value_with_nil (line 100) | func Test_overwrite_interface_value_with_nil(t *testing.T) {
function Test_unmarshal_into_nil (line 139) | func Test_unmarshal_into_nil(t *testing.T) {
FILE: misc_tests/jsoniter_iterator_test.go
function Test_bad_case (line 14) | func Test_bad_case(t *testing.T) {
function Test_iterator_use_number (line 43) | func Test_iterator_use_number(t *testing.T) {
function Test_iterator_without_number (line 56) | func Test_iterator_without_number(t *testing.T) {
FILE: misc_tests/jsoniter_map_test.go
function Test_decode_TextMarshaler_key_map (line 13) | func Test_decode_TextMarshaler_key_map(t *testing.T) {
function Test_read_map_with_reader (line 22) | func Test_read_map_with_reader(t *testing.T) {
function Test_map_eface_of_eface (line 35) | func Test_map_eface_of_eface(t *testing.T) {
function Test_encode_nil_map (line 46) | func Test_encode_nil_map(t *testing.T) {
FILE: misc_tests/jsoniter_nested_test.go
type Level1 (line 11) | type Level1 struct
type Level2 (line 15) | type Level2 struct
function Test_deep_nested (line 19) | func Test_deep_nested(t *testing.T) {
function Test_nested (line 256) | func Test_nested(t *testing.T) {
function Benchmark_jsoniter_nested (line 290) | func Benchmark_jsoniter_nested(b *testing.B) {
function readLevel1Hello (line 305) | func readLevel1Hello(iter *jsoniter.Iterator) []Level2 {
function Benchmark_json_nested (line 322) | func Benchmark_json_nested(b *testing.B) {
FILE: misc_tests/jsoniter_null_test.go
function Test_read_null (line 12) | func Test_read_null(t *testing.T) {
function Test_write_null (line 26) | func Test_write_null(t *testing.T) {
function Test_decode_null_object_field (line 36) | func Test_decode_null_object_field(t *testing.T) {
function Test_decode_null_array_element (line 55) | func Test_decode_null_array_element(t *testing.T) {
function Test_decode_null_string (line 64) | func Test_decode_null_string(t *testing.T) {
function Test_decode_null_skip (line 73) | func Test_decode_null_skip(t *testing.T) {
FILE: misc_tests/jsoniter_object_test.go
function Test_empty_object (line 14) | func Test_empty_object(t *testing.T) {
function Test_one_field (line 26) | func Test_one_field(t *testing.T) {
function Test_two_field (line 44) | func Test_two_field(t *testing.T) {
function Test_write_object (line 70) | func Test_write_object(t *testing.T) {
function Test_reader_and_load_more (line 86) | func Test_reader_and_load_more(t *testing.T) {
function Test_unmarshal_into_existing_value (line 135) | func Test_unmarshal_into_existing_value(t *testing.T) {
function Test_unmarshal_anonymous_struct_invalid (line 153) | func Test_unmarshal_anonymous_struct_invalid(t *testing.T) {
FILE: misc_tests/jsoniter_raw_message_test.go
function Test_jsoniter_RawMessage (line 11) | func Test_jsoniter_RawMessage(t *testing.T) {
function Test_encode_map_of_jsoniter_raw_message (line 21) | func Test_encode_map_of_jsoniter_raw_message(t *testing.T) {
function Test_marshal_invalid_json_raw_message (line 31) | func Test_marshal_invalid_json_raw_message(t *testing.T) {
function Test_marshal_nil_json_raw_message (line 45) | func Test_marshal_nil_json_raw_message(t *testing.T) {
function Test_raw_message_memory_not_copied_issue (line 64) | func Test_raw_message_memory_not_copied_issue(t *testing.T) {
FILE: pool.go
type IteratorPool (line 8) | type IteratorPool interface
type StreamPool (line 14) | type StreamPool interface
method BorrowStream (line 19) | func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream {
method ReturnStream (line 25) | func (cfg *frozenConfig) ReturnStream(stream *Stream) {
method BorrowIterator (line 32) | func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator {
method ReturnIterator (line 38) | func (cfg *frozenConfig) ReturnIterator(iter *Iterator) {
FILE: reflect.go
type ValDecoder (line 21) | type ValDecoder interface
type ValEncoder (line 28) | type ValEncoder interface
type checkIsEmpty (line 33) | type checkIsEmpty interface
type ctx (line 37) | type ctx struct
method caseSensitive (line 44) | func (b *ctx) caseSensitive() bool {
method append (line 52) | func (b *ctx) append(prefix string) *ctx {
method ReadVal (line 62) | func (iter *Iterator) ReadVal(obj interface{}) {
method WriteVal (line 87) | func (stream *Stream) WriteVal(val interface{}) {
method DecoderOf (line 101) | func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder {
function decoderOfType (line 119) | func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
function createDecoderOfType (line 135) | func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
function _createDecoderOfType (line 147) | func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder {
method EncoderOf (line 190) | func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder {
type onePtrEncoder (line 210) | type onePtrEncoder struct
method IsEmpty (line 214) | func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool {
method Encode (line 218) | func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Strea...
function encoderOfType (line 222) | func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
function createEncoderOfType (line 238) | func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
function _createEncoderOfType (line 249) | func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder {
type lazyErrorDecoder (line 289) | type lazyErrorDecoder struct
method Decode (line 293) | func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iter...
type lazyErrorEncoder (line 303) | type lazyErrorEncoder struct
method Encode (line 307) | func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *St...
method IsEmpty (line 315) | func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type placeholderDecoder (line 319) | type placeholderDecoder struct
method Decode (line 323) | func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *It...
type placeholderEncoder (line 327) | type placeholderEncoder struct
method Encode (line 331) | func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *...
method IsEmpty (line 335) | func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool {
FILE: reflect_array.go
function decoderOfArray (line 10) | func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder {
function encoderOfArray (line 16) | func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder {
type emptyArrayEncoder (line 25) | type emptyArrayEncoder struct
method Encode (line 27) | func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *St...
method IsEmpty (line 31) | func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type arrayEncoder (line 35) | type arrayEncoder struct
method Encode (line 40) | func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 55) | func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type arrayDecoder (line 59) | type arrayDecoder struct
method Decode (line 64) | func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
method doDecode (line 71) | func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterat...
FILE: reflect_dynamic.go
type dynamicEncoder (line 9) | type dynamicEncoder struct
method Encode (line 13) | func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stre...
method IsEmpty (line 18) | func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type efaceDecoder (line 22) | type efaceDecoder struct
method Decode (line 25) | func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
type ifaceDecoder (line 55) | type ifaceDecoder struct
method Decode (line 59) | func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
FILE: reflect_extension.go
type StructDescriptor (line 20) | type StructDescriptor struct
method GetField (line 27) | func (structDescriptor *StructDescriptor) GetField(fieldName string) *...
type Binding (line 37) | type Binding struct
type Extension (line 48) | type Extension interface
type DummyExtension (line 59) | type DummyExtension struct
method UpdateStructDescriptor (line 63) | func (extension *DummyExtension) UpdateStructDescriptor(structDescript...
method CreateMapKeyDecoder (line 67) | func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type...
method CreateMapKeyEncoder (line 72) | func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type...
method CreateDecoder (line 77) | func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValD...
method CreateEncoder (line 82) | func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValE...
method DecorateDecoder (line 87) | func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, de...
method DecorateEncoder (line 92) | func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, en...
type EncoderExtension (line 96) | type EncoderExtension
method UpdateStructDescriptor (line 99) | func (extension EncoderExtension) UpdateStructDescriptor(structDescrip...
method CreateDecoder (line 103) | func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) Val...
method CreateEncoder (line 108) | func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) Val...
method CreateMapKeyDecoder (line 113) | func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Typ...
method CreateMapKeyEncoder (line 118) | func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Typ...
method DecorateDecoder (line 123) | func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, d...
method DecorateEncoder (line 128) | func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, e...
type DecoderExtension (line 132) | type DecoderExtension
method UpdateStructDescriptor (line 135) | func (extension DecoderExtension) UpdateStructDescriptor(structDescrip...
method CreateMapKeyDecoder (line 139) | func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Typ...
method CreateMapKeyEncoder (line 144) | func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Typ...
method CreateDecoder (line 149) | func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) Val...
method CreateEncoder (line 154) | func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) Val...
method DecorateDecoder (line 159) | func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, d...
method DecorateEncoder (line 164) | func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, e...
type funcDecoder (line 168) | type funcDecoder struct
method Decode (line 172) | func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
type funcEncoder (line 176) | type funcEncoder struct
method Encode (line 181) | func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 185) | func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type DecoderFunc (line 193) | type DecoderFunc
type EncoderFunc (line 196) | type EncoderFunc
function RegisterTypeDecoderFunc (line 199) | func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) {
function RegisterTypeDecoder (line 204) | func RegisterTypeDecoder(typ string, decoder ValDecoder) {
function RegisterFieldDecoderFunc (line 209) | func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) {
function RegisterFieldDecoder (line 214) | func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) {
function RegisterTypeEncoderFunc (line 219) | func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc fu...
function RegisterTypeEncoder (line 224) | func RegisterTypeEncoder(typ string, encoder ValEncoder) {
function RegisterFieldEncoderFunc (line 229) | func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc,...
function RegisterFieldEncoder (line 234) | func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
function RegisterExtension (line 239) | func RegisterExtension(extension Extension) {
function getTypeDecoderFromExtension (line 243) | func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder {
function _getTypeDecoderFromExtension (line 256) | func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder {
function getTypeEncoderFromExtension (line 288) | func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder {
function _getTypeEncoderFromExtension (line 302) | func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder {
function describeStruct (line 334) | func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor {
function createStructDescriptor (line 398) | func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Bin...
type sortableBindings (line 419) | type sortableBindings
method Len (line 421) | func (bindings sortableBindings) Len() int {
method Less (line 425) | func (bindings sortableBindings) Less(i, j int) bool {
method Swap (line 439) | func (bindings sortableBindings) Swap(i, j int) {
function processTags (line 443) | func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) {
function calcFieldNames (line 465) | func calcFieldNames(originalFieldName string, tagProvidedFieldName strin...
FILE: reflect_json_number.go
type Number (line 10) | type Number
method String (line 13) | func (n Number) String() string { return string(n) }
method Float64 (line 16) | func (n Number) Float64() (float64, error) {
method Int64 (line 21) | func (n Number) Int64() (int64, error) {
function CastJsonNumber (line 25) | func CastJsonNumber(val interface{}) (string, bool) {
function createDecoderOfJsonNumber (line 38) | func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder {
function createEncoderOfJsonNumber (line 48) | func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder {
type jsonNumberCodec (line 58) | type jsonNumberCodec struct
method Decode (line 61) | func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterato...
method Encode (line 73) | func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Strea...
method IsEmpty (line 82) | func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool {
type jsoniterNumberCodec (line 86) | type jsoniterNumberCodec struct
method Decode (line 89) | func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Ite...
method Encode (line 101) | func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *S...
method IsEmpty (line 110) | func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool {
FILE: reflect_json_raw_message.go
function createEncoderOfJsonRawMessage (line 12) | func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncod...
function createDecoderOfJsonRawMessage (line 22) | func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecod...
type jsonRawMessageCodec (line 32) | type jsonRawMessageCodec struct
method Decode (line 35) | func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Ite...
method Encode (line 43) | func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *S...
method IsEmpty (line 51) | func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
type jsoniterRawMessageCodec (line 55) | type jsoniterRawMessageCodec struct
method Decode (line 58) | func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter ...
method Encode (line 66) | func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, strea...
method IsEmpty (line 74) | func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
FILE: reflect_map.go
function decoderOfMap (line 13) | func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder {
function encoderOfMap (line 26) | func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder {
function decoderOfMapKey (line 42) | func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder {
function encoderOfMapKey (line 98) | func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder {
type mapDecoder (line 145) | type mapDecoder struct
method Decode (line 153) | func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
type numericMapKeyDecoder (line 201) | type numericMapKeyDecoder struct
method Decode (line 205) | func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *...
type numericMapKeyEncoder (line 219) | type numericMapKeyEncoder struct
method Encode (line 223) | func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream...
method IsEmpty (line 229) | func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type dynamicMapKeyEncoder (line 233) | type dynamicMapKeyEncoder struct
method Encode (line 238) | func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream...
method IsEmpty (line 243) | func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type mapEncoder (line 248) | type mapEncoder struct
method Encode (line 254) | func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 277) | func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type sortKeysMapEncoder (line 282) | type sortKeysMapEncoder struct
method Encode (line 288) | func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *...
method IsEmpty (line 335) | func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type encodedKeyValues (line 340) | type encodedKeyValues
method Len (line 347) | func (sv encodedKeyValues) Len() int { return len(sv) }
method Swap (line 348) | func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j],...
method Less (line 349) | func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv...
type encodedKV (line 342) | type encodedKV struct
FILE: reflect_marshaler.go
function createDecoderOfMarshaler (line 16) | func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder {
function createEncoderOfMarshaler (line 31) | func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder {
type marshalerEncoder (line 86) | type marshalerEncoder struct
method Encode (line 91) | func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *St...
method IsEmpty (line 112) | func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type directMarshalerEncoder (line 116) | type directMarshalerEncoder struct
method Encode (line 120) | func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stre...
method IsEmpty (line 134) | func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type textMarshalerEncoder (line 138) | type textMarshalerEncoder struct
method Encode (line 144) | func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream...
method IsEmpty (line 160) | func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type directTextMarshalerEncoder (line 164) | type directTextMarshalerEncoder struct
method Encode (line 169) | func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, ...
method IsEmpty (line 184) | func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer)...
type unmarshalerDecoder (line 188) | type unmarshalerDecoder struct
method Decode (line 192) | func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *It...
type textUnmarshalerDecoder (line 205) | type textUnmarshalerDecoder struct
method Decode (line 209) | func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter...
FILE: reflect_native.go
constant ptrSize (line 12) | ptrSize = 32 << uintptr(^uintptr(0)>>63)
function createEncoderOfNative (line 14) | func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder {
function createDecoderOfNative (line 110) | func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder {
type stringCodec (line 205) | type stringCodec struct
method Decode (line 208) | func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 212) | func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 217) | func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool {
type int8Codec (line 221) | type int8Codec struct
method Decode (line 224) | func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 230) | func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 234) | func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool {
type int16Codec (line 238) | type int16Codec struct
method Decode (line 241) | func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 247) | func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 251) | func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool {
type int32Codec (line 255) | type int32Codec struct
method Decode (line 258) | func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 264) | func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 268) | func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool {
type int64Codec (line 272) | type int64Codec struct
method Decode (line 275) | func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 281) | func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 285) | func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool {
type uint8Codec (line 289) | type uint8Codec struct
method Decode (line 292) | func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 298) | func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 302) | func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool {
type uint16Codec (line 306) | type uint16Codec struct
method Decode (line 309) | func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 315) | func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 319) | func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool {
type uint32Codec (line 323) | type uint32Codec struct
method Decode (line 326) | func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 332) | func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 336) | func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool {
type uint64Codec (line 340) | type uint64Codec struct
method Decode (line 343) | func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 349) | func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 353) | func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool {
type float32Codec (line 357) | type float32Codec struct
method Decode (line 360) | func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 366) | func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 370) | func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool {
type float64Codec (line 374) | type float64Codec struct
method Decode (line 377) | func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 383) | func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 387) | func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool {
type boolCodec (line 391) | type boolCodec struct
method Decode (line 394) | func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 400) | func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 404) | func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool {
type base64Codec (line 408) | type base64Codec struct
method Decode (line 413) | func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
method Encode (line 434) | func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 451) | func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool {
FILE: reflect_optional.go
function decoderOfOptional (line 8) | func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder {
function encoderOfOptional (line 15) | func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder {
type OptionalDecoder (line 23) | type OptionalDecoder struct
method Decode (line 28) | func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Itera...
type dereferenceDecoder (line 44) | type dereferenceDecoder struct
method Decode (line 50) | func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *It...
type OptionalEncoder (line 62) | type OptionalEncoder struct
method Encode (line 66) | func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Str...
method IsEmpty (line 74) | func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type dereferenceEncoder (line 78) | type dereferenceEncoder struct
method Encode (line 82) | func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *...
method IsEmpty (line 90) | func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool {
method IsEmbeddedPtrNil (line 98) | func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer...
type referenceEncoder (line 111) | type referenceEncoder struct
method Encode (line 115) | func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *St...
method IsEmpty (line 119) | func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type referenceDecoder (line 123) | type referenceDecoder struct
method Decode (line 127) | func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iter...
FILE: reflect_slice.go
function decoderOfSlice (line 10) | func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder {
function encoderOfSlice (line 16) | func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder {
type sliceEncoder (line 22) | type sliceEncoder struct
method Encode (line 27) | func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
method IsEmpty (line 50) | func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type sliceDecoder (line 54) | type sliceDecoder struct
method Decode (line 59) | func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
method doDecode (line 66) | func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterat...
FILE: reflect_struct_decoder.go
function decoderOfStruct (line 12) | func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder {
function createStructDecoder (line 47) | func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]...
type generalStructDecoder (line 493) | type generalStructDecoder struct
method Decode (line 499) | func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *...
method decodeOneField (line 519) | func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer...
type skipObjectDecoder (line 555) | type skipObjectDecoder struct
method Decode (line 559) | func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Ite...
type oneFieldStructDecoder (line 568) | type oneFieldStructDecoder struct
method Decode (line 574) | func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter ...
type twoFieldsStructDecoder (line 597) | type twoFieldsStructDecoder struct
method Decode (line 605) | func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter...
type threeFieldsStructDecoder (line 631) | type threeFieldsStructDecoder struct
method Decode (line 641) | func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, it...
type fourFieldsStructDecoder (line 669) | type fourFieldsStructDecoder struct
method Decode (line 681) | func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, ite...
type fiveFieldsStructDecoder (line 711) | type fiveFieldsStructDecoder struct
method Decode (line 725) | func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, ite...
type sixFieldsStructDecoder (line 757) | type sixFieldsStructDecoder struct
method Decode (line 773) | func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter...
type sevenFieldsStructDecoder (line 807) | type sevenFieldsStructDecoder struct
method Decode (line 825) | func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, it...
type eightFieldsStructDecoder (line 861) | type eightFieldsStructDecoder struct
method Decode (line 881) | func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, it...
type nineFieldsStructDecoder (line 919) | type nineFieldsStructDecoder struct
method Decode (line 941) | func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, ite...
type tenFieldsStructDecoder (line 981) | type tenFieldsStructDecoder struct
method Decode (line 1005) | func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter...
type structFieldDecoder (line 1047) | type structFieldDecoder struct
method Decode (line 1052) | func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *It...
type stringModeStringDecoder (line 1060) | type stringModeStringDecoder struct
method Decode (line 1065) | func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, ite...
type stringModeNumberDecoder (line 1073) | type stringModeNumberDecoder struct
method Decode (line 1077) | func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, ite...
FILE: reflect_struct_encoder.go
function encoderOfStruct (line 11) | func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder {
function createCheckIsEmpty (line 49) | func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty {
function resolveConflictBinding (line 73) | func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignor...
type structFieldEncoder (line 102) | type structFieldEncoder struct
method Encode (line 108) | func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *...
method IsEmpty (line 116) | func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool {
method IsEmbeddedPtrNil (line 121) | func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer...
type IsEmbeddedPtrNil (line 130) | type IsEmbeddedPtrNil interface
type structEncoder (line 134) | type structEncoder struct
method Encode (line 144) | func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Strea...
method IsEmpty (line 167) | func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type structFieldTo (line 139) | type structFieldTo struct
type emptyStructEncoder (line 171) | type emptyStructEncoder struct
method Encode (line 174) | func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *...
method IsEmpty (line 178) | func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool {
type stringModeNumberEncoder (line 182) | type stringModeNumberEncoder struct
method Encode (line 186) | func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, str...
method IsEmpty (line 192) | func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bo...
type stringModeStringEncoder (line 196) | type stringModeStringEncoder struct
method Encode (line 201) | func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, str...
method IsEmpty (line 209) | func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bo...
FILE: skip_tests/array_test.go
function init (line 3) | func init() {
FILE: skip_tests/float64_test.go
function init (line 3) | func init() {
FILE: skip_tests/jsoniter_skip_test.go
function Test_skip_number_in_array (line 12) | func Test_skip_number_in_array(t *testing.T) {
function Test_skip_string_in_array (line 22) | func Test_skip_string_in_array(t *testing.T) {
function Test_skip_null (line 32) | func Test_skip_null(t *testing.T) {
function Test_skip_true (line 42) | func Test_skip_true(t *testing.T) {
function Test_skip_false (line 52) | func Test_skip_false(t *testing.T) {
function Test_skip_array (line 62) | func Test_skip_array(t *testing.T) {
function Test_skip_empty_array (line 72) | func Test_skip_empty_array(t *testing.T) {
function Test_skip_nested (line 82) | func Test_skip_nested(t *testing.T) {
function Test_skip_and_return_bytes (line 92) | func Test_skip_and_return_bytes(t *testing.T) {
function Test_skip_and_return_bytes_with_reader (line 100) | func Test_skip_and_return_bytes_with_reader(t *testing.T) {
function Test_append_skip_and_return_bytes_with_reader (line 108) | func Test_append_skip_and_return_bytes_with_reader(t *testing.T) {
function Test_skip_empty (line 117) | func Test_skip_empty(t *testing.T) {
type TestResp (line 122) | type TestResp struct
function Benchmark_jsoniter_skip (line 126) | func Benchmark_jsoniter_skip(b *testing.B) {
function Benchmark_json_skip (line 165) | func Benchmark_json_skip(b *testing.B) {
FILE: skip_tests/skip_test.go
type testCase (line 13) | type testCase struct
function Test_skip (line 20) | func Test_skip(t *testing.T) {
FILE: skip_tests/string_test.go
function init (line 3) | func init() {
FILE: skip_tests/struct_test.go
function init (line 3) | func init() {
FILE: stream.go
type Stream (line 9) | type Stream struct
method Pool (line 33) | func (stream *Stream) Pool() StreamPool {
method Reset (line 38) | func (stream *Stream) Reset(out io.Writer) {
method Available (line 44) | func (stream *Stream) Available() int {
method Buffered (line 49) | func (stream *Stream) Buffered() int {
method Buffer (line 54) | func (stream *Stream) Buffer() []byte {
method SetBuffer (line 59) | func (stream *Stream) SetBuffer(buf []byte) {
method Write (line 67) | func (stream *Stream) Write(p []byte) (nn int, err error) {
method writeByte (line 78) | func (stream *Stream) writeByte(c byte) {
method writeTwoBytes (line 82) | func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) {
method writeThreeBytes (line 86) | func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) {
method writeFourBytes (line 90) | func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byt...
method writeFiveBytes (line 94) | func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byt...
method Flush (line 99) | func (stream *Stream) Flush() error {
method WriteRaw (line 118) | func (stream *Stream) WriteRaw(s string) {
method WriteNil (line 123) | func (stream *Stream) WriteNil() {
method WriteTrue (line 128) | func (stream *Stream) WriteTrue() {
method WriteFalse (line 133) | func (stream *Stream) WriteFalse() {
method WriteBool (line 138) | func (stream *Stream) WriteBool(val bool) {
method WriteObjectStart (line 147) | func (stream *Stream) WriteObjectStart() {
method WriteObjectField (line 154) | func (stream *Stream) WriteObjectField(field string) {
method WriteObjectEnd (line 164) | func (stream *Stream) WriteObjectEnd() {
method WriteEmptyObject (line 171) | func (stream *Stream) WriteEmptyObject() {
method WriteMore (line 177) | func (stream *Stream) WriteMore() {
method WriteArrayStart (line 183) | func (stream *Stream) WriteArrayStart() {
method WriteEmptyArray (line 190) | func (stream *Stream) WriteEmptyArray() {
method WriteArrayEnd (line 195) | func (stream *Stream) WriteArrayEnd() {
method writeIndention (line 201) | func (stream *Stream) writeIndention(delta int) {
function NewStream (line 22) | func NewStream(cfg API, out io.Writer, bufSize int) *Stream {
FILE: stream_float.go
function init (line 11) | func init() {
method WriteFloat32 (line 16) | func (stream *Stream) WriteFloat32(val float32) {
method WriteFloat32Lossy (line 41) | func (stream *Stream) WriteFloat32Lossy(val float32) {
method WriteFloat64 (line 73) | func (stream *Stream) WriteFloat64(val float64) {
method WriteFloat64Lossy (line 98) | func (stream *Stream) WriteFloat64Lossy(val float64) {
FILE: stream_int.go
function init (line 5) | func init() {
function writeFirstBuf (line 17) | func writeFirstBuf(space []byte, v uint32) []byte {
function writeBuf (line 28) | func writeBuf(buf []byte, v uint32) []byte {
method WriteUint8 (line 33) | func (stream *Stream) WriteUint8(val uint8) {
method WriteInt8 (line 38) | func (stream *Stream) WriteInt8(nval int8) {
method WriteUint16 (line 50) | func (stream *Stream) WriteUint16(val uint16) {
method WriteInt16 (line 63) | func (stream *Stream) WriteInt16(nval int16) {
method WriteUint32 (line 75) | func (stream *Stream) WriteUint32(val uint32) {
method WriteInt32 (line 102) | func (stream *Stream) WriteInt32(nval int32) {
method WriteUint64 (line 114) | func (stream *Stream) WriteUint64(val uint64) {
method WriteInt64 (line 171) | func (stream *Stream) WriteInt64(nval int64) {
method WriteInt (line 183) | func (stream *Stream) WriteInt(val int) {
method WriteUint (line 188) | func (stream *Stream) WriteUint(val uint) {
FILE: stream_str.go
method WriteStringWithHTMLEscaped (line 221) | func (stream *Stream) WriteStringWithHTMLEscaped(s string) {
function writeStringSlowPathWithHTMLEscaped (line 241) | func writeStringSlowPathWithHTMLEscaped(stream *Stream, i int, s string,...
method WriteString (line 311) | func (stream *Stream) WriteString(s string) {
function writeStringSlowPath (line 331) | func writeStringSlowPath(stream *Stream, i int, s string, valLen int) {
FILE: stream_test.go
function Test_writeByte_should_grow_buffer (line 9) | func Test_writeByte_should_grow_buffer(t *testing.T) {
function Test_writeBytes_should_grow_buffer (line 22) | func Test_writeBytes_should_grow_buffer(t *testing.T) {
function Test_writeIndention_should_grow_buffer (line 33) | func Test_writeIndention_should_grow_buffer(t *testing.T) {
function Test_writeRaw_should_grow_buffer (line 40) | func Test_writeRaw_should_grow_buffer(t *testing.T) {
function Test_writeString_should_grow_buffer (line 48) | func Test_writeString_should_grow_buffer(t *testing.T) {
type NopWriter (line 56) | type NopWriter struct
method Write (line 60) | func (w *NopWriter) Write(p []byte) (n int, err error) {
function Test_flush_buffer_should_stop_grow_buffer (line 65) | func Test_flush_buffer_should_stop_grow_buffer(t *testing.T) {
FILE: type_tests/array_test.go
function init (line 3) | func init() {
type structEmpty (line 62) | type structEmpty struct
type arrayAlis (line 63) | type arrayAlis
FILE: type_tests/builtin_test.go
function init (line 3) | func init() {
type boolAlias (line 51) | type boolAlias
type byteAlias (line 52) | type byteAlias
type float32Alias (line 53) | type float32Alias
type float64Alias (line 54) | type float64Alias
type ptrFloat64Alias (line 55) | type ptrFloat64Alias
type int8Alias (line 56) | type int8Alias
type int16Alias (line 57) | type int16Alias
type int32Alias (line 58) | type int32Alias
type ptrInt32Alias (line 59) | type ptrInt32Alias
type int64Alias (line 60) | type int64Alias
type stringAlias (line 61) | type stringAlias
type ptrStringAlias (line 62) | type ptrStringAlias
type uint8Alias (line 63) | type uint8Alias
type uint16Alias (line 64) | type uint16Alias
type uint32Alias (line 65) | type uint32Alias
type uintptrAlias (line 66) | type uintptrAlias
type uintAlias (line 67) | type uintAlias
type uint64Alias (line 68) | type uint64Alias
type intAlias (line 69) | type intAlias
FILE: type_tests/map_key_test.go
function init (line 12) | func init() {
type stringKeyType (line 19) | type stringKeyType
method MarshalText (line 21) | func (k stringKeyType) MarshalText() ([]byte, error) {
method UnmarshalText (line 25) | func (k *stringKeyType) UnmarshalText(text []byte) error {
type structKeyType (line 33) | type structKeyType struct
method MarshalText (line 37) | func (k structKeyType) MarshalText() ([]byte, error) {
method UnmarshalText (line 41) | func (k *structKeyType) UnmarshalText(text []byte) error {
FILE: type_tests/map_test.go
function init (line 3) | func init() {
type structVarious (line 51) | type structVarious struct
FILE: type_tests/marshaler_string_test.go
type StringMarshaler (line 10) | type StringMarshaler
method encode (line 12) | func (m StringMarshaler) encode(str string) string {
method decode (line 24) | func (m StringMarshaler) decode(str string) string {
method MarshalJSON (line 38) | func (m StringMarshaler) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 42) | func (m *StringMarshaler) UnmarshalJSON(text []byte) error {
function init (line 50) | func init() {
FILE: type_tests/marshaler_struct_test.go
type structMarshaler (line 10) | type structMarshaler struct
method encode (line 14) | func (m structMarshaler) encode(str string) string {
method decode (line 26) | func (m structMarshaler) decode(str string) string {
method MarshalJSON (line 40) | func (m structMarshaler) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 44) | func (m *structMarshaler) UnmarshalJSON(text []byte) error {
type structMarshalerAlias (line 52) | type structMarshalerAlias
function init (line 54) | func init() {
FILE: type_tests/slice_test.go
function init (line 3) | func init() {
type jsonMarshaler (line 81) | type jsonMarshaler struct
method MarshalJSON (line 85) | func (p *jsonMarshaler) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 89) | func (p *jsonMarshaler) UnmarshalJSON(input []byte) error {
type jsonMarshalerMap (line 94) | type jsonMarshalerMap
method MarshalJSON (line 96) | func (p *jsonMarshalerMap) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 100) | func (p *jsonMarshalerMap) UnmarshalJSON(input []byte) error {
type textMarshaler (line 104) | type textMarshaler struct
method MarshalText (line 108) | func (p *textMarshaler) MarshalText() ([]byte, error) {
method UnmarshalText (line 112) | func (p *textMarshaler) UnmarshalText(input []byte) error {
type textMarshalerMap (line 117) | type textMarshalerMap
method MarshalText (line 119) | func (p *textMarshalerMap) MarshalText() ([]byte, error) {
method UnmarshalText (line 123) | func (p *textMarshalerMap) UnmarshalText(input []byte) error {
FILE: type_tests/struct_embedded_test.go
function init (line 3) | func init() {
type EmbeddedFloat64 (line 67) | type EmbeddedFloat64
type EmbeddedInt32 (line 68) | type EmbeddedInt32
type EmbeddedMapStringString (line 69) | type EmbeddedMapStringString
type EmbeddedSliceString (line 70) | type EmbeddedSliceString
type EmbeddedString (line 71) | type EmbeddedString
type EmbeddedStruct (line 72) | type EmbeddedStruct struct
type OverlapDifferentLevelsE1 (line 83) | type OverlapDifferentLevelsE1 struct
type OverlapDifferentLevelsE2 (line 87) | type OverlapDifferentLevelsE2 struct
type OverlapDifferentLevels (line 91) | type OverlapDifferentLevels struct
type IgnoreDeeperLevelDoubleEmbedded (line 97) | type IgnoreDeeperLevelDoubleEmbedded struct
type IgnoreDeeperLevelE1 (line 101) | type IgnoreDeeperLevelE1 struct
type IgnoreDeeperLevelE2 (line 106) | type IgnoreDeeperLevelE2 struct
type IgnoreDeeperLevel (line 111) | type IgnoreDeeperLevel struct
type SameLevel1BothTaggedE1 (line 116) | type SameLevel1BothTaggedE1 struct
type SameLevel1BothTaggedE2 (line 120) | type SameLevel1BothTaggedE2 struct
type SameLevel1BothTagged (line 124) | type SameLevel1BothTagged struct
type SameLevel1NoTagsE1 (line 129) | type SameLevel1NoTagsE1 struct
type SameLevel1NoTagsE2 (line 133) | type SameLevel1NoTagsE2 struct
type SameLevel1NoTags (line 137) | type SameLevel1NoTags struct
type SameLevel1TaggedE1 (line 142) | type SameLevel1TaggedE1 struct
type SameLevel1TaggedE2 (line 146) | type SameLevel1TaggedE2 struct
type SameLevel1Tagged (line 150) | type SameLevel1Tagged struct
type SameLevel2BothTaggedDE1 (line 155) | type SameLevel2BothTaggedDE1 struct
type SameLevel2BothTaggedE1 (line 159) | type SameLevel2BothTaggedE1 struct
type SameLevel2BothTaggedDE2 (line 164) | type SameLevel2BothTaggedDE2 struct
type SameLevel2BothTaggedE2 (line 169) | type SameLevel2BothTaggedE2 struct
type SameLevel2BothTagged (line 173) | type SameLevel2BothTagged struct
type SameLevel2NoTagsDE1 (line 178) | type SameLevel2NoTagsDE1 struct
type SameLevel2NoTagsE1 (line 182) | type SameLevel2NoTagsE1 struct
type SameLevel2NoTagsDE2 (line 186) | type SameLevel2NoTagsDE2 struct
type SameLevel2NoTagsE2 (line 190) | type SameLevel2NoTagsE2 struct
type SameLevel2NoTags (line 194) | type SameLevel2NoTags struct
type SameLevel2TaggedDE1 (line 200) | type SameLevel2TaggedDE1 struct
type SameLevel2TaggedE1 (line 205) | type SameLevel2TaggedE1 struct
type SameLevel2TaggedDE2 (line 210) | type SameLevel2TaggedDE2 struct
type SameLevel2TaggedE2 (line 215) | type SameLevel2TaggedE2 struct
type SameLevel2Tagged (line 219) | type SameLevel2Tagged struct
type EmbeddedPtrO1 (line 224) | type EmbeddedPtrO1 struct
type EmbeddedPtrOption (line 228) | type EmbeddedPtrOption struct
type EmbeddedPtr (line 232) | type EmbeddedPtr struct
type UnnamedLiteral (line 236) | type UnnamedLiteral struct
FILE: type_tests/struct_field_case_test.go
function init (line 3) | func init() {
FILE: type_tests/struct_tags_test.go
function init (line 3) | func init() {
type EmbeddedFieldNameS1 (line 156) | type EmbeddedFieldNameS1 struct
type EmbeddedFieldNameS2 (line 161) | type EmbeddedFieldNameS2 struct
type EmbeddedFieldNameS3 (line 166) | type EmbeddedFieldNameS3 struct
type EmbeddedFieldNameS4 (line 171) | type EmbeddedFieldNameS4 struct
type EmbeddedFieldNameS5 (line 176) | type EmbeddedFieldNameS5 struct
type EmbeddedFieldNameS6 (line 181) | type EmbeddedFieldNameS6 struct
type EmbeddedFieldName (line 185) | type EmbeddedFieldName struct
type StringFieldNameE (line 194) | type StringFieldNameE struct
type StringFieldName (line 198) | type StringFieldName struct
type StructFieldNameS1 (line 208) | type StructFieldNameS1 struct
type StructFieldNameS2 (line 212) | type StructFieldNameS2 struct
type StructFieldNameS3 (line 216) | type StructFieldNameS3 struct
type StructFieldNameS4 (line 220) | type StructFieldNameS4 struct
type StructFieldNameS5 (line 224) | type StructFieldNameS5 struct
type StructFieldNameS6 (line 228) | type StructFieldNameS6 struct
type StructFieldName (line 232) | type StructFieldName struct
type EmbeddedOmitEmptyE (line 240) | type EmbeddedOmitEmptyE struct
type EmbeddedOmitEmpty (line 244) | type EmbeddedOmitEmpty struct
type jm (line 248) | type jm
method UnmarshalJSON (line 250) | func (t *jm) UnmarshalJSON(b []byte) error {
method MarshalJSON (line 254) | func (t jm) MarshalJSON() ([]byte, error) {
type tm (line 258) | type tm
method UnmarshalText (line 260) | func (t *tm) UnmarshalText(b []byte) error {
method MarshalText (line 264) | func (t tm) MarshalText() ([]byte, error) {
type sjm (line 268) | type sjm struct
method UnmarshalJSON (line 270) | func (t *sjm) UnmarshalJSON(b []byte) error {
method MarshalJSON (line 274) | func (t sjm) MarshalJSON() ([]byte, error) {
type stm (line 278) | type stm struct
method UnmarshalText (line 280) | func (t *stm) UnmarshalText(b []byte) error {
method MarshalText (line 284) | func (t stm) MarshalText() ([]byte, error) {
FILE: type_tests/struct_test.go
function init (line 5) | func init() {
function structFields1To11 (line 262) | func structFields1To11() {
type struct1 (line 355) | type struct1 struct
type struct1Alias (line 371) | type struct1Alias
type struct2 (line 373) | type struct2 struct
type struct3 (line 376) | type struct3 struct
type withTime (line 382) | type withTime struct
method UnmarshalJSON (line 386) | func (t *withTime) UnmarshalJSON(b []byte) error {
method MarshalJSON (line 389) | func (t withTime) MarshalJSON() ([]byte, error) {
type YetYetAnotherObject (line 393) | type YetYetAnotherObject struct
type YetAnotherObject (line 396) | type YetAnotherObject struct
type AnotherObject (line 399) | type AnotherObject struct
type DeeplyNested (line 402) | type DeeplyNested struct
FILE: type_tests/text_marshaler_string_test.go
function init (line 10) | func init() {
type StringTextMarshaler (line 17) | type StringTextMarshaler
method encode (line 19) | func (m StringTextMarshaler) encode(str string) string {
method decode (line 31) | func (m StringTextMarshaler) decode(str string) string {
method MarshalText (line 46) | func (m StringTextMarshaler) MarshalText() ([]byte, error) {
method UnmarshalText (line 51) | func (m *StringTextMarshaler) UnmarshalText(text []byte) error {
FILE: type_tests/text_marshaler_struct_test.go
function init (line 10) | func init() {
type structTextMarshaler (line 27) | type structTextMarshaler struct
method encode (line 31) | func (m structTextMarshaler) encode(str string) string {
method decode (line 43) | func (m structTextMarshaler) decode(str string) string {
method MarshalText (line 57) | func (m structTextMarshaler) MarshalText() ([]byte, error) {
method UnmarshalText (line 61) | func (m *structTextMarshaler) UnmarshalText(text []byte) error {
type structTextMarshalerAlias (line 69) | type structTextMarshalerAlias
FILE: type_tests/type_test.go
type selectedSymmetricCase (line 18) | type selectedSymmetricCase struct
function Test_symmetric (line 22) | func Test_symmetric(t *testing.T) {
function Test_asymmetric (line 84) | func Test_asymmetric(t *testing.T) {
constant indentStr (line 138) | indentStr = "> "
function fingerprint (line 140) | func fingerprint(obj interface{}) string {
function dump (line 148) | func dump(obj interface{}) string {
function indent (line 155) | func indent(src []byte, prefix string) string {
FILE: value_tests/array_test.go
function init (line 3) | func init() {
FILE: value_tests/bool_test.go
function init (line 3) | func init() {
FILE: value_tests/eface_test.go
function init (line 3) | func init() {
FILE: value_tests/error_test.go
function Test_errorInput (line 10) | func Test_errorInput(t *testing.T) {
FILE: value_tests/float_test.go
function Test_read_float (line 14) | func Test_read_float(t *testing.T) {
function Test_write_float32 (line 54) | func Test_write_float32(t *testing.T) {
function Test_write_float64 (line 95) | func Test_write_float64(t *testing.T) {
FILE: value_tests/iface_test.go
function init (line 5) | func init() {
type strCloser1 (line 35) | type strCloser1
method Close (line 37) | func (closer strCloser1) Close() error {
type strCloser2 (line 41) | type strCloser2
method Close (line 43) | func (closer *strCloser2) Close() error {
FILE: value_tests/int_test.go
function init (line 12) | func init() {
function Test_int8 (line 47) | func Test_int8(t *testing.T) {
function Test_read_int16 (line 60) | func Test_read_int16(t *testing.T) {
function Test_read_int32 (line 73) | func Test_read_int32(t *testing.T) {
function Test_read_int_overflow (line 93) | func Test_read_int_overflow(t *testing.T) {
function Test_read_int64 (line 141) | func Test_read_int64(t *testing.T) {
function Test_write_uint8 (line 161) | func Test_write_uint8(t *testing.T) {
function Test_write_int8 (line 193) | func Test_write_int8(t *testing.T) {
function Test_write_uint16 (line 225) | func Test_write_uint16(t *testing.T) {
function Test_write_int16 (line 257) | func Test_write_int16(t *testing.T) {
function Test_write_uint32 (line 289) | func Test_write_uint32(t *testing.T) {
function Test_write_int32 (line 321) | func Test_write_int32(t *testing.T) {
function Test_write_uint64 (line 353) | func Test_write_uint64(t *testing.T) {
function Test_write_int64 (line 387) | func Test_write_int64(t *testing.T) {
FILE: value_tests/invalid_test.go
function Test_missing_object_end (line 13) | func Test_missing_object_end(t *testing.T) {
function Test_missing_array_end (line 23) | func Test_missing_array_end(t *testing.T) {
function Test_invalid_any (line 28) | func Test_invalid_any(t *testing.T) {
function Test_invalid_struct_input (line 50) | func Test_invalid_struct_input(t *testing.T) {
function Test_invalid_slice_input (line 58) | func Test_invalid_slice_input(t *testing.T) {
function Test_invalid_array_input (line 66) | func Test_invalid_array_input(t *testing.T) {
function Test_invalid_float (line 74) | func Test_invalid_float(t *testing.T) {
function Test_chan (line 105) | func Test_chan(t *testing.T) {
function Test_invalid_in_map (line 128) | func Test_invalid_in_map(t *testing.T) {
function Test_invalid_number (line 146) | func Test_invalid_number(t *testing.T) {
function Test_valid (line 162) | func Test_valid(t *testing.T) {
function Test_nil_pointer (line 168) | func Test_nil_pointer(t *testing.T) {
function Test_func_pointer_type (line 179) | func Test_func_pointer_type(t *testing.T) {
function TestEOF (line 216) | func TestEOF(t *testing.T) {
function TestDecodeErrorType (line 222) | func TestDecodeErrorType(t *testing.T) {
function Test_decode_slash (line 229) | func Test_decode_slash(t *testing.T) {
function Test_NilInput (line 236) | func Test_NilInput(t *testing.T) {
function Test_EmptyInput (line 245) | func Test_EmptyInput(t *testing.T) {
type Foo (line 254) | type Foo struct
function Test_nil_any (line 258) | func Test_nil_any(t *testing.T) {
FILE: value_tests/map_test.go
function init (line 10) | func init() {
type MyInterface (line 65) | type MyInterface interface
type MyString (line 69) | type MyString
method Hello (line 71) | func (ms MyString) Hello() string {
type Date (line 75) | type Date struct
method UnmarshalJSON (line 79) | func (d *Date) UnmarshalJSON(b []byte) error {
method MarshalJSON (line 95) | func (d *Date) MarshalJSON() ([]byte, error) {
type Date2 (line 99) | type Date2 struct
method UnmarshalJSON (line 103) | func (d Date2) UnmarshalJSON(b []byte) error {
method MarshalJSON (line 119) | func (d Date2) MarshalJSON() ([]byte, error) {
type customKey (line 123) | type customKey
method MarshalText (line 125) | func (c customKey) MarshalText() ([]byte, error) {
method UnmarshalText (line 129) | func (c *customKey) UnmarshalText(value []byte) error {
FILE: value_tests/marshaler_test.go
function init (line 8) | func init() {
type jmOfStruct (line 38) | type jmOfStruct struct
method MarshalJSON (line 42) | func (q jmOfStruct) MarshalJSON() ([]byte, error) {
method UnmarshalJSON (line 46) | func (q *jmOfStruct) UnmarshalJSON(value []byte) error {
type tmOfStruct (line 50) | type tmOfStruct struct
method MarshalText (line 54) | func (q tmOfStruct) MarshalText() ([]byte, error) {
method UnmarshalText (line 58) | func (q *tmOfStruct) UnmarshalText(value []byte) error {
type tmOfStructInt (line 62) | type tmOfStructInt struct
method MarshalText (line 66) | func (q *tmOfStructInt) MarshalText() ([]byte, error) {
method UnmarshalText (line 70) | func (q *tmOfStructInt) UnmarshalText(value []byte) error {
type tmOfMap (line 74) | type tmOfMap
method UnmarshalText (line 76) | func (q tmOfMap) UnmarshalText(value []byte) error {
type tmOfMapPtr (line 80) | type tmOfMapPtr
method UnmarshalText (line 82) | func (q *tmOfMapPtr) UnmarshalText(value []byte) error {
FILE: value_tests/number_test.go
function init (line 5) | func init() {
FILE: value_tests/ptr_114_test.go
function init (line 5) | func init() {
FILE: value_tests/ptr_test.go
function init (line 3) | func init() {
FILE: value_tests/raw_message_test.go
function init (line 7) | func init() {
FILE: value_tests/slice_test.go
function init (line 3) | func init() {
FILE: value_tests/string_test.go
function init (line 10) | func init() {
function Test_read_string (line 21) | func Test_read_string(t *testing.T) {
function testReadString (line 77) | func testReadString(t *testing.T, input string, expectValue string, expe...
FILE: value_tests/struct_test.go
function init (line 9) | func init() {
type StructVarious (line 210) | type StructVarious struct
type structRecursive (line 216) | type structRecursive struct
type omit (line 221) | type omit
type CacheItem (line 222) | type CacheItem struct
type orderA (line 227) | type orderA struct
type orderC (line 231) | type orderC struct
type orderB (line 235) | type orderB struct
type structOrder (line 241) | type structOrder struct
FILE: value_tests/value_test.go
type unmarshalCase (line 12) | type unmarshalCase struct
type selectedMarshalCase (line 25) | type selectedMarshalCase struct
function Test_unmarshal (line 29) | func Test_unmarshal(t *testing.T) {
function Test_marshal (line 58) | func Test_marshal(t *testing.T) {
Condensed preview — 138 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (536K chars).
[
{
"path": ".codecov.yml",
"chars": 33,
"preview": "ignore:\n - \"output_tests/.*\"\n\n"
},
{
"path": ".gitignore",
"chars": 42,
"preview": "/vendor\n/bug_test.go\n/coverage.txt\n/.idea\n"
},
{
"path": ".travis.yml",
"chars": 159,
"preview": "language: go\n\ngo:\n - 1.8.x\n - 1.x\n\nbefore_install:\n - go get -t -v ./...\n\nscript:\n - ./test.sh\n\nafter_success:\n - b"
},
{
"path": "Gopkg.toml",
"chars": 712,
"preview": "# Gopkg.toml example\n#\n# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md\n# for detailed Gopkg.toml"
},
{
"path": "LICENSE",
"chars": 1070,
"preview": "MIT License\n\nCopyright (c) 2016 json-iterator\n\nPermission is hereby granted, free of charge, to any person obtaining a c"
},
{
"path": "README.md",
"chars": 2933,
"preview": "[](https://sourcegraph.com/github.com/jso"
},
{
"path": "adapter.go",
"chars": 4598,
"preview": "package jsoniter\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n// RawMessage to make replace json with jsoniter\ntype RawMessage []byte\n\n//"
},
{
"path": "any.go",
"chars": 7195,
"preview": "package jsoniter\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/modern-go/reflect2\"\n\t\"io\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"unsafe\"\n)\n\n//"
},
{
"path": "any_array.go",
"chars": 4838,
"preview": "package jsoniter\n\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype arrayLazyAny struct {\n\tbaseAny\n\tcfg *frozenConfig\n\tbuf []byte\n\te"
},
{
"path": "any_bool.go",
"chars": 1882,
"preview": "package jsoniter\n\ntype trueAny struct {\n\tbaseAny\n}\n\nfunc (any *trueAny) LastError() error {\n\treturn nil\n}\n\nfunc (any *tr"
},
{
"path": "any_float.go",
"chars": 1252,
"preview": "package jsoniter\n\nimport (\n\t\"strconv\"\n)\n\ntype floatAny struct {\n\tbaseAny\n\tval float64\n}\n\nfunc (any *floatAny) Parse() *I"
},
{
"path": "any_int32.go",
"chars": 1142,
"preview": "package jsoniter\n\nimport (\n\t\"strconv\"\n)\n\ntype int32Any struct {\n\tbaseAny\n\tval int32\n}\n\nfunc (any *int32Any) LastError() "
},
{
"path": "any_int64.go",
"chars": 1135,
"preview": "package jsoniter\n\nimport (\n\t\"strconv\"\n)\n\ntype int64Any struct {\n\tbaseAny\n\tval int64\n}\n\nfunc (any *int64Any) LastError() "
},
{
"path": "any_invalid.go",
"chars": 1362,
"preview": "package jsoniter\n\nimport \"fmt\"\n\ntype invalidAny struct {\n\tbaseAny\n\terr error\n}\n\nfunc newInvalidAny(path []interface{}) *"
},
{
"path": "any_nil.go",
"chars": 916,
"preview": "package jsoniter\n\ntype nilAny struct {\n\tbaseAny\n}\n\nfunc (any *nilAny) LastError() error {\n\treturn nil\n}\n\nfunc (any *nilA"
},
{
"path": "any_number.go",
"chars": 2616,
"preview": "package jsoniter\n\nimport (\n\t\"io\"\n\t\"unsafe\"\n)\n\ntype numberLazyAny struct {\n\tbaseAny\n\tcfg *frozenConfig\n\tbuf []byte\n\terr e"
},
{
"path": "any_object.go",
"chars": 6937,
"preview": "package jsoniter\n\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype objectLazyAny struct {\n\tbaseAny\n\tcfg *frozenConfig\n\tbuf []byte\n\t"
},
{
"path": "any_str.go",
"chars": 2893,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype stringAny struct {\n\tbaseAny\n\tval string\n}\n\nfunc (any *stringAny) Ge"
},
{
"path": "any_tests/jsoniter_any_array_test.go",
"chars": 3745,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Te"
},
{
"path": "any_tests/jsoniter_any_bool_test.go",
"chars": 1348,
"preview": "package any_tests\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n"
},
{
"path": "any_tests/jsoniter_any_float_test.go",
"chars": 2091,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar flo"
},
{
"path": "any_tests/jsoniter_any_int_test.go",
"chars": 5459,
"preview": "package any_tests\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n"
},
{
"path": "any_tests/jsoniter_any_map_test.go",
"chars": 772,
"preview": "package any_tests\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Tes"
},
{
"path": "any_tests/jsoniter_any_null_test.go",
"chars": 355,
"preview": "package any_tests\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Tes"
},
{
"path": "any_tests/jsoniter_any_object_test.go",
"chars": 3607,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Te"
},
{
"path": "any_tests/jsoniter_any_string_test.go",
"chars": 1597,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar str"
},
{
"path": "any_tests/jsoniter_must_be_valid_test.go",
"chars": 1944,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n// if m"
},
{
"path": "any_tests/jsoniter_wrap_test.go",
"chars": 3509,
"preview": "package any_tests\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Te"
},
{
"path": "any_uint32.go",
"chars": 1160,
"preview": "package jsoniter\n\nimport (\n\t\"strconv\"\n)\n\ntype uint32Any struct {\n\tbaseAny\n\tval uint32\n}\n\nfunc (any *uint32Any) LastError"
},
{
"path": "any_uint64.go",
"chars": 1154,
"preview": "package jsoniter\n\nimport (\n\t\"strconv\"\n)\n\ntype uint64Any struct {\n\tbaseAny\n\tval uint64\n}\n\nfunc (any *uint64Any) LastError"
},
{
"path": "api_tests/config_test.go",
"chars": 5465,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require"
},
{
"path": "api_tests/decoder_test.go",
"chars": 1796,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t"
},
{
"path": "api_tests/encoder_18_test.go",
"chars": 1140,
"preview": "//+build go1.8\n\npackage test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\t\"unicode/utf8\"\n\n\t\"github.com/json-iterator/"
},
{
"path": "api_tests/encoder_test.go",
"chars": 466,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t"
},
{
"path": "api_tests/marshal_indent_test.go",
"chars": 1068,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\""
},
{
"path": "api_tests/marshal_json_escape_test.go",
"chars": 918,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\tjsoniter \"github.com/json-iterator/go\"\n\t\"github.com/stretc"
},
{
"path": "api_tests/marshal_json_test.go",
"chars": 671,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"testing\"\n\t\"github.com/stretchr/testify"
},
{
"path": "benchmarks/encode_string_test.go",
"chars": 463,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"github.com/json-iterator/go\"\n\t\"testing\"\n)\n\nfunc Benchmark_encode_string_with_SetEscape"
},
{
"path": "benchmarks/jsoniter_large_file_test.go",
"chars": 3691,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n//func Test_larg"
},
{
"path": "benchmarks/stream_test.go",
"chars": 6687,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"strconv\"\n\t\"testing\"\n\n\tjsoniter \"github.com/json-iterator/go\"\n)\n\nfunc Benchmark_stream_"
},
{
"path": "build.sh",
"chars": 381,
"preview": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n mkdir -p /tmp/build-gola"
},
{
"path": "config.go",
"chars": 10545,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"reflect\"\n\t\"sync\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/concurrent\"\n\t\"git"
},
{
"path": "example_test.go",
"chars": 2627,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc ExampleMarshal() {\n\ttype ColorGroup struct {\n\t\tID int\n\t\tN"
},
{
"path": "extension_tests/decoder_test.go",
"chars": 5111,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"strconv\"\n"
},
{
"path": "extension_tests/extension_test.go",
"chars": 2985,
"preview": "package test\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/modern-go/reflect2\"\n\t\"github.com/stretchr/testify/req"
},
{
"path": "extra/binary_as_string_codec.go",
"chars": 5048,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/modern-go/reflect2\"\n\t\"unicode/utf8\"\n\t\"unsafe\"\n)\n\n// "
},
{
"path": "extra/binary_as_string_codec_test.go",
"chars": 837,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc init() "
},
{
"path": "extra/fuzzy_decoder.go",
"chars": 8492,
"preview": "package extra\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"math\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com/json-iterator/go\"\n\t"
},
{
"path": "extra/fuzzy_decoder_test.go",
"chars": 12469,
"preview": "package extra\n\nimport (\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc init()"
},
{
"path": "extra/naming_strategy.go",
"chars": 1515,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// SetNamingStrategy rename struct field"
},
{
"path": "extra/naming_strategy_test.go",
"chars": 1736,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Test_lo"
},
{
"path": "extra/privat_fields.go",
"chars": 1388,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// SupportPrivateFields include private "
},
{
"path": "extra/private_fields_test.go",
"chars": 372,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n)\n\nfunc Test_pr"
},
{
"path": "extra/time_as_int64_codec.go",
"chars": 956,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n// RegisterTimeAsInt64Codec encode/decode ti"
},
{
"path": "extra/time_as_int64_codec_test.go",
"chars": 857,
"preview": "package extra\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc"
},
{
"path": "fuzzy_mode_convert_table.md",
"chars": 927,
"preview": "| json type \\ dest type | bool | int | uint | float |string|\n| --- | --- | --- | --- |--|--|\n| number | positive => true"
},
{
"path": "go.mod",
"chars": 267,
"preview": "module github.com/json-iterator/go\n\ngo 1.12\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1\n\tgithub.com/google/gofuzz v1.0"
},
{
"path": "go.sum",
"chars": 1922,
"preview": "github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1"
},
{
"path": "iter.go",
"chars": 7897,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n)\n\n// ValueType the type for JSON element\ntype ValueType int\n\nc"
},
{
"path": "iter_array.go",
"chars": 1402,
"preview": "package jsoniter\n\n// ReadArray read array element, tells if the array has more element to read.\nfunc (iter *Iterator) Re"
},
{
"path": "iter_float.go",
"chars": 7641,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"math/big\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\nvar floatDigits []int8\n"
},
{
"path": "iter_int.go",
"chars": 8769,
"preview": "package jsoniter\n\nimport (\n\t\"math\"\n\t\"strconv\"\n)\n\nvar intDigits []int8\n\nconst uint32SafeToMultiply10 = uint32(0xffffffff)"
},
{
"path": "iter_object.go",
"chars": 6362,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// ReadObject read one field from object.\n// If object ended, returns em"
},
{
"path": "iter_skip.go",
"chars": 3429,
"preview": "package jsoniter\n\nimport \"fmt\"\n\n// ReadNil reads a json object as nil and\n// returns whether it's a nil or not\nfunc (ite"
},
{
"path": "iter_skip_sloppy.go",
"chars": 3255,
"preview": "//+build jsoniter_sloppy\n\npackage jsoniter\n\n// sloppy but faster implementation, do not validate the input json\n\nfunc (i"
},
{
"path": "iter_skip_sloppy_test.go",
"chars": 3166,
"preview": "//+build jsoniter_sloppy\n\npackage jsoniter\n\nimport (\n\t\"github.com/stretchr/testify/require\"\n\t\"io\"\n\t\"testing\"\n)\n\nfunc Tes"
},
{
"path": "iter_skip_strict.go",
"chars": 2002,
"preview": "//+build !jsoniter_sloppy\n\npackage jsoniter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nfunc (iter *Iterator) skipNumber() {\n\tif !iter.try"
},
{
"path": "iter_str.go",
"chars": 4821,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"unicode/utf16\"\n)\n\n// ReadString read string from iterator\nfunc (iter *Iterator) Read"
},
{
"path": "jsoniter.go",
"chars": 884,
"preview": "// Package jsoniter implements encoding and decoding of JSON as defined in\n// RFC 4627 and provides interfaces with iden"
},
{
"path": "misc_tests/jsoniter_array_test.go",
"chars": 6154,
"preview": "package misc_tests\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/"
},
{
"path": "misc_tests/jsoniter_bool_test.go",
"chars": 1170,
"preview": "package misc_tests\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n"
},
{
"path": "misc_tests/jsoniter_float_test.go",
"chars": 3207,
"preview": "package misc_tests\n\nimport (\n\t\"encoding/json\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/t"
},
{
"path": "misc_tests/jsoniter_int_test.go",
"chars": 4576,
"preview": "// +build go1.8\n\npackage misc_tests\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"tes"
},
{
"path": "misc_tests/jsoniter_interface_test.go",
"chars": 4086,
"preview": "package misc_tests\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"io"
},
{
"path": "misc_tests/jsoniter_iterator_test.go",
"chars": 30516,
"preview": "package misc_tests\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"gi"
},
{
"path": "misc_tests/jsoniter_map_test.go",
"chars": 2436,
"preview": "package misc_tests\n\nimport (\n\t\"encoding/json\"\n\t\"math/big\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretc"
},
{
"path": "misc_tests/jsoniter_nested_test.go",
"chars": 7121,
"preview": "package misc_tests\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\ntype Le"
},
{
"path": "misc_tests/jsoniter_null_test.go",
"chars": 2080,
"preview": "package misc_tests\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/req"
},
{
"path": "misc_tests/jsoniter_object_test.go",
"chars": 9243,
"preview": "package misc_tests\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testif"
},
{
"path": "misc_tests/jsoniter_raw_message_test.go",
"chars": 3347,
"preview": "package misc_tests\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"st"
},
{
"path": "pool.go",
"chars": 956,
"preview": "package jsoniter\n\nimport (\n\t\"io\"\n)\n\n// IteratorPool a thread safe pool of iterators with same configuration\ntype Iterato"
},
{
"path": "reflect.go",
"chars": 8737,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/reflect2\"\n)\n\n// ValDecoder is an internal"
},
{
"path": "reflect_array.go",
"chars": 2652,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"github.com/modern-go/reflect2\"\n\t\"io\"\n\t\"unsafe\"\n)\n\nfunc decoderOfArray(ctx *ctx, typ "
},
{
"path": "reflect_dynamic.go",
"chars": 1458,
"preview": "package jsoniter\n\nimport (\n\t\"github.com/modern-go/reflect2\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype dynamicEncoder struct {\n\tvalTyp"
},
{
"path": "reflect_extension.go",
"chars": 14584,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"github.com/modern-go/reflect2\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unsafe\"\n)\n"
},
{
"path": "reflect_json_number.go",
"chars": 2694,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/modern-go/reflect2\"\n\t\"strconv\"\n\t\"unsafe\"\n)\n\ntype Number string\n"
},
{
"path": "reflect_json_raw_message.go",
"chars": 1842,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/modern-go/reflect2\"\n\t\"unsafe\"\n)\n\nvar jsonRawMessageType = refle"
},
{
"path": "reflect_map.go",
"chars": 9212,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"sort\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/reflect2\"\n)\n\nfunc decoderOf"
},
{
"path": "reflect_marshaler.go",
"chars": 5964,
"preview": "package jsoniter\n\nimport (\n\t\"encoding\"\n\t\"encoding/json\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/reflect2\"\n)\n\nvar marshalerType"
},
{
"path": "reflect_native.go",
"chars": 11153,
"preview": "package jsoniter\n\nimport (\n\t\"encoding/base64\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/reflect2\"\n)\n\nconst"
},
{
"path": "reflect_optional.go",
"chars": 3373,
"preview": "package jsoniter\n\nimport (\n\t\"github.com/modern-go/reflect2\"\n\t\"unsafe\"\n)\n\nfunc decoderOfOptional(ctx *ctx, typ reflect2.T"
},
{
"path": "reflect_slice.go",
"chars": 2662,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"github.com/modern-go/reflect2\"\n\t\"io\"\n\t\"unsafe\"\n)\n\nfunc decoderOfSlice(ctx *ctx, typ "
},
{
"path": "reflect_struct_decoder.go",
"chars": 29987,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com/modern-go/reflect2\"\n)\n\nfunc decoderOfStruct(c"
},
{
"path": "reflect_struct_encoder.go",
"chars": 5295,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"github.com/modern-go/reflect2\"\n\t\"io\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nfunc encoderOfStruct(ct"
},
{
"path": "skip_tests/array_test.go",
"chars": 322,
"preview": "package skip_tests\n\nfunc init() {\n\ttestCases = append(testCases, testCase{\n\t\tptr: (*[]interface{})(nil),\n\t\tinputs: []str"
},
{
"path": "skip_tests/float64_test.go",
"chars": 406,
"preview": "package skip_tests\n\nfunc init() {\n\ttestCases = append(testCases, testCase{\n\t\tptr: (*float64)(nil),\n\t\tinputs: []string{\n\t"
},
{
"path": "skip_tests/jsoniter_skip_test.go",
"chars": 4755,
"preview": "package skip_tests\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/"
},
{
"path": "skip_tests/skip_test.go",
"chars": 919,
"preview": "package skip_tests\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/req"
},
{
"path": "skip_tests/string_test.go",
"chars": 331,
"preview": "package skip_tests\n\nfunc init() {\n\ttestCases = append(testCases, testCase{\n\t\tptr: (*string)(nil),\n\t\tinputs: []string{\n\t\t"
},
{
"path": "skip_tests/struct_test.go",
"chars": 563,
"preview": "package skip_tests\n\nfunc init() {\n\ttestCases = append(testCases, testCase{\n\t\tptr: (*struct{})(nil),\n\t\tinputs: []string{\n"
},
{
"path": "stream.go",
"chars": 5287,
"preview": "package jsoniter\n\nimport (\n\t\"io\"\n)\n\n// stream is a io.Writer like object, with JSON specific write functions.\n// Error i"
},
{
"path": "stream_float.go",
"chars": 3222,
"preview": "package jsoniter\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n)\n\nvar pow10 []uint64\n\nfunc init() {\n\tpow10 = []uint64{1, 10, 100, "
},
{
"path": "stream_int.go",
"chars": 4580,
"preview": "package jsoniter\n\nvar digits []uint32\n\nfunc init() {\n\tdigits = make([]uint32, 1000)\n\tfor i := uint32(0); i < 1000; i++ {"
},
{
"path": "stream_str.go",
"chars": 7986,
"preview": "package jsoniter\n\nimport (\n\t\"unicode/utf8\"\n)\n\n// htmlSafeSet holds the value true if the ASCII character with the given\n"
},
{
"path": "stream_test.go",
"chars": 2381,
"preview": "package jsoniter\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Test_writeByte_should_grow_buffer("
},
{
"path": "test.sh",
"chars": 285,
"preview": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n go test -coverpro"
},
{
"path": "type_tests/array_test.go",
"chars": 1224,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*[4]bool)(nil),\n\t\t(*[4]byte)(nil),\n\t\t(*[4]float64)(nil),\n\t"
},
{
"path": "type_tests/builtin_test.go",
"chars": 1492,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*bool)(nil),\n\t\t(*boolAlias)(nil),\n\t\t(*byte)(nil),\n\t\t(*byte"
},
{
"path": "type_tests/map_key_test.go",
"chars": 1053,
"preview": "// +build go1.15\n// remove these tests temporarily until https://github.com/golang/go/issues/38105 and\n// https://github"
},
{
"path": "type_tests/map_test.go",
"chars": 1359,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*map[int8]string)(nil),\n\t\t(*map[int16]string)(nil),\n\t\t(*ma"
},
{
"path": "type_tests/marshaler_string_test.go",
"chars": 1132,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype StringMarshaler string\n\nfunc (m S"
},
{
"path": "type_tests/marshaler_struct_test.go",
"chars": 1337,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype structMarshaler struct {\n\tX strin"
},
{
"path": "type_tests/slice_test.go",
"chars": 2476,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*[][4]bool)(nil),\n\t\t(*[][4]byte)(nil),\n\t\t(*[][4]float64)(n"
},
{
"path": "type_tests/struct_embedded_test.go",
"chars": 3760,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*struct {\n\t\t\tEmbeddedFloat64\n\t\t})(nil),\n\t\t(*struct {\n\t\t\tEm"
},
{
"path": "type_tests/struct_field_case_test.go",
"chars": 426,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*struct {\n\t\t\tUpper bool `json:\"M\"`\n\t\t\tLower bool `json:\"m\""
},
{
"path": "type_tests/struct_tags_test.go",
"chars": 5484,
"preview": "package test\n\nfunc init() {\n\ttestCases = append(testCases,\n\t\t(*EmbeddedFieldName)(nil),\n\t\t(*StringFieldName)(nil),\n\t\t(*S"
},
{
"path": "type_tests/struct_test.go",
"chars": 5823,
"preview": "package test\n\nimport \"time\"\n\nfunc init() {\n\tstructFields1To11()\n\ttestCases = append(testCases,\n\t\t(*struct1Alias)(nil),\n\t"
},
{
"path": "type_tests/text_marshaler_string_test.go",
"chars": 1243,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding\"\n\t\"encoding/base64\"\n\t\"strings\"\n)\n\nfunc init() {\n\ttestCases = append(testCases"
},
{
"path": "type_tests/text_marshaler_struct_test.go",
"chars": 1374,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding\"\n\t\"encoding/base64\"\n\t\"strings\"\n)\n\nfunc init() {\n\ttestCases = append(testCases"
},
{
"path": "type_tests/type_test.go",
"chars": 4966,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/davecgh/go-spew/spew\"\n\t\"github.com/google/gofuzz\"\n\t"
},
{
"path": "value_tests/array_test.go",
"chars": 367,
"preview": "package test\n\nfunc init() {\n\ttwo := float64(2)\n\tmarshalCases = append(marshalCases,\n\t\t[1]*float64{nil},\n\t\t[1]*float64{&t"
},
{
"path": "value_tests/bool_test.go",
"chars": 176,
"preview": "package test\n\nfunc init() {\n\tunmarshalCases = append(unmarshalCases, unmarshalCase{\n\t\tptr: (*struct {\n\t\t\tField bool `jso"
},
{
"path": "value_tests/eface_test.go",
"chars": 1484,
"preview": "package test\n\nfunc init() {\n\tvar pEFace = func(val interface{}) *interface{} {\n\t\treturn &val\n\t}\n\tvar pInt = func(val int"
},
{
"path": "value_tests/error_test.go",
"chars": 730,
"preview": "package test\n\nimport (\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfu"
},
{
"path": "value_tests/float_test.go",
"chars": 4257,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\tjsoniter \"github.com/json-iterator/go\"\n\t"
},
{
"path": "value_tests/iface_test.go",
"chars": 812,
"preview": "package test\n\nimport \"io\"\n\nfunc init() {\n\tvar pCloser1 = func(str string) *io.Closer {\n\t\tcloser := io.Closer(strCloser1("
},
{
"path": "value_tests/int_test.go",
"chars": 12950,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/require\"\n\t\"strconv\"\n"
},
{
"path": "value_tests/invalid_test.go",
"chars": 6984,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/stretchr/testify/assert\"\n\t\""
},
{
"path": "value_tests/map_test.go",
"chars": 2577,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"time\"\n)\n\nfunc init() {\n\tvar pRawMessage = func(val json.Raw"
},
{
"path": "value_tests/marshaler_test.go",
"chars": 1415,
"preview": "package test\n\nimport (\n\t\"encoding\"\n\t\"encoding/json\"\n)\n\nfunc init() {\n\tjm := json.Marshaler(jmOfStruct{})\n\ttm1 := encodin"
},
{
"path": "value_tests/number_test.go",
"chars": 345,
"preview": "package test\n\nimport \"encoding/json\"\n\nfunc init() {\n\tunmarshalCases = append(unmarshalCases, unmarshalCase{\n\t\tptr: (*j"
},
{
"path": "value_tests/ptr_114_test.go",
"chars": 212,
"preview": "// +build go1.14\n\npackage test\n\nfunc init() {\n\tunmarshalCases = append(unmarshalCases, unmarshalCase{\n\t\tobj: func() inte"
},
{
"path": "value_tests/ptr_test.go",
"chars": 486,
"preview": "package test\n\nfunc init() {\n\tvar pInt = func(val int) *int {\n\t\treturn &val\n\t}\n\tmarshalCases = append(marshalCases,\n\t\t(*i"
},
{
"path": "value_tests/raw_message_test.go",
"chars": 524,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n)\n\nfunc init() {\n\tmarshalCases = append(marshalCases,\n\t\tjson.RawMessage(\"{}\"),\n\t"
},
{
"path": "value_tests/slice_test.go",
"chars": 543,
"preview": "package test\n\nfunc init() {\n\tnilSlice := []string(nil)\n\tmarshalCases = append(marshalCases,\n\t\t[]interface{}{\"hello\"},\n\t\t"
},
{
"path": "value_tests/string_test.go",
"chars": 2635,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/json-iterator/go\"\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nfunc init() {\n\tmars"
},
{
"path": "value_tests/struct_test.go",
"chars": 4496,
"preview": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"time\"\n)\n\nfunc init() {\n\tvar pString = func(val string) *string {\n\t\tre"
},
{
"path": "value_tests/value_test.go",
"chars": 1955,
"preview": "package test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/json-iterator/go\"\n\t\"github.com/modern-go/reflect2\"\n\t\"github."
}
]
About this extraction
This page contains the full source code of the json-iterator/go GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 138 files (469.3 KB), approximately 140.1k tokens, and a symbol index with 1425 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.