package jsontextimport ()// Kind is the kind of a JSON token.//// It is a single byte, the first byte of the token in the grammar, except for numbers, whose kind is always// '0'.typeKindbyteconst (KindInvalidKind = 0// invalid kindKindNullKind = 'n'// nullKindFalseKind = 'f'// falseKindTrueKind = 't'// trueKindStringKind = '"'// stringKindNumberKind = '0'// numberKindBeginObjectKind = '{'// begin objectKindEndObjectKind = '}'// end objectKindBeginArrayKind = '['// begin arrayKindEndArrayKind = ']'// end array)// String returns a string representation of k.func ( Kind) () string {switch {caseKindInvalid:return"invalid"caseKindNull:return"null"caseKindFalse:return"false"caseKindTrue:return"true"caseKindString:return"string"caseKindNumber:return"number"caseKindBeginObject, KindEndObject, KindBeginArray, KindEndArray:returnstring(rune()) }return"<invalid jsontext.Kind: " + quoteChar([]byte{byte()}) + ">"}// kindOf is the kind of a token or value which starts with c, or KindInvalid.func kindOf( byte) Kind {switch {case'n', 'f', 't', '"', '{', '}', '[', ']':returnKind()case'-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':returnKindNumber }returnKindInvalid}// The forms in which a Token holds its value.const ( formNone = iota// a literal or a delimiter, whose kind is all of it formRaw // the text of the token: in the buffer of dec, or in str after Clone formString // a string, in str formInt // an int64, in num formUint // a uint64, in num formFloat // a float64, as its bits in num formFloat32 // a float32, as the bits of its float64 value in num)// Token is a lexical JSON token, one of:// - a JSON literal (i.e., null, true, or false)// - a JSON string (e.g., "hello, world!")// - a JSON number (e.g., 123.456)// - a begin or end delimiter of a JSON object (i.e., { or } )// - a begin or end delimiter of a JSON array (i.e., [ or ] )//// A Token can't hold a whole array or object, which a Value can. There is no Token for a comma or a colon,// which the structure implies.//// A Token holds its value in one of two forms://// - As raw JSON text in the buffer of a Decoder, as only Decoder.ReadToken makes it. Such a token is only// valid until the next call of a method of the Decoder (e.g., Decoder.PeekKind, Decoder.ReadToken,// Decoder.ReadValue, or Decoder.SkipValue). Token.Clone copies the text to a token which stays valid.//// - As a Go value, as the constructors (e.g., String, Int, Uint, Float) make it. Such a token is valid// forever.typeTokenstruct { _ [0]func() // not comparable// Of four fields at most, so that the compiler keeps a Token in registers. src *tokenSource// what the token is str string// the value of a string, or the text of a clone of a raw token num uint64// the value of a number, or, in the buffer of the decoder, the offset of the token in the input}// tokenSource is the kind and the form of a token, and the decoder of a raw token: a raw token points to one of// its decoder, and the others to one of the variables here.type tokenSource struct { dec *decoder kind Kind form uint8}var ( invalidSource = tokenSource{} nullSource, falseSource, trueSource = tokenSource{kind: KindNull}, tokenSource{kind: KindFalse}, tokenSource{kind: KindTrue} beginObjectSource, endObjectSource = tokenSource{kind: KindBeginObject}, tokenSource{kind: KindEndObject} beginArraySource, endArraySource = tokenSource{kind: KindBeginArray}, tokenSource{kind: KindEndArray} stringSource = tokenSource{kind: KindString, form: formString} intSource, uintSource = tokenSource{kind: KindNumber, form: formInt}, tokenSource{kind: KindNumber, form: formUint} floatSource, float32Source = tokenSource{kind: KindNumber, form: formFloat}, tokenSource{kind: KindNumber, form: formFloat32} nonFiniteSource = tokenSource{kind: KindString, form: formFloat} // NaN or an infinity nonFinite32Source = tokenSource{kind: KindString, form: formFloat32} rawStringSource, rawNumberSource = tokenSource{kind: KindString, form: formRaw}, tokenSource{kind: KindNumber, form: formRaw})var (Null = Token{src: &nullSource}False = Token{src: &falseSource}True = Token{src: &trueSource}BeginObject = Token{src: &beginObjectSource}EndObject = Token{src: &endObjectSource}BeginArray = Token{src: &beginArraySource}EndArray = Token{src: &endArraySource})// source is the source of t, which the zero Token has not.func ( Token) () *tokenSource {if .src == nil {return &invalidSource }return .src}// literalToken is the token of a literal or a delimiter of the kind k.func literalToken( Kind) Token {switch {caseKindNull:returnNullcaseKindFalse:returnFalsecaseKindTrue:returnTruecaseKindBeginObject:returnBeginObjectcaseKindEndObject:returnEndObjectcaseKindBeginArray:returnBeginArray }returnEndArray}// Bool constructs a Token of a JSON boolean.func ( bool) Token {if {returnTrue }returnFalse}// String constructs a Token of a JSON string. The string should be valid UTF-8: invalid bytes may be mangled// as the Unicode replacement character.func ( string) Token {returnToken{src: &stringSource, str: }}// Float constructs a Token of a JSON number of a 64-bit floating-point number, formatted as ECMA-262, 10th// edition, section 7.1.12.1 and RFC 8785, section 3.2.2.3 do, except that -0 is formatted as -0. NaN, +Inf and// -Inf are JSON strings of the values "NaN", "Infinity" and "-Infinity".func ( float64) Token { := &floatSourceifmath.IsNaN() || math.IsInf(, 0) { = &nonFiniteSource }returnToken{src: , num: math.Float64bits()}}// Float32 constructs a Token of a JSON number of a 32-bit floating-point number, formatted as ECMA-262, 10th// edition, section 7.1.12.1 does, except that -0 is formatted as -0. NaN, +Inf and -Inf are JSON strings of the// values "NaN", "Infinity" and "-Infinity".//// Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use 32-bit precision// only if the decoder knows that the number has only 32-bit precision. In any other case, use Float.func ( float32) Token { := float64() := &float32Sourceifmath.IsNaN() || math.IsInf(, 0) { = &nonFinite32Source }returnToken{src: , num: math.Float64bits()}}// Int constructs a Token of a JSON number of an int64.func ( int64) Token {returnToken{src: &intSource, num: uint64()}}// Uint constructs a Token of a JSON number of a uint64.func ( uint64) Token {returnToken{src: &uintSource, num: }}// Clone returns a copy of the token whose value is not in the buffer of a Decoder: it stays valid after the// following calls of the Decoder. A token which a constructor made is returned as it is.func ( Token) () Token {if .source().dec == nil {return }if .kind() == KindString {returnToken{src: &rawStringSource, str: string(.raw())} }returnToken{src: &rawNumberSource, str: string(.raw())}}// raw is the text of a raw token. It panics if the decoder has moved past the token.func ( Token) () []byte { := .source().decif == nil {return []byte(.str) } .panicIfVoided()return .prevBuffer()}// panicIfVoided panics if t is a raw token which the decoder has moved past.func ( Token) () {if := .source().dec; != nil && .prevOffset() != int64(.num) {panic("invalid jsontext.Token; it has been voided by a subsequent json.Decoder call") }}// Kind returns the kind of the token. It panics for a raw token which the decoder has moved past.func ( Token) () Kind {return .kind()}// kind is the kind of t. The kind of a raw token is the one of the text of the decoder at its offset, which a// Reset of the decoder may change, as encoding/json/jsontext reads it.func ( Token) () Kind {if .src != nil && .src.dec == nil {return .src.kind// inlined, for the tokens which the encoder writes }return .otherKind()}// otherKind is the kind of the zero Token and of a raw token.func ( Token) () Kind {if .src == nil {returnKindInvalid } .panicIfVoided() := .src.decreturnkindOf(.buf[.prevStart])}// Bool returns the value of a JSON boolean. It panics if the token is not a JSON boolean.func ( Token) () bool {switch .kind() {caseKindTrue:returntruecaseKindFalse:returnfalse }panic("invalid JSON token kind: " + .kind().String())}// String returns the unescaped value of a JSON string. For a token of another kind, it returns its raw JSON// text.func ( Token) () string {// It is small enough to be inlined: the text of a raw token, which is in the buffer of the decoder, is // converted by the caller, which doesn't allocate it where the string doesn't escape. , := .text()if != nil {returnstring() }return}// text is the value of String, as a string or as the bytes of the buffer of a decoder.func ( Token) () (string, []byte) {switch .source().form {caseformNone:if .kind() == KindInvalid {return"<invalid jsontext.Token>", nil }return .kind().String(), nilcaseformRaw: := .kind() := .raw()if != KindString {return"", }if := [1 : len()-1]; bytes.IndexByte(, '\\') < 0 && utf8.Valid() {return"", // the value is the text between the quotes } , := AppendUnquote(nil, )returnstring(), nilcaseformString:return .str, nil }returnstring(.appendNumber(nil)), nil}// appendNumber appends the text of a number of a Go value: for a float which is not finite, the text of its// string, without the quotes.func ( Token) ( []byte) []byte {switch .source().form {caseformInt:returnintfmt.AppendInt(, int64(.num))caseformUint:returnintfmt.AppendUint(, .num)caseformFloat:returnappendFloatText(, math.Float64frombits(.num), 64)default:returnappendFloatText(, math.Float64frombits(.num), 32) }}// numError is the error of a method of Token which reads a number.type numError struct { method string text string err error}func ( *numError) () string {return"jsontext.Token(" + .text + ")." + .method + " error: " + .err.Error()}func ( *numError) () error { return .err }// panicUnlessNumber panics unless the token is a JSON number.func ( Token) () {if .kind() != KindNumber {panic("invalid JSON token kind: " + .kind().String()) }}// Int returns the signed integer value of a JSON number.//// It reports an error which matches strconv.ErrSyntax if the number is not in the restricted grammar of a// signed integer, and one which matches strconv.ErrRange if it is a signed integer out of the range of an// int64. It returns a reasonable value even with an error: the fraction is truncated toward zero, and a number// out of the range is saturated at the closest end.//// It panics if the token is not a JSON number.func ( Token) () (int64, error) { .panicUnlessNumber()varint64varerrorswitch .source().form {caseformInt:returnint64(.num), nilcaseformUint:if .num > math.MaxInt64 { , = math.MaxInt64, strconv.ErrRange } else { = int64(.num) }caseformFloat, formFloat32: , = floatToInt(math.Float64frombits(.num))default: , = parseInt(.raw()) }if != nil {return , &numError{"Int", .String(), } }return , nil}// Uint returns the unsigned integer value of a JSON number.//// It reports an error which matches strconv.ErrSyntax if the number is not in the restricted grammar of an// unsigned integer, and one which matches strconv.ErrRange if it is an unsigned integer out of the range of a// uint64. It returns a reasonable value even with an error: the fraction is truncated toward zero, and a number// out of the range is saturated at the closest end.//// It panics if the token is not a JSON number.func ( Token) () (uint64, error) { .panicUnlessNumber()varuint64varerrorswitch .source().form {caseformUint:return .num, nilcaseformInt:ifint64(.num) < 0 { = strconv.ErrSyntax } else { = .num }caseformFloat, formFloat32: , = floatToUint(math.Float64frombits(.num))default: , = parseUint(.raw()) }if != nil {return , &numError{"Uint", .String(), } }return , nil}// Float returns the floating-point value of a JSON number, parsed with 64 bits of precision.//// If the number is out of the range of a float64, it returns +Inf or -Inf with an error which matches// strconv.ErrRange.//// It returns NaN, +Inf or -Inf for a JSON string of the value "NaN", "Infinity" or "-Infinity".//// It panics if the token is not a JSON number or one of those JSON strings.func ( Token) () (float64, error) {return .float(64)}// Float32 returns the floating-point value of a JSON number, parsed with 32 bits of precision.//// If the number is out of the range of a float32, it returns +Inf or -Inf with an error which matches// strconv.ErrRange.//// It returns NaN, +Inf or -Inf for a JSON string of the value "NaN", "Infinity" or "-Infinity".//// It panics if the token is not a JSON number or one of those JSON strings.//// Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use this method only if// the number is known to have only 32 bits of precision (as Float32 writes it). In any other case, use// Token.Float.func ( Token) () (float32, error) { , := .float(32)returnfloat32(), }func ( Token) ( int) (float64, error) {if .kind() == KindString {if , := .nonFinite(); {return , nil } } .panicUnlessNumber()switch .source().form {caseformInt:returnfloat64(int64(.num)), nilcaseformUint:returnfloat64(.num), nilcaseformFloat, formFloat32: := math.Float64frombits(.num)if == 32 && .source().form == formFloat {if := float64(float32()); math.IsInf(, 0) {return , &numError{"Float", .String(), strconv.ErrRange} } = float64(float32()) }return , nil } := .raw()if == 64 {// a float32 is parsed by strconv: a float64 rounded to a float32 may differ from it by the rounding.if , := jsonnum.ParseFloat(); {return , nil } } , := strconv.ParseFloat(string(), )if != nil {// the grammar of a JSON number is in the one of ParseFloat: the only error is the range.return , &numError{"Float", string(), strconv.ErrRange} }return , nil}// nonFinite is the float of a JSON string of the value "NaN", "Infinity" or "-Infinity".func ( Token) () (float64, bool) {varstringswitch .source().form {caseformFloat, formFloat32:if := math.Float64frombits(.num); !math.IsNaN() {return , true }returnmath.NaN(), truecaseformString: = .strcaseformRaw: = .String() }switch {case"NaN":returnmath.NaN(), truecase"Infinity":returnmath.Inf(+1), truecase"-Infinity":returnmath.Inf(-1), true }return0, false}// floatToInt is f truncated toward zero and saturated in the range of an int64, with an error of the syntax// if f is not an integer, or else of the range if it is out of the range.func floatToInt( float64) (int64, error) {varerrorif != math.Trunc() { = strconv.ErrSyntax }switch {case >= 1<<63:if > 1<<63 { // 2⁶³ is math.MaxInt64 rounded to a float64, as encoding/json/jsontext takes it = orErr(, strconv.ErrRange) }returnmath.MaxInt64, case < -1<<63:returnmath.MinInt64, orErr(, strconv.ErrRange) }returnint64(), }// floatToUint is floatToInt for a uint64: a negative number is out of the syntax of an unsigned integer.func floatToUint( float64) (uint64, error) {varerrorif != math.Trunc() || math.Signbit() { = strconv.ErrSyntax }switch {case >= 1<<64:if > 1<<64 { // 2⁶⁴ is math.MaxUint64 rounded to a float64 = orErr(, strconv.ErrRange) }returnmath.MaxUint64, case <= 0:return0, }returnuint64(), }func orErr(, error) error {if != nil {return }return}// parseInt is Int of the text of a JSON number.func parseInt( []byte) (int64, error) { := len() > 0 && [0] == '-' := if { = [1:] }if , := jsonnum.ParseUint(); {if {if > 1<<63 {returnmath.MinInt64, strconv.ErrRange }return -int64(), nil }if > math.MaxInt64 {returnmath.MaxInt64, strconv.ErrRange }returnint64(), nil } elseifisDigits() {// an integer out of the range of a uint64if {returnmath.MinInt64, strconv.ErrRange }returnmath.MaxInt64, strconv.ErrRange } := parseFloat64() , := floatToInt()return , strconv.ErrSyntax}// parseFloat64 is the float64 of the text of a JSON number, infinite if it is out of the range.func parseFloat64( []byte) float64 {if , := jsonnum.ParseFloat(); {return } , := strconv.ParseFloat(string(), 64)return}// parseUint is Uint of the text of a JSON number.func parseUint( []byte) (uint64, error) {if , := jsonnum.ParseUint(); {return , nil } elseifisDigits() {returnmath.MaxUint64, strconv.ErrRange } := parseFloat64() , := floatToUint()return , strconv.ErrSyntax}// isDigits reports whether b is a JSON integer without a sign: 0, or digits which don't start with 0.func isDigits( []byte) bool {iflen() == 0 || [0] == '0' && len() > 1 {returnfalse }for , := range {if < '0' || > '9' {returnfalse } }returntrue}
The pages are generated with Goldsv0.8.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 @zigo_101 (reachable from the left QR code) to get the latest news of Golds.