Source File
dec.go
Belonging Package
github.com/go-faster/jx
package jx
import (
)
// Type of json value.
type Type int
func ( Type) () string {
switch {
case Invalid:
return "invalid"
case String:
return "string"
case Number:
return "number"
case Null:
return "null"
case Bool:
return "bool"
case Array:
return "array"
case Object:
return "object"
default:
return "unknown"
}
}
const (
// Invalid json value.
Invalid Type = 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
)
var types []Type
func () {
types = make([]Type, 256)
for := range types {
types[] = Invalid
}
types['"'] = String
types['-'] = Number
types['0'] = Number
types['1'] = Number
types['2'] = Number
types['3'] = Number
types['4'] = Number
types['5'] = Number
types['6'] = Number
types['7'] = Number
types['8'] = Number
types['9'] = Number
types['t'] = Bool
types['f'] = Bool
types['n'] = Null
types['['] = Array
types['{'] = Object
}
// Decoder decodes json.
//
// Can decode from io.Reader or byte slice directly.
type Decoder struct {
reader io.Reader
// buf is current buffer.
//
// Contains full json if reader is nil or used as a read buffer
// otherwise.
buf []byte
head int // offset in buf to start of current json stream
tail int // offset in buf to end of current json stream
streamOffset int // for reader, offset in stream to start of current buf contents
depth int
}
const defaultBuf = 512
// Decode creates a Decoder that reads json from io.Reader.
func ( io.Reader, int) *Decoder {
if <= 0 {
= defaultBuf
}
return &Decoder{
reader: ,
buf: make([]byte, ),
}
}
// DecodeBytes creates a Decoder that reads json from byte slice.
func ( []byte) *Decoder {
return &Decoder{
buf: ,
tail: len(),
}
}
// DecodeStr creates a Decoder that reads string as json.
func ( string) *Decoder {
return DecodeBytes([]byte())
}
func ( *Decoder) () int {
return .streamOffset + .head
}
// Reset resets reader and underlying state, next reads will use provided io.Reader.
func ( *Decoder) ( io.Reader) {
.reader =
.head = 0
.tail = 0
.depth = 0
// Reads from reader need buffer.
if cap(.buf) == 0 {
// Allocate new buffer if none.
.buf = make([]byte, defaultBuf)
}
if len(.buf) == 0 {
// Set buffer to full capacity if needed.
.buf = .buf[:cap(.buf)]
}
}
// ResetBytes resets underlying state, next reads will use provided buffer.
func ( *Decoder) ( []byte) {
.reader = nil
.head = 0
.tail = len()
.depth = 0
.buf =
}
The pages are generated with Golds v0.6.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |