Movatterモバイル変換


[0]ホーム

URL:


jx

packagemodule
v1.1.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2023 License:MITImports:15Imported by:339

Details

Repository

github.com/go-faster/jx

Links

README

jxstable

Package jx implements encoding and decoding of json [RFC 7159].Lightweight fork ofjsoniter.

go get github.com/go-faster/jx

Features

  • Mostly zero-allocation and highly optimized
  • Directly encode and decode json values
  • No reflect orinterface{}
  • Pools and direct buffer access for less (or none) allocations
  • Multi-pass decoding
  • Validation

Seeusage for examples. Mostly suitable for fast low-level json manipulationwith high control, for dynamic parsing and encoding of unstructured data. Used inogen project forjson (un)marshaling code generation based on json and OpenAPI schemas.

For example, we have following OpenTelemetry log entry:

{  "Timestamp": "1586960586000000000",  "Attributes": {    "http.status_code": 500,    "http.url": "http://example.com",    "my.custom.application.tag": "hello"  },  "Resource": {    "service.name": "donut_shop",    "service.version": "2.0.0",    "k8s.pod.uid": "1138528c-c36e-11e9-a1a7-42010a800198"  },  "TraceId": "13e2a0921288b3ff80df0a0482d4fc46",  "SpanId": "43222c2d51a7abe3",  "SeverityText": "INFO",  "SeverityNumber": 9,  "Body": "20200415T072306-0700 INFO I like donuts"}

Flexibility ofjx enables highly efficient semantic-aware encoding and decoding,e.g. using[16]byte forTraceId with zero-allocationhex encoding in json:

NameSpeedAllocations
Decode1279 MB/s0 allocs/op
Validate1914 MB/s0 allocs/op
Encode1202 MB/s0 allocs/op
Write2055 MB/s0 allocs/op

cpu: AMD Ryzen 9 7950X

Seeotel_test.go for example.

Why

Most ofjsoniter issues are caused by necessityto be drop-in replacement for standardencoding/json. Removing such constrains greatlysimplified implementation and reduced scope, allowing to focus on json stream processing.

  • Commas are handled automatically while encoding
  • Raw json, Number and Base64 support
  • Reduced scope
    • No reflection
    • Noencoding/json adapter
    • 3.5x less code (8.5K to 2.4K SLOC)
  • Fuzzing, improved test coverage
  • Drastically refactored and simplified
    • Explicit error returns
    • NoConfig orAPI

Usage

Decode

Usejx.Decoder. Zero value is valid,but constructors are available for convenience:

To reuse decoders and their buffers, usejx.GetDecoderandjx.PutDecoder alongside with reset functions:

Decoder is reset onPutDecoder.

d := jx.DecodeStr(`{"values":[4,8,15,16,23,42]}`)// Save all integers from "values" array to slice.var values []int// Iterate over each object field.if err := d.Obj(func(d *jx.Decoder, key string) error {    switch key {    case "values":        // Iterate over each array element.        return d.Arr(func(d *jx.Decoder) error {            v, err := d.Int()            if err != nil {                return err            }            values = append(values, v)            return nil        })    default:        // Skip unknown fields if any.        return d.Skip()    }}); err != nil {    panic(err)}fmt.Println(values)// Output: [4 8 15 16 23 42]
Encode

Usejx.Encoder. Zero value is valid, reuse withjx.GetEncoder,jx.PutEncoder andjx.Encoder.Reset(). Encoder is reset onPutEncoder.

var e jx.Encodere.ObjStart()           // {e.FieldStart("values") // "values":e.ArrStart()           // [for _, v := range []int{4, 8, 15, 16, 23, 42} {    e.Int(v)}e.ArrEnd() // ]e.ObjEnd() // }fmt.Println(e)fmt.Println("Buffer len:", len(e.Bytes()))// Output: {"values":[4,8,15,16,23,42]}// Buffer len: 28
Writer

Usejx.Writer for low level json writing.

No automatic commas or indentation for lowest possible overhead, useful for code generated json encoding.

Raw

Usejx.Decoder.Raw to read raw json values, similar tojson.RawMessage.

d := jx.DecodeStr(`{"foo": [1, 2, 3]}`)var raw jx.Rawif err := d.Obj(func(d *jx.Decoder, key string) error {    v, err := d.Raw()    if err != nil {        return err    }    raw = v    return nil}); err != nil {    panic(err)}fmt.Println(raw.Type(), raw)// Output:// array [1, 2, 3]
Number

Usejx.Decoder.Num to read numbers, similar tojson.Number.Also supports number strings, like"12345", which is common compatible way to representuint64.

d := jx.DecodeStr(`{"foo": "10531.0"}`)var n jx.Numif err := d.Obj(func(d *jx.Decoder, key string) error {    v, err := d.Num()    if err != nil {        return err    }    n = v    return nil}); err != nil {    panic(err)}fmt.Println(n)fmt.Println("positive:", n.Positive())// Can decode floats with zero fractional part as integers:v, err := n.Int64()if err != nil {    panic(err)}fmt.Println("int64:", v)// Output:// "10531.0"// positive: true// int64: 10531
Base64

Usejx.Encoder.Base64 andjx.Decoder.Base64 orjx.Decoder.Base64Append.

Same as encoding/json, base64.StdEncoding or [RFC 4648].

var e jx.Encodere.Base64([]byte("Hello"))fmt.Println(e)data, _ := jx.DecodeBytes(e.Bytes()).Base64()fmt.Printf("%s", data)// Output:// "SGVsbG8="// Hello
Validate

Check that byte slice is valid json withjx.Valid:

fmt.Println(jx.Valid([]byte(`{"field": "value"}`))) // truefmt.Println(jx.Valid([]byte(`"Hello, world!"`)))    // truefmt.Println(jx.Valid([]byte(`["foo"}`)))            // false
Capture

Thejx.Decoder.Capture method allows to unread everything is read in callback.Useful for multi-pass parsing:

d := jx.DecodeStr(`["foo", "bar", "baz"]`)var elems int// NB: Currently Capture does not support io.Reader, only buffers.if err := d.Capture(func(d *jx.Decoder) error {// Everything decoded in this callback will be rolled back.return d.Arr(func(d *jx.Decoder) error {elems++return d.Skip()})}); err != nil {panic(err)}// Decoder is rolled back to state before "Capture" call.fmt.Println("Read", elems, "elements on first pass")fmt.Println("Next element is", d.Next(), "again")// Output:// Read 3 elements on first pass// Next element is array again
ObjBytes

TheDecoder.ObjBytes method tries not to allocate memory for keys, reusing existing buffer.

d := DecodeStr(`{"id":1,"randomNumber":10}`)d.ObjBytes(func(d *Decoder, key []byte) error {    switch string(key) {    case "id":    case "randomNumber":    }    return d.Skip()})

Roadmap

  • Rework and exportAny
  • SupportRaw for io.Reader
  • SupportCapture for io.Reader
  • Improve Num
    • Better validation on decoding
    • Support BigFloat and BigInt
    • Support equivalence check, likeeq(1.0, 1) == true
  • Add non-callback decoding of objects

Non-goals

  • Code generation for decoding or encoding
  • Replacement forencoding/json
  • Reflection orinterface{} based encoding or decoding
  • Support for json path or similar

This package should be kept as simple as possible and be used aslow-level foundation for high-level projects like code generator.

License

MIT, same as jsoniter

Documentation

Overview

Package jx implementsRFC 7159 json encoding and decoding.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {var e jx.Encodere.Obj(func(e *jx.Encoder) {e.FieldStart("data")e.Base64([]byte("hello"))})fmt.Println(e)if err := jx.DecodeBytes(e.Bytes()).Obj(func(d *jx.Decoder, key string) error {v, err := d.Base64()fmt.Printf("%s: %s\n", key, v)return err}); err != nil {panic(err)}}
Output:{"data":"aGVsbG8="}data: hello

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcPutDecoder

func PutDecoder(d *Decoder)

PutDecoder puts *Decoder into pool.

funcPutEncoder

func PutEncoder(e *Encoder)

PutEncoder puts *Encoder to pool

funcPutWriteradded inv0.32.0

func PutWriter(e *Writer)

PutWriter puts *Writer to pool

funcValid

func Valid(data []byte)bool

Valid reports whether data is valid json.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {fmt.Println(jx.Valid([]byte(`{"field": "value"}`)))fmt.Println(jx.Valid([]byte(`"Hello, world!"`)))fmt.Println(jx.Valid([]byte(`["foo"}`)))}
Output:truetruefalse

Types

typeArrIteradded inv0.33.0

type ArrIter struct {// contains filtered or unexported fields}

ArrIter is decoding array iterator.

func (*ArrIter)Erradded inv0.33.0

func (i *ArrIter) Err()error

Err returns the error, if any, that was encountered during iteration.

func (*ArrIter)Nextadded inv0.33.0

func (i *ArrIter) Next()bool

Next consumes element and returns false, if there is no elements anymore.

typeDecoder

type Decoder struct {// contains filtered or unexported fields}

Decoder decodes json.

Can decode from io.Reader or byte slice directly.

funcDecode

func Decode(readerio.Reader, bufSizeint) *Decoder

Decode creates a Decoder that reads json from io.Reader.

funcDecodeBytes

func DecodeBytes(input []byte) *Decoder

DecodeBytes creates a Decoder that reads json from byte slice.

funcDecodeStr

func DecodeStr(inputstring) *Decoder

DecodeStr creates a Decoder that reads string as json.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {d := jx.DecodeStr(`{"values":[4,8,15,16,23,42]}`)// Save all integers from "values" array to slice.var values []int// Iterate over each object field.if err := d.Obj(func(d *jx.Decoder, key string) error {switch key {case "values":// Iterate over each array element.return d.Arr(func(d *jx.Decoder) error {v, err := d.Int()if err != nil {return err}values = append(values, v)return nil})default:// Skip unknown fields if any.return d.Skip()}}); err != nil {panic(err)}fmt.Println(values)}
Output:[4 8 15 16 23 42]

funcGetDecoder

func GetDecoder() *Decoder

GetDecoder gets *Decoder from pool.

func (*Decoder)Arr

func (d *Decoder) Arr(f func(d *Decoder)error)error

Arr decodes array and invokes callback on each array element.

func (*Decoder)ArrIteradded inv0.33.0

func (d *Decoder) ArrIter() (ArrIter,error)

ArrIter creates new array iterator.

func (*Decoder)Base64

func (d *Decoder) Base64() ([]byte,error)

Base64 decodes base64 encoded data from string.

Same as encoding/json, base64.StdEncoding orRFC 4648.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {data, _ := jx.DecodeStr(`"SGVsbG8="`).Base64()fmt.Printf("%s", data)}
Output:Hello

func (*Decoder)Base64Append

func (d *Decoder) Base64Append(b []byte) ([]byte,error)

Base64Append appends base64 encoded data from string.

Same as encoding/json, base64.StdEncoding orRFC 4648.

func (*Decoder)BigFloat

func (d *Decoder) BigFloat() (*big.Float,error)

BigFloat read big.Float

func (*Decoder)BigInt

func (d *Decoder) BigInt() (*big.Int,error)

BigInt read big.Int

func (*Decoder)Bool

func (d *Decoder) Bool() (bool,error)

Bool reads a json object as Bool

func (*Decoder)Capture

func (d *Decoder) Capture(f func(d *Decoder)error)error

Capture calls f and then rolls back to state before call.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {d := jx.DecodeStr(`["foo", "bar", "baz"]`)var elems int// NB: Currently Capture does not support io.Reader, only buffers.if err := d.Capture(func(d *jx.Decoder) error {// Everything decoded in this callback will be rolled back.return d.Arr(func(d *jx.Decoder) error {elems++return d.Skip()})}); err != nil {panic(err)}// Decoder is rolled back to state before "Capture" call.fmt.Println("Read", elems, "elements on first pass")fmt.Println("Next element is", d.Next(), "again")}
Output:Read 3 elements on first passNext element is array again

func (*Decoder)Elem

func (d *Decoder) Elem() (okbool, errerror)

Elem skips to the start of next array element, returning true booleanif element exists.

Can be called before or in Array.

func (*Decoder)Float32

func (d *Decoder) Float32() (float32,error)

Float32 reads float32 value.

func (*Decoder)Float64

func (d *Decoder) Float64() (float64,error)

Float64 read float64

func (*Decoder)Int

func (d *Decoder) Int() (int,error)

Int reads int.

func (*Decoder)Int16added inv0.40.0

func (d *Decoder) Int16() (int16,error)

Int16 reads int16.

func (*Decoder)Int32

func (d *Decoder) Int32() (int32,error)

Int32 reads int32.

func (*Decoder)Int64

func (d *Decoder) Int64() (int64,error)

Int64 reads int64.

func (*Decoder)Int8added inv0.40.0

func (d *Decoder) Int8() (int8,error)

Int8 reads int8.

func (*Decoder)Next

func (d *Decoder) Next()Type

Next gets Type of relatively next json element

func (*Decoder)Null

func (d *Decoder) Null()error

Null reads a json object as null andreturns whether it's a null or not.

func (*Decoder)Num

func (d *Decoder) Num() (Num,error)

Num decodes number.

Do not retain returned value, it references underlying buffer.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {// Can decode numbers and number strings.d := jx.DecodeStr(`{"foo": "10531.0"}`)var n jx.Numif err := d.Obj(func(d *jx.Decoder, key string) error {v, err := d.Num()if err != nil {return err}n = vreturn nil}); err != nil {panic(err)}fmt.Println(n)fmt.Println("positive:", n.Positive())// Can decode floats with zero fractional part as integers:v, err := n.Int64()if err != nil {panic(err)}fmt.Println("int64:", v)}
Output:"10531.0"positive: trueint64: 10531

func (*Decoder)NumAppend

func (d *Decoder) NumAppend(vNum) (Num,error)

NumAppend appends number.

func (*Decoder)Obj

func (d *Decoder) Obj(f func(d *Decoder, keystring)error)error

Obj reads json object, calling f on each field.

Use ObjBytes to reduce heap allocations for keys.

func (*Decoder)ObjBytes

func (d *Decoder) ObjBytes(f func(d *Decoder, key []byte)error)error

ObjBytes calls f for every key in object, using byte slice as key.

The key value is valid only until f is not returned.

func (*Decoder)ObjIteradded inv0.35.0

func (d *Decoder) ObjIter() (ObjIter,error)

ObjIter creates new object iterator.

func (*Decoder)Raw

func (d *Decoder) Raw() (Raw,error)

Raw is like Skip(), but saves and returns skipped value as raw json.

Do not retain returned value, it references underlying buffer.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {d := jx.DecodeStr(`{"foo": [1, 2, 3]}`)var raw jx.Rawif err := d.Obj(func(d *jx.Decoder, key string) error {v, err := d.Raw()if err != nil {return err}raw = vreturn nil}); err != nil {panic(err)}fmt.Println(raw.Type(), raw)}
Output:array [1, 2, 3]

func (*Decoder)RawAppend

func (d *Decoder) RawAppend(bufRaw) (Raw,error)

RawAppend is Raw that appends saved raw json value to buf.

func (*Decoder)Reset

func (d *Decoder) Reset(readerio.Reader)

Reset resets reader and underlying state, next reads will use provided io.Reader.

func (*Decoder)ResetBytes

func (d *Decoder) ResetBytes(input []byte)

ResetBytes resets underlying state, next reads will use provided buffer.

func (*Decoder)Skip

func (d *Decoder) Skip()error

Skip skips a json object and positions to relatively the next json object.

func (*Decoder)Str

func (d *Decoder) Str() (string,error)

Str reads string.

func (*Decoder)StrAppend

func (d *Decoder) StrAppend(b []byte) ([]byte,error)

StrAppend reads string and appends it to byte slice.

func (*Decoder)StrBytes

func (d *Decoder) StrBytes() ([]byte,error)

StrBytes returns string value as sub-slice of internal buffer.

Bytes are valid only until next call to any Decoder method.

func (*Decoder)UIntadded inv0.26.0

func (d *Decoder) UInt() (uint,error)

UInt reads uint.

func (*Decoder)UInt16added inv0.40.0

func (d *Decoder) UInt16() (uint16,error)

UInt16 reads uint16.

func (*Decoder)UInt32added inv0.26.0

func (d *Decoder) UInt32() (uint32,error)

UInt32 reads uint32.

func (*Decoder)UInt64added inv0.26.0

func (d *Decoder) UInt64() (uint64,error)

UInt64 reads uint64.

func (*Decoder)UInt8added inv0.40.0

func (d *Decoder) UInt8() (uint8,error)

UInt8 reads uint8.

func (*Decoder)Validateadded inv0.18.0

func (d *Decoder) Validate()error

Validate consumes all input, validating that input is a json objectwithout any trialing data.

typeEncoder

type Encoder struct {// contains filtered or unexported fields}

Encoder encodes json to underlying buffer.

Zero value is valid.

funcGetEncoder

func GetEncoder() *Encoder

GetEncoder returns *Encoder from pool.

funcNewStreamingEncoderadded inv1.0.0

func NewStreamingEncoder(wio.Writer, bufSizeint) *Encoder

NewStreamingEncoder creates new streaming encoder.

func (*Encoder)Arradded inv0.21.0

func (e *Encoder) Arr(f func(e *Encoder)) (failbool)

Arr writes start of array, invokes callback and writes end of array.

If callback is nil, writes empty array.

func (*Encoder)ArrEmpty

func (e *Encoder) ArrEmpty()bool

ArrEmpty writes empty array.

func (*Encoder)ArrEnd

func (e *Encoder) ArrEnd()bool

ArrEnd writes end of array, performing indentation if needed.

Use Arr as convenience helper for writing arrays.

func (*Encoder)ArrStart

func (e *Encoder) ArrStart() (failbool)

ArrStart writes start of array, performing indentation if needed.

Use Arr as convenience helper for writing arrays.

func (*Encoder)Base64

func (e *Encoder) Base64(data []byte)bool

Base64 encodes data as standard base64 encoded string.

Same as encoding/json, base64.StdEncoding orRFC 4648.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {var e jx.Encodere.Base64([]byte("Hello"))fmt.Println(e)data, _ := jx.DecodeBytes(e.Bytes()).Base64()fmt.Printf("%s", data)}
Output:"SGVsbG8="Hello

func (*Encoder)Bool

func (e *Encoder) Bool(vbool)bool

Bool encodes boolean.

func (*Encoder)ByteStradded inv0.34.0

func (e *Encoder) ByteStr(v []byte)bool

ByteStr encodes byte slice without html escaping.

Use ByteStrEscape to escape html, this is default for encoding/json andshould be used by default for untrusted strings.

func (*Encoder)ByteStrEscapeadded inv0.34.0

func (e *Encoder) ByteStrEscape(v []byte)bool

ByteStrEscape encodes string with html special characters escaping.

func (Encoder)Bytes

func (eEncoder) Bytes() []byte

Bytes returns underlying buffer.

func (*Encoder)Closeadded inv1.0.0

func (e *Encoder) Close()error

Close flushes underlying buffer to writer in streaming mode.Otherwise, it does nothing.

func (*Encoder)Fieldadded inv0.19.0

func (e *Encoder) Field(namestring, f func(e *Encoder)) (failbool)

Field encodes field start and then invokes callback.

Has ~5ns overhead over FieldStart.

func (*Encoder)FieldStartadded inv0.22.0

func (e *Encoder) FieldStart(fieldstring) (failbool)

FieldStart encodes field name and writes colon.

For non-zero indentation also writes single space after colon.

Use Field as convenience helper for encoding fields.

func (*Encoder)Float32

func (e *Encoder) Float32(vfloat32)bool

Float32 encodes float32.

NB: Infinities and NaN are represented as null.

func (*Encoder)Float64

func (e *Encoder) Float64(vfloat64)bool

Float64 encodes float64.

NB: Infinities and NaN are represented as null.

func (*Encoder)Growadded inv1.1.0

func (e *Encoder) Grow(nint)

Grow grows the underlying buffer

func (*Encoder)Int

func (e *Encoder) Int(vint)bool

Int encodes int.

func (*Encoder)Int16added inv0.25.0

func (e *Encoder) Int16(vint16)bool

Int16 encodes int16.

func (*Encoder)Int32

func (e *Encoder) Int32(vint32)bool

Int32 encodes int32.

func (*Encoder)Int64

func (e *Encoder) Int64(vint64)bool

Int64 encodes int64.

func (*Encoder)Int8added inv0.25.0

func (e *Encoder) Int8(vint8)bool

Int8 encodes int8.

func (*Encoder)Null

func (e *Encoder) Null()bool

Null writes null.

func (*Encoder)Num

func (e *Encoder) Num(vNum)bool

Num encodes number.

func (*Encoder)Objadded inv0.21.0

func (e *Encoder) Obj(f func(e *Encoder)) (failbool)

Obj writes start of object, invokes callback and writes end of object.

If callback is nil, writes empty object.

func (*Encoder)ObjEmpty

func (e *Encoder) ObjEmpty()bool

ObjEmpty writes empty object.

func (*Encoder)ObjEnd

func (e *Encoder) ObjEnd()bool

ObjEnd writes end of object token, performing indentation if needed.

Use Obj as convenience helper for writing objects.

func (*Encoder)ObjStart

func (e *Encoder) ObjStart() (failbool)

ObjStart writes object start, performing indentation if needed.

Use Obj as convenience helper for writing objects.

func (*Encoder)Raw

func (e *Encoder) Raw(b []byte)bool

Raw writes byte slice as raw json.

func (*Encoder)RawStradded inv0.20.0

func (e *Encoder) RawStr(vstring)bool

RawStr writes string as raw json.

func (*Encoder)Reset

func (e *Encoder) Reset()

Reset resets underlying buffer.

If e is in streaming mode, it is reset to non-streaming mode.

func (*Encoder)ResetWriteradded inv1.0.0

func (e *Encoder) ResetWriter(outio.Writer)

ResetWriter resets underlying buffer and sets output writer.

func (*Encoder)SetBytes

func (e *Encoder) SetBytes(buf []byte)

SetBytes sets underlying buffer.

func (*Encoder)SetIdent

func (e *Encoder) SetIdent(nint)

SetIdent sets length of single indentation step.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {var e jx.Encodere.SetIdent(2)e.ObjStart()e.FieldStart("data")e.ArrStart()e.Int(1)e.Int(2)e.ArrEnd()e.ObjEnd()fmt.Println(e)}
Output:{  "data": [    1,    2  ]}

func (*Encoder)Str

func (e *Encoder) Str(vstring)bool

Str encodes string without html escaping.

Use StrEscape to escape html, this is default for encoding/json andshould be used by default for untrusted strings.

func (*Encoder)StrEscape

func (e *Encoder) StrEscape(vstring)bool

StrEscape encodes string with html special characters escaping.

func (Encoder)String

func (eEncoder) String()string

String returns string of underlying buffer.

Example
package mainimport ("fmt""github.com/go-faster/jx")func main() {var e jx.Encodere.ObjStart()           // {e.FieldStart("values") // "values":e.ArrStart()           // [for _, v := range []int{4, 8, 15, 16, 23, 42} {e.Int(v)}e.ArrEnd() // ]e.ObjEnd() // }fmt.Println(e)fmt.Println("Buffer len:", len(e.Bytes()))}
Output:{"values":[4,8,15,16,23,42]}Buffer len: 28

func (*Encoder)UIntadded inv0.26.0

func (e *Encoder) UInt(vuint)bool

UInt encodes uint.

func (*Encoder)UInt16added inv0.26.0

func (e *Encoder) UInt16(vuint16)bool

UInt16 encodes uint16.

func (*Encoder)UInt32added inv0.26.0

func (e *Encoder) UInt32(vuint32)bool

UInt32 encodes uint32.

func (*Encoder)UInt64added inv0.26.0

func (e *Encoder) UInt64(vuint64)bool

UInt64 encodes uint64.

func (*Encoder)UInt8added inv0.26.0

func (e *Encoder) UInt8(vuint8)bool

UInt8 encodes uint8.

func (*Encoder)Write

func (e *Encoder) Write(p []byte) (nint, errerror)

Write implements io.Writer.

func (*Encoder)WriteTo

func (e *Encoder) WriteTo(wio.Writer) (nint64, errerror)

WriteTo implements io.WriterTo.

typeNum

type Num []byte

Num represents number, which can be raw json number or number string.

Same as Raw, but with number invariants.

Examples:

123.45   // Str: false, IsInt: false"123.45" // Str: true,  IsInt: false"12345"  // Str: true,  IsInt: true12345    // Str: false, IsInt: true

func (Num)Equal

func (nNum) Equal(vNum)bool

Equal reports whether numbers are strictly equal, including their formats.

func (Num)Float64

func (nNum) Float64() (float64,error)

Float64 decodes number as 64-bit floating point.

func (Num)Formatadded inv0.23.2

func (nNum) Format(ffmt.State, verbrune)

Format implements fmt.Formatter.

func (Num)Int64

func (nNum) Int64() (int64,error)

Int64 decodes number as a signed 64-bit integer.Works on floats with zero fractional part.

func (Num)IsInt

func (nNum) IsInt()bool

IsInt reports whether number is integer.

func (Num)Negative

func (nNum) Negative()bool

Negative reports whether number is negative.

func (Num)Positive

func (nNum) Positive()bool

Positive reports whether number is positive.

func (Num)Sign

func (nNum) Sign()int

Sign reports sign of number.

0 is zero, 1 is positive, -1 is negative.

func (Num)Str

func (nNum) Str()bool

Str reports whether Num is string number.

func (Num)String

func (nNum) String()string

func (Num)Uint64

func (nNum) Uint64() (uint64,error)

Uint64 decodes number as an unsigned 64-bit integer.Works on floats with zero fractional part.

func (Num)Zero

func (nNum) Zero()bool

Zero reports whether number is zero.

typeObjIteradded inv0.35.0

type ObjIter struct {// contains filtered or unexported fields}

ObjIter is decoding object iterator.

func (*ObjIter)Erradded inv0.35.0

func (i *ObjIter) Err()error

Err returns the error, if any, that was encountered during iteration.

func (*ObjIter)Keyadded inv0.35.0

func (i *ObjIter) Key() []byte

Key returns current key.

Key call must be preceded by a call to Next.

func (*ObjIter)Nextadded inv0.35.0

func (i *ObjIter) Next()bool

Next consumes element and returns false, if there is no elements anymore.

typeRaw

type Raw []byte

Raw json value.

func (Raw)String

func (rRaw) String()string

func (Raw)Type

func (rRaw) Type()Type

Type of Raw json value.

typeType

type Typeint

Type of json value.

const (// Invalid json value.InvalidType =iota// String json value, like "foo".String// Number json value, like 100 or 1.01.Number// Null json value.Null// Bool json value, true or false.Bool// Array json value, like [1, 2, 3].Array// Object json value, like {"foo": 1}.Object)

func (Type)String

func (tType) String()string

typeWriteradded inv0.26.0

type Writer struct {Buf []byte// underlying buffer// contains filtered or unexported fields}

Writer writes json tokens to underlying buffer.

Zero value is valid.

funcGetWriteradded inv0.32.0

func GetWriter() *Writer

GetWriter returns *Writer from pool.

func (*Writer)ArrEndadded inv0.26.0

func (w *Writer) ArrEnd()bool

ArrEnd writes end of array.

func (*Writer)ArrStartadded inv0.26.0

func (w *Writer) ArrStart()bool

ArrStart writes start of array.

func (*Writer)Base64added inv0.26.0

func (w *Writer) Base64(data []byte)bool

Base64 encodes data as standard base64 encoded string.

Same as encoding/json, base64.StdEncoding orRFC 4648.

func (*Writer)Booladded inv0.26.0

func (w *Writer) Bool(vbool)bool

Bool encodes boolean.

func (*Writer)ByteStradded inv0.34.0

func (w *Writer) ByteStr(v []byte)bool

ByteStr encodes string without html escaping.

Use ByteStrEscape to escape html, this is default for encoding/json andshould be used by default for untrusted strings.

func (*Writer)ByteStrEscapeadded inv0.34.0

func (w *Writer) ByteStrEscape(v []byte)bool

ByteStrEscape encodes string with html special characters escaping.

func (*Writer)Closeadded inv1.0.0

func (w *Writer) Close()error

Close flushes underlying buffer to writer in streaming mode.Otherwise, it does nothing.

func (*Writer)Commaadded inv0.26.0

func (w *Writer) Comma()bool

Comma writes comma.

func (*Writer)Falseadded inv0.26.0

func (w *Writer) False()bool

False writes false.

func (*Writer)FieldStartadded inv0.26.0

func (w *Writer) FieldStart(fieldstring)bool

FieldStart encodes field name and writes colon.

func (*Writer)Floatadded inv0.26.0

func (w *Writer) Float(vfloat64, bitsint)bool

Float writes float value to buffer.

func (*Writer)Float32added inv0.26.0

func (w *Writer) Float32(vfloat32)bool

Float32 encodes float32.

NB: Infinities and NaN are represented as null.

func (*Writer)Float64added inv0.26.0

func (w *Writer) Float64(vfloat64)bool

Float64 encodes float64.

NB: Infinities and NaN are represented as null.

func (*Writer)Growadded inv1.1.0

func (w *Writer) Grow(nint)

Grow grows the underlying buffer.

Calls (*bytes.Buffer).Grow(n int) on w.Buf.

func (*Writer)Intadded inv0.26.0

func (w *Writer) Int(vint)bool

Int encodes int.

func (*Writer)Int16added inv0.26.0

func (w *Writer) Int16(vint16) (failbool)

Int16 encodes int16.

func (*Writer)Int32added inv0.26.0

func (w *Writer) Int32(vint32) (failbool)

Int32 encodes int32.

func (*Writer)Int64added inv0.26.0

func (w *Writer) Int64(vint64) (failbool)

Int64 encodes int64.

func (*Writer)Int8added inv0.26.0

func (w *Writer) Int8(vint8) (failbool)

Int8 encodes int8.

func (*Writer)Nulladded inv0.26.0

func (w *Writer) Null()bool

Null writes null.

func (*Writer)Numadded inv0.26.0

func (w *Writer) Num(vNum)bool

Num encodes number.

func (*Writer)ObjEndadded inv0.26.0

func (w *Writer) ObjEnd()bool

ObjEnd writes end of object token.

func (*Writer)ObjStartadded inv0.26.0

func (w *Writer) ObjStart()bool

ObjStart writes object start.

func (*Writer)Rawadded inv0.26.0

func (w *Writer) Raw(b []byte)bool

Raw writes byte slice as raw json.

func (*Writer)RawStradded inv0.26.0

func (w *Writer) RawStr(vstring)bool

RawStr writes string as raw json.

func (*Writer)Resetadded inv0.26.0

func (w *Writer) Reset()

Reset resets underlying buffer.

If w is in streaming mode, it is reset to non-streaming mode.

func (*Writer)ResetWriteradded inv1.0.0

func (w *Writer) ResetWriter(outio.Writer)

ResetWriter resets underlying buffer and sets output writer.

func (*Writer)Stradded inv0.26.0

func (w *Writer) Str(vstring)bool

Str encodes string without html escaping.

Use StrEscape to escape html, this is default for encoding/json andshould be used by default for untrusted strings.

func (*Writer)StrEscapeadded inv0.26.0

func (w *Writer) StrEscape(vstring)bool

StrEscape encodes string with html special characters escaping.

func (Writer)Stringadded inv0.26.0

func (wWriter) String()string

String returns string of underlying buffer.

func (*Writer)Trueadded inv0.26.0

func (w *Writer) True()bool

True writes true.

func (*Writer)UIntadded inv0.26.0

func (w *Writer) UInt(vuint)bool

UInt encodes uint.

func (*Writer)UInt16added inv0.26.0

func (w *Writer) UInt16(vuint16) (failbool)

UInt16 encodes uint16.

func (*Writer)UInt32added inv0.26.0

func (w *Writer) UInt32(vuint32) (failbool)

UInt32 encodes uint32.

func (*Writer)UInt64added inv0.26.0

func (w *Writer) UInt64(vuint64) (failbool)

UInt64 encodes uint64.

func (*Writer)UInt8added inv0.26.0

func (w *Writer) UInt8(vuint8)bool

UInt8 encodes uint8.

func (*Writer)Writeadded inv0.26.0

func (w *Writer) Write(p []byte) (nint, errerror)

Write implements io.Writer.

func (*Writer)WriteToadded inv0.26.0

func (w *Writer) WriteTo(tio.Writer) (nint64, errerror)

WriteTo implements io.WriterTo.

Source Files

View all Source files

Directories

PathSynopsis
internal
byteseq
Package byteseq provides a Byteseq type that can be used to represent a sequence of bytes.
Package byteseq provides a Byteseq type that can be used to represent a sequence of bytes.
tools
mkintcommand
Command mkencint generates integer encoding/decoding functions.
Command mkencint generates integer encoding/decoding functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp