package jsontext

import (
	
	
	
	

	
	
)

func init() {
	textcoder.AttachDecoder = attachDecoder
	textcoder.DetachDecoder = detachDecoder
	textcoder.UnmarshalPlaceAt = unmarshalPlaceAt
	textcoder.DecoderPlace = decoderPlace
	textcoder.DecoderAt = func( unsafe.Pointer) (bool, textcoder.Outer, int) {
		 := &(*Decoder)().d
		if !.ready() {
			.setUp()
		}
		return .st.last().needName(), .st.outer, .st.depth() + .st.base
	}
	textcoder.BeginValue = beginValue
	textcoder.DecoderInput = func( unsafe.Pointer,  int64) ([]byte, io.Reader) {
		 := &(*Decoder)().d
		return .buf[-.base:], .r
	}
	textcoder.DecoderBuffer = func( unsafe.Pointer) ([]byte, int64, bool) {
		 := &(*Decoder)().d
		return .buf, .base, !.shared && .bb == nil && .r != nil && cap(.buf)-len(.buf) >= textcoder.InputRoom
	}
	textcoder.FetchInput = func( unsafe.Pointer,  int64,  int) ([]byte, int64, int, error) {
		 := &(*Decoder)().d
		// the bytes before keep are dropped as the ones before the last token are: the positions of the decoder
		// before them are the start of the buffer then, which the caller sets by EndValue or PutBack
		var  int
		if cap(.buf)-len(.buf) <= textcoder.InputRoom {
			// the buffer is full, as a stream finds its buffer full before it reads ( see decoder.Stream.read )
			 := .prevStart
			.prevStart = int( - .base)
			 = .makeRoom( + textcoder.InputRoom)
			.prevStart =  - 
		}
		.pos, .prevStart, .prevEnd = max(.pos, 0), max(.prevStart, 0), max(.prevEnd, 0)
		,  := .r.Read(.buf[len(.buf):min(cap(.buf)-textcoder.InputRoom, len(.buf)+)])
		.buf = .buf[:len(.buf)+]
		return .buf, .base, , 
	}
	textcoder.EndValue = endValue
	textcoder.PutBack = func( unsafe.Pointer,  int64,  []byte) {
		 := &(*Decoder)().d
		if .shared {
			.buf, .shared = nil, false
		}
		.buf = append(.buf[:0], ...)
		.base, .pos, .prevStart, .prevEnd = , 0, 0, 0
	}
	textcoder.SkipToEnd = skipToEnd
	textcoder.FailDecoder = func( unsafe.Pointer,  error) {
		 := &(*Decoder)().d
		.buf, .shared = .buf[:.pos], true
		.r, .bb, .rerr, .peekErr = &failedInput{err: }, nil, nil, nil
	}
	textcoder.DecoderFailed = func( unsafe.Pointer) bool {
		,  := (*Decoder)().d.r.(*failedInput)
		return 
	}
	textcoder.ConfigureDecoder = func( unsafe.Pointer,  *options.Config) func() {
		 := &(*Decoder)().d
		, ,  := .cfg, .vs.validUTF8, .vs.rejectDuplicateNames
		.cfg = *
		.vs.validUTF8, .vs.rejectDuplicateNames = !.cfg.Has(allowInvalidUTF8), !.cfg.Has(allowDuplicateNames)
		return func() {
			.cfg, .vs.validUTF8, .vs.rejectDuplicateNames = , , 
		}
	}
	textcoder.ReadError = func( error) error { return &ioError{err: } }
	textcoder.IsIOError = func( error) bool {
		var  *ioError
		return errors.As(, &)
	}
	textcoder.AfterTopLevelError = func( []byte,  int64,  *options.Config) error {
		 := NewDecoder(bytes.NewBuffer(), )
		.d.base = 
		return .d.charError(0, placeAfterTopLevel, pointAt)
	}
	textcoder.ReleaseDecoder = func( unsafe.Pointer) {
		 := &(*Decoder)().d
		.cfg = config{}
		.st.outer = nil
		if .r != &attachedInput {
			.r, .bb = nil, nil // the reader of an input which is read on, which the decoder must not keep
		}
	}
	textcoder.DecoderPointer = func( unsafe.Pointer,  int) string {
		 := &(*Decoder)().d.st
		switch  {
		case -1:
			return string(.pointer(pointLast))
		case +1:
			return string(.pointer(pointNext))
		}
		return string(.pointer(pointAt))
	}
}

// attachedInput is the reader of an attached decoder, whose input is all in its buffer: an empty bytes.Buffer, which
// is never written to, which makes the decoder read its buffer in place, and nothing after it.
var attachedInput bytes.Buffer

// attachDecoder makes the Decoder dec read p.In from p.Pos, at the place whose innermost level is the one of p ( see
// textcoder.AttachDecoder ). The input is read in place: it is the array of a bytes.Buffer for the decoder, which
// never writes to it, and, if p has a reader, the buffer of the decoder, which it moves and reads into, once it
// needs more.
func attachDecoder( unsafe.Pointer,  *textcoder.DecoderAttachment) {
	 := &(*Decoder)().d
	if !(.Same && .R == nil && .ready() && .r == &attachedInput) {
		// set up as reset sets up a decoder of a reader, by the options of the call, without the options of a
		// reset, which would be allocated.
		if !.ready() {
			.st, .vs.scratch = stack{}, nil
		}
		.cfg = *.Opts
		.r, .bb = &attachedInput, &attachedInput
		if .R != nil {
			.r, .bb = .R, nil
		}
		.raw = tokenSource{dec: , form: formRaw}
		.vs = valueScanner{
			st:                   &.st,
			validUTF8:            !.cfg.Has(allowInvalidUTF8),
			rejectDuplicateNames: !.cfg.Has(allowDuplicateNames),
			decoding:             true,
			scratch:              .vs.scratch[:0],
		}
	}
	 := &.st
	.reset()
	if !.Top {
		_ = .push(.Object)
	}
	// the names of an object, which the value read at its place can't have, are not given.
	.last().count = .Count
	.outer, .outerDepth, .outerCount = .Outer, len(.levels)-1, .Count
	.base = .OuterDepth - .outerDepth
	.buf, .shared = .In, !.Own
	.base, .pos, .prevStart, .prevEnd = .Base, .Pos, .Pos, .Pos
	.rerr, .peekErr = nil, nil
	.vs.scratch = .vs.scratch[:0]
	.Depth = .depth()
}

// detachDecoder sets where dec stopped reading in p, and drops its input ( see textcoder.DetachDecoder ).
func detachDecoder( unsafe.Pointer,  *textcoder.DecoderAttachment) {
	 := &(*Decoder)().d
	 := .prevStart
	if  == .prevEnd &&  > 0 {
		// a delimiter or a literal, which ends there: the buffer doesn't keep it as the last token.
		if  := .buf[-1];  == '{' ||  == '}' ||  == '[' ||  == ']' {
			--
		} else {
			for  > 0 && 'a' <= .buf[-1] && .buf[-1] <= 'z' {
				--
			}
		}
	}
	.Depth, .Count, .Pos, .End, .PrevStart = .st.depth(), .st.last().count, .pos, .base+int64(.pos), .base+int64()
	.Rest = nil
	if !.shared {
		// the decoder read on into a buffer of its own, whose bytes after the place go back to the caller
		.Rest = .buf[.pos:]
		if .Own {
			.In = .buf
		}
	}
	.buf, .vs.in = nil, nil
	.pos, .prevStart, .prevEnd = 0, 0, 0
	.peekErr = nil
}

// unmarshalPlace is textcoder.UnmarshalPlace: the input is read by a Decoder, token by token, as encoding/json/v2
// reads it, which finds its syntax errors and the pointer of the value at stop as encoding/json/v2 does.
func unmarshalPlace( []byte,  *options.Config,  int64,  textcoder.Read) (string, error) {
	 := NewDecoder(bytes.NewBuffer(), )
	 := &.d
	for {
		if  >= 0 {
			if ,  := .beforeToken(true);  == nil && .base+int64() >=  {
				return readPlace(, )
			}
		}
		if ,  := .ReadToken();  != nil {
			if  == io.EOF {
				// an input of white space only, which has no value
				return "", &SyntacticError{ByteOffset: int64(len()), Err: io.ErrUnexpectedEOF}
			}
			return "", 
		}
		if .st.depth() == 0 {
			// the value is read: only white space may follow it
			,  := .skip(.pos)
			if  == nil {
				return "", .charError(, placeAfterTopLevel, pointAt)
			}
			return "", nil
		}
	}
}

// decoderPlace is textcoder.DecoderPlace.
func decoderPlace( unsafe.Pointer,  []textcoder.Level) []textcoder.Level {
	 := &(*Decoder)().d
	if !.ready() {
		.setUp()
	}
	 := &.st
	if .outer != nil {
		 = .full()
	}
	for  := range .levels {
		 := &.levels[]
		 := len()
		if  < cap() {
			// the entry, whose name keeps its array, which the name is copied into
			 = [:+1]
		} else {
			 = append(, textcoder.Level{})
		}
		 := &[]
		.Object, .Count = .object, .count
		if  < len(.levels)-1 {
			.Count-- // the value of the next level, which is open, is not counted
		}
		if !.object || .last < .first {
			.Name = nil
		} else if .Name = append(.Name[:0], .names.get(.last)...); .Name == nil {
			// the name "", which is a name, as a level without a name has none ( see textcoder.Level )
			.Name = []byte{}
		}
	}
	return 
}

// beginValue is textcoder.BeginValue: the start of readValue, up to the value, which is not a name.
func beginValue( unsafe.Pointer) (int64, error) {
	 := &(*Decoder)().d
	if !.ready() {
		.setUp()
	}
	.invalidate()
	if  := .peekErr;  != nil {
		.peekErr = nil
		return 0, 
	}
	,  := .beforeToken(false)
	if  != nil {
		return 0, 
	}
	if  := .buf[];  == '}' ||  == ']' {
		// as readValue reports an end delimiter where a value is
		if  := .st.last(); !(.needValue() &&  == '}') {
			if  := .closeError();  != nil {
				return 0, 
			}
		}
		return 0, .charError(, placeStartOfValue, pointNext)
	}
	return .base + int64(), nil
}

// endValue is textcoder.EndValue: the decoder is where done leaves it after a value, which its level counts.
func endValue( unsafe.Pointer, ,  int64,  []byte) {
	 := &(*Decoder)().d
	if  == nil {
		// the start of the value may be before the buffer, which dropped it for the caller, which read more into
		// it ( see textcoder.FetchInput )
		.done(int(-.base), int(-.base))
	} else {
		// the input after the value, which the reader gave the caller, in a buffer of the decoder, before which the
		// value starts
		if .shared {
			.buf, .shared = nil, false
		}
		.buf = append(.buf[:0], ...)
		.base, .pos, .prevStart, .prevEnd = , 0, int(-), 0
	}
	.st.last().count++
}

// skipToEnd is textcoder.SkipToEnd: the input is read as unmarshalPlaceAt reads it.
func skipToEnd( *textcoder.DecoderAttachment,  int,  int64) (int64, []byte, error) {
	 := new(Decoder)
	attachDecoder(unsafe.Pointer(), )
	 := &.d
	if .st.outer != nil {
		.st = *.st.full()
	}
	for .st.depth() !=  || .st.levels[].count <=  {
		if ,  := .ReadToken();  != nil {
			return 0, nil, 
		}
	}
	var  []byte
	if !.shared {
		 = .buf[.pos:]
	}
	return .base + int64(.pos), , nil
}

// failedInput is the reader of a decoder which failed ( see textcoder.FailDecoder ): every read returns err, which
// the decoder returns as it is.
type failedInput struct{ err error }

func ( *failedInput) ([]byte) (int, error) { return 0, .err }

// unmarshalPlaceAt is textcoder.UnmarshalPlaceAt: the part of the input is read by a Decoder attached at its place,
// whose stack is made the one of the whole input, so that the levels of the place may end in the part.
func unmarshalPlaceAt( *textcoder.DecoderAttachment,  int64,  textcoder.Read) (string, error) {
	 := new(Decoder)
	attachDecoder(unsafe.Pointer(), )
	 := &.d
	if .st.outer != nil {
		.st = *.st.full()
	}
	for {
		if  >= 0 {
			if ,  := .beforeToken(true);  == nil && .base+int64() >=  {
				return readPlace(, )
			}
		}
		if ,  := .ReadToken();  != nil {
			if  == io.EOF {
				return "", nil
			}
			return "", 
		}
		if .st.depth() == 0 {
			return "", nil
		}
	}
}

// skipperOptions are the options of the skippers, by AllowDuplicateNames and AllowInvalidUTF8, made once so that a
// call makes no Options.
var skipperOptions = func() [2][2][]Options {
	var  [2][2][]Options
	for ,  := range []bool{false, true} {
		for ,  := range []bool{false, true} {
			[][] = []Options{AllowDuplicateNames(), AllowInvalidUTF8()}
		}
	}
	return 
}()

// takeSkipper is textcoder.TakeSkipper: an encoder of the pool, whose scanner doesn't write. Its options are set
// once: the fields of the scanner which they make are not set again by a call ( see encoder.init ).
func takeSkipper(,  bool) unsafe.Pointer {
	var ,  int
	if  {
		 = 1
	}
	if  {
		 = 1
	}
	 := getEncoder(skipperOptions[][])
	.vs.write, .vs.spaced = false, false
	return unsafe.Pointer()
}

// releaseSkipper is textcoder.ReleaseSkipper.
func releaseSkipper( unsafe.Pointer) { putEncoder((*encoder)()) }

// validValue is textcoder.ValidValue: v is checked as Value.IsValid checks it, by the scanner of the skipper, which
// doesn't write it and reports no place of an error: the count of the innermost level, which only the places tell,
// goes on.
func validValue( unsafe.Pointer,  []byte) bool {
	,  := (*encoder)().vs.scan(, 0)
	return  == nil &&  == len()
}

// readPlace reads the value at the start of the input of dec as read says, and returns the syntax error it meets,
// or else the pointer of the value.
func readPlace( *Decoder,  textcoder.Read) (string, error) {
	switch  {
	case textcoder.ReadNothing:
		return string(.d.st.pointer(pointNext)), nil
	case textcoder.ReadValue:
		if ,  := .ReadValue();  != nil {
			return "", 
		}
	default:
		if ,  := .ReadToken();  != nil {
			return "", 
		}
	}
	return string(.d.st.pointer(pointLast)), nil
}