package jsontext

import (
	
	
	
	

	
	
)

// 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'.
type Kind byte

const (
	KindInvalid     Kind = 0   // invalid kind
	KindNull        Kind = 'n' // null
	KindFalse       Kind = 'f' // false
	KindTrue        Kind = 't' // true
	KindString      Kind = '"' // string
	KindNumber      Kind = '0' // number
	KindBeginObject Kind = '{' // begin object
	KindEndObject   Kind = '}' // end object
	KindBeginArray  Kind = '[' // begin array
	KindEndArray    Kind = ']' // end array
)

// String returns a string representation of k.
func ( Kind) () string {
	switch  {
	case KindInvalid:
		return "invalid"
	case KindNull:
		return "null"
	case KindFalse:
		return "false"
	case KindTrue:
		return "true"
	case KindString:
		return "string"
	case KindNumber:
		return "number"
	case KindBeginObject, KindEndObject, KindBeginArray, KindEndArray:
		return string(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', '"', '{', '}', '[', ']':
		return Kind()
	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		return KindNumber
	}
	return KindInvalid
}

// 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.
type Token struct {
	_ [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  {
	case KindNull:
		return Null
	case KindFalse:
		return False
	case KindTrue:
		return True
	case KindBeginObject:
		return BeginObject
	case KindEndObject:
		return EndObject
	case KindBeginArray:
		return BeginArray
	}
	return EndArray
}

// Bool constructs a Token of a JSON boolean.
func ( bool) Token {
	if  {
		return True
	}
	return False
}

// 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 {
	return Token{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 {
	 := &floatSource
	if math.IsNaN() || math.IsInf(, 0) {
		 = &nonFiniteSource
	}
	return Token{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()
	 := &float32Source
	if math.IsNaN() || math.IsInf(, 0) {
		 = &nonFinite32Source
	}
	return Token{src: , num: math.Float64bits()}
}

// Int constructs a Token of a JSON number of an int64.
func ( int64) Token {
	return Token{src: &intSource, num: uint64()}
}

// Uint constructs a Token of a JSON number of a uint64.
func ( uint64) Token {
	return Token{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 {
		return Token{src: &rawStringSource, str: string(.raw())}
	}
	return Token{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().dec
	if  == 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 {
		return KindInvalid
	}
	.panicIfVoided()
	 := .src.dec
	return kindOf(.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() {
	case KindTrue:
		return true
	case KindFalse:
		return false
	}
	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 {
		return string()
	}
	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 {
	case formNone:
		if .kind() == KindInvalid {
			return "<invalid jsontext.Token>", nil
		}
		return .kind().String(), nil
	case formRaw:
		 := .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, )
		return string(), nil
	case formString:
		return .str, nil
	}
	return string(.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 {
	case formInt:
		return intfmt.AppendInt(, int64(.num))
	case formUint:
		return intfmt.AppendUint(, .num)
	case formFloat:
		return appendFloatText(, math.Float64frombits(.num), 64)
	default:
		return appendFloatText(, 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()
	var  int64
	var  error
	switch .source().form {
	case formInt:
		return int64(.num), nil
	case formUint:
		if .num > math.MaxInt64 {
			,  = math.MaxInt64, strconv.ErrRange
		} else {
			 = int64(.num)
		}
	case formFloat, 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()
	var  uint64
	var  error
	switch .source().form {
	case formUint:
		return .num, nil
	case formInt:
		if int64(.num) < 0 {
			 = strconv.ErrSyntax
		} else {
			 = .num
		}
	case formFloat, 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)
	return float32(), 
}

func ( Token) ( int) (float64, error) {
	if .kind() == KindString {
		if ,  := .nonFinite();  {
			return , nil
		}
	}
	.panicUnlessNumber()
	switch .source().form {
	case formInt:
		return float64(int64(.num)), nil
	case formUint:
		return float64(.num), nil
	case formFloat, 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) {
	var  string
	switch .source().form {
	case formFloat, formFloat32:
		if  := math.Float64frombits(.num); !math.IsNaN() {
			return , true
		}
		return math.NaN(), true
	case formString:
		 = .str
	case formRaw:
		 = .String()
	}
	switch  {
	case "NaN":
		return math.NaN(), true
	case "Infinity":
		return math.Inf(+1), true
	case "-Infinity":
		return math.Inf(-1), true
	}
	return 0, 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) {
	var  error
	if  != 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)
		}
		return math.MaxInt64, 
	case  < -1<<63:
		return math.MinInt64, orErr(, strconv.ErrRange)
	}
	return int64(), 
}

// floatToUint is floatToInt for a uint64: a negative number is out of the syntax of an unsigned integer.
func floatToUint( float64) (uint64, error) {
	var  error
	if  != math.Trunc() || math.Signbit() {
		 = strconv.ErrSyntax
	}
	switch {
	case  >= 1<<64:
		if  > 1<<64 { // 2⁶⁴ is math.MaxUint64 rounded to a float64
			 = orErr(, strconv.ErrRange)
		}
		return math.MaxUint64, 
	case  <= 0:
		return 0, 
	}
	return uint64(), 
}

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 {
				return math.MinInt64, strconv.ErrRange
			}
			return -int64(), nil
		}
		if  > math.MaxInt64 {
			return math.MaxInt64, strconv.ErrRange
		}
		return int64(), nil
	} else if isDigits() {
		// an integer out of the range of a uint64
		if  {
			return math.MinInt64, strconv.ErrRange
		}
		return math.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
	} else if isDigits() {
		return math.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 {
	if len() == 0 || [0] == '0' && len() > 1 {
		return false
	}
	for ,  := range  {
		if  < '0' ||  > '9' {
			return false
		}
	}
	return true
}