// Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.

package zstd

import (
	
	
	
)

type seq struct {
	litLen   uint32
	matchLen uint32
	offset   uint32

	// Codes are stored here for the encoder
	// so they only have to be looked up once.
	llCode, mlCode, ofCode uint8
}

type seqVals struct {
	ll, ml, mo int
}

func ( seq) () string {
	if .offset <= 3 {
		if .offset == 0 {
			return fmt.Sprint("litLen:", .litLen, ", matchLen:", .matchLen+zstdMinMatch, ", offset: INVALID (0)")
		}
		return fmt.Sprint("litLen:", .litLen, ", matchLen:", .matchLen+zstdMinMatch, ", offset:", .offset, " (repeat)")
	}
	return fmt.Sprint("litLen:", .litLen, ", matchLen:", .matchLen+zstdMinMatch, ", offset:", .offset-3, " (new)")
}

type seqCompMode uint8

const (
	compModePredefined seqCompMode = iota
	compModeRLE
	compModeFSE
	compModeRepeat
)

type sequenceDec struct {
	// decoder keeps track of the current state and updates it from the bitstream.
	fse    *fseDecoder
	state  fseState
	repeat bool
}

// init the state of the decoder with input from stream.
func ( *sequenceDec) ( *bitReader) error {
	if .fse == nil {
		return errors.New("sequence decoder not defined")
	}
	.state.init(, .fse.actualTableLog, .fse.dt[:1<<.fse.actualTableLog])
	return nil
}

// sequenceDecs contains all 3 sequence decoders and their state.
type sequenceDecs struct {
	litLengths   sequenceDec
	offsets      sequenceDec
	matchLengths sequenceDec
	prevOffset   [3]int
	dict         []byte
	literals     []byte
	out          []byte
	nSeqs        int
	br           *bitReader
	seqSize      int
	windowSize   int
	maxBits      uint8
	maxSyncLen   uint64
}

// twoPassFarCode is the offset code from which a match counts as far: 20 is
// 1 MiB, the distance every measured arm64 core gains from. A Neoverse N1
// (Graviton2, Ampere Altra) gains from 128 KiB too, but that needs a
// per-core threshold override; not worth the CPU-specific special case for
// a core class already being phased out of the fleet.
const twoPassFarCode = 20

// useTwoPass reports whether the block is decoded in two passes with the
// match-source prefetch (seqdec_arm64.go): a window of at least
// decodeTwoPassMinWindow and, unless the offset table is predefined or
// RLE, a share of at least twoPassMinFarShare of codes twoPassFarCode+.
func ( *sequenceDecs) () bool {
	if .windowSize < decodeTwoPassMinWindow {
		return false
	}
	 := .offsets.fse
	if  != nil && !.preDefined && .actualTableLog != 0 && int(.symbolLen) <= twoPassFarCode {
		// No symbol reaches twoPassFarCode, so codeShare can only return 0:
		// skip finding it.
		return false
	}
	 := .codeShare(twoPassFarCode)
	return  < 0 ||  >= twoPassMinFarShare
}

// initialize all 3 decoders from the stream input.
func ( *sequenceDecs) ( *bitReader,  *history,  []byte) error {
	if  := .litLengths.init();  != nil {
		return errors.New("litLengths:" + .Error())
	}
	if  := .offsets.init();  != nil {
		return errors.New("offsets:" + .Error())
	}
	if  := .matchLengths.init();  != nil {
		return errors.New("matchLengths:" + .Error())
	}
	.br = 
	.prevOffset = .recentOffsets
	.maxBits = .litLengths.fse.maxBits + .offsets.fse.maxBits + .matchLengths.fse.maxBits
	.windowSize = .windowSize
	.out = 
	.dict = nil
	if .dict != nil {
		.dict = .dict.content
	}
	return nil
}

// consumeSyncLen accounts for n bytes of frame output produced outside
// decodeSync. maxSyncLen bounds how much the frame may still produce and
// decodeSyncSimple compares it with the output buffer's slack to decide
// whether the extended 16-byte copies are safe. Blocks with sequences
// subtracted their output; raw blocks, RLE blocks and compressed blocks
// holding only literals did not, so a frame that opened with a raw block
// overstated its remaining size for every block after it and ran the
// bounds-exact copies for the rest of the frame.
//
// Zero means "no bound" and selects the conservative paths, so a block that
// meets or exceeds the bound lands there; the frame-size checks in
// runDecoder reject the excess afterwards.
func ( *sequenceDecs) ( int) {
	if .maxSyncLen == 0 {
		return
	}
	if uint64() >= .maxSyncLen {
		.maxSyncLen = 0
		return
	}
	.maxSyncLen -= uint64()
}

func ( *sequenceDecs) () {
	if  := .litLengths.fse;  != nil && !.preDefined {
		fseDecoderPool.Put()
		.litLengths.fse = nil
	}
	if  := .offsets.fse;  != nil && !.preDefined {
		fseDecoderPool.Put()
		.offsets.fse = nil
	}
	if  := .matchLengths.fse;  != nil && !.preDefined {
		fseDecoderPool.Put()
		.matchLengths.fse = nil
	}
}

// execute will execute the decoded sequence with the provided history.
// The sequence must be evaluated before being sent.
func ( *sequenceDecs) ( []seqVals,  []byte) error {
	if len(.dict) == 0 {
		return .executeSimple(, )
	}

	// Ensure we have enough output size...
	if len(.out)+.seqSize > cap(.out) {
		 := .seqSize + len(.out)
		.out = append(.out, make([]byte, )...)
		.out = .out[:len(.out)-]
	}

	if debugDecoder {
		printf("Execute %d seqs with hist %d, dict %d, literals: %d into %d bytes\n", len(), len(), len(.dict), len(.literals), .seqSize)
	}

	var  = len(.out)
	 := .out[:+.seqSize]
	 := .literals
	 := .windowSize
	 := .dict

	for ,  := range  {
		// Short sequences copy 16 bytes for each part.
		if .ll <= 16 && .ml <= 16 && +.ll+16 <= cap() && cap() >= 16 {
			if  := matchSource(, , , +.ll, .mo, 16, );  != nil {
				*(*[16]byte)([ : +16]) = *(*[16]byte)([:16])
				 += .ll
				*(*[16]byte)([ : +16]) = *(*[16]byte)()
				 += .ml
				 = [.ll:]
				continue
			}
		}

		// Add literals
		copy([:], [:.ll])
		 += .ll
		 = [.ll:]

		// Copy from dictionary...
		if .mo > +len() || .mo >  {
			if len(.dict) == 0 {
				return fmt.Errorf("match offset (%d) bigger than current history (%d)", .mo, +len())
			}

			// we may be in dictionary.
			 := len(.dict) - (.mo - ( + len()))
			if  < 0 ||  >= len(.dict) {
				return fmt.Errorf("match offset (%d) bigger than current history+dict (%d)", .mo, +len()+len(.dict))
			}
			 :=  + .ml
			if  > len(.dict) {
				 := len(.dict) - 
				copy([:], .dict[:])
				 += 
				.ml -= 
			} else {
				copy([:], .dict[:])
				 +=  - 
				continue
			}
		}

		// Copy from history.
		if  := .mo - ;  > 0 {
			// v is the start position in history from end.
			 := len() - 
			if .ml >  {
				// Some goes into current block.
				// Copy remainder of history
				copy([:], [:])
				 += 
				.ml -= 
			} else {
				copy([:], [:+.ml])
				 += .ml
				continue
			}
		}
		// We must be in current buffer now
		if .ml > 0 {
			 :=  - .mo
			if .ml <= - {
				// No overlap
				copy([:], [:+.ml])
				 += .ml
				continue
			} else {
				// Overlapping copy
				overlapCopy(, , , .ml)
				 += .ml
			}
		}
	}

	// Add final literals
	copy([:], )
	.literals = 
	if debugDecoder {
		 += len()
		if  != len() {
			panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(), , .seqSize))
		}
	}
	.out = 

	return nil
}

// decodeSyncGoOnly makes decodeSync skip the assembly decoder, so tests can
// compare it with the Go one in the same binary.
var decodeSyncGoOnly bool

// decode sequences from the stream with the provided history.
func ( *sequenceDecs) ( []byte) error {
	if !decodeSyncGoOnly {
		,  := .decodeSyncSimple()
		if  {
			return 
		}
	}

	// The bit reader, repeat offsets and literals are held in locals so
	// they stay in registers; they are written back on success.
	 := .br
	,  := .in, .state()
	, ,  := .prevOffset[0], .prevOffset[1], .prevOffset[2]
	 := .literals
	 := .maxBits
	 := .windowSize
	 := .dict
	 := .nSeqs
	 := len(.out)
	// Grab full sizes tables, to avoid bounds checks.
	, ,  := .litLengths.fse.dt[:maxTablesize], .matchLengths.fse.dt[:maxTablesize], .offsets.fse.dt[:maxTablesize]
	, ,  := .litLengths.state.state, .matchLengths.state.state, .offsets.state.state
	 := .out
	 := min(, maxCompressedBlockSize)

	if debugDecoder {
		println("decodeSync: decoding", , "sequences", .remain(), "bits remain on stream")
	}
	for  :=  - 1;  >= 0; -- {
		if .bitsRead > 64 {
			.setState()
			printf("reading sequence %d, exceeded available data. Overread by %d\n", -, -.remain())
			return io.ErrUnexpectedEOF
		}
		var , ,  int
		// Final will not read from stream.
		var , ,  uint8
		,  = .final()
		,  = .final()
		,  = .final()

		// extra bits are stored in reverse order.
		var  int
		 = .fill()
		,  = .getBits()
		 += 
		if  > 32 {
			 = .fill()
		}
		,  = .getBits()
		 += 
		,  = .getBits()
		 += 

		if  > 1 {
			 = 
			 = 
			 = 
		} else {
			// mo = s.adjustOffset(mo, ll, moB)
			// Inlined for rather big speedup
			if  == 0 {
				// There is an exception though, when current sequence's literals_length = 0.
				// In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2,
				// an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte.
				++
			}

			if  == 0 {
				 = 
			} else {
				var  int
				switch  {
				case 1:
					 = 
				case 2:
					 = 
				default:
					 =  - 1
				}

				if  == 0 {
					// 0 is not valid; input is corrupted; force offset to 1
					println("WARNING: temp was 0")
					 = 1
				}

				if  != 1 {
					 = 
				}
				 = 
				 = 
				 = 
			}
		}
		 = .fill()

		if debugSequences {
			println("Seq", --1, "Litlen:", , "mo:", , "(abs) ml:", )
		}

		if  > len() {
			return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", , len())
		}
		 :=  +  + len()
		if - >  {
			return fmt.Errorf("output bigger than max block size (%d)", )
		}
		// Matches from earlier output, the history or the dictionary are
		// copied without calling executeSeq; short ones with fixed 16-byte copies, with no
		// calls so the loop state stays in registers.
		 := len()
		 :=  + 
		 :=  <= 16 &&  <= 16 && +16 <= cap() && cap() >= 16
		var  []byte
		if  {
			 = matchSource(, , , , , 16, )
		}
		if  == nil && + <= cap() {
			 = false
			 = matchSource(, , , , , , )
		}
		if  {
			*(*[16]byte)([ : +16]) = *(*[16]byte)([:16])
			*(*[16]byte)([ : +16]) = *(*[16]byte)()
			 = [:+]
			 = [:]
		} else if  != nil {
			 = [:+]
			copy([:], [:])
			copy([:], )
			 = [:]
		} else {
			var  error
			, ,  = .executeSeq(, , , , , , , )
			if  != nil {
				return 
			}
		}
		if  == 0 {
			// This is the last sequence, so we shouldn't update state.
			break
		}

		// Manually inlined, ~ 5-20% faster
		// Update all 3 states at once. Approx 20% faster.
		 := .nbBits() + .nbBits() + .nbBits()
		if  == 0 {
			 = [.newState()&maxTableMask]
			 = [.newState()&maxTableMask]
			 = [.newState()&maxTableMask]
		} else {
			var  uint32
			,  = .get32BitsFast()

			 := uint16( >> ((.nbBits() + .nbBits()) & 31))
			 = [(.newState()+)&maxTableMask]

			 = uint16( >> (.nbBits() & 31))
			 &= bitMask[.nbBits()&15]
			 = [(.newState()+)&maxTableMask]

			 = uint16() & bitMask[.nbBits()&15]
			 = [(.newState()+)&maxTableMask]
		}
	}

	if  := len() + len() - ;  >  {
		return fmt.Errorf("output bigger than max block size (%d)", )
	}

	// Add final literals
	.out = append(, ...)
	.literals = 
	.prevOffset = [3]int{, , }
	.setState()
	return .close()
}

// overlapCopy writes n bytes at out[t:] repeating out[start:t], which
// overlaps the destination. Each copy doubles the repeated span, so it takes
// about log2(n/(t-start)) copies instead of n byte moves.
func overlapCopy( []byte, , ,  int) {
	if  >=  {
		// Nothing to repeat; callers reject a zero offset.
		return
	}
	for  :=  + ;  < ; {
		 += copy([:], [:])
	}
}

// matchSource returns the n bytes a match of length n at p in out copies
// from: earlier output it does not overlap, the history or the dictionary.
// It returns nil when the match needs the general path. It must stay
// inlinable: a call would spill the decode loop's state.
func matchSource(, ,  []byte, , , ,  int) []byte {
	// v is how far the match starts back from the end of hist, and d how
	// far it reaches past hist into dict.
	if  <=  {
		if  >=  &&  <=  {
			return [- : -+]
		}
		if  :=  - ;  >=  &&  <= len() {
			return [len()-:][:]
		}
	}
	if  :=  - ( + len());  >=  &&  <= len() {
		return [len()-:][:]
	}
	return nil
}

// executeSeq appends the literals and match of one sequence to out and
// returns the updated out and remaining literals.
func ( *sequenceDecs) (, ,  []byte, , , , ,  int) ([]byte, []byte, error) {
	if ++len() > cap() {
		// Not enough size, which can happen under high volume block streaming conditions
		// but could be if destination slice is too small for sync operations.
		// over-allocating here can create a large amount of GC pressure so we try to keep
		// it as contained as possible
		 := len() - 
		 := 256 +  +  + >>2
		// Clamp to max block size.
		if + >  {
			 =  - 
		}
		 = append(, make([]byte, )...)
		 = [:len()-]
	}
	if  > maxMatchLen {
		return nil, nil, fmt.Errorf("match len (%d) bigger than max allowed length", )
	}

	// Add literals
	 = append(, [:]...)
	 = [:]

	if  == 0 &&  > 0 {
		return nil, nil, fmt.Errorf("zero matchoff and matchlen (%d) > 0", )
	}

	if  > len()+len() ||  > .windowSize {
		if len(.dict) == 0 {
			return nil, nil, fmt.Errorf("match offset (%d) bigger than current history (%d)", , len()-)
		}

		// we may be in dictionary.
		 := len(.dict) - ( - (len() + len()))
		if  < 0 ||  >= len(.dict) {
			return nil, nil, fmt.Errorf("match offset (%d) bigger than current history (%d)", , len()-)
		}
		 :=  + 
		if  > len(.dict) {
			 = append(, .dict[:]...)
			 -= len(.dict) - 
		} else {
			 = append(, .dict[:]...)
			 = 0
			 = 0
		}
	}

	// Copy from history.
	// TODO: Blocks without history could be made to ignore this completely.
	if  :=  - len();  > 0 {
		// v is the start position in history from end.
		 := len() - 
		if  >  {
			// Some goes into current block.
			// Copy remainder of history
			 = append(, [:]...)
			 -= 
		} else {
			 = append(, [:+]...)
			 = 0
		}
	}
	// We must be in current buffer now
	if  > 0 {
		 := len() - 
		if  <= len()- {
			// No overlap
			 = append(, [:+]...)
		} else {
			// Overlapping copy
			 = [:len()+]
			overlapCopy(, , len()-, )
		}
	}
	return , , nil
}

var bitMask [16]uint16

func init() {
	for  := range bitMask[:] {
		bitMask[] = uint16((1 << uint()) - 1)
	}
}

func ( *sequenceDecs) (,  int,  uint8) int {
	if  > 1 {
		.prevOffset[2] = .prevOffset[1]
		.prevOffset[1] = .prevOffset[0]
		.prevOffset[0] = 
		return 
	}

	if  == 0 {
		// There is an exception though, when current sequence's literals_length = 0.
		// In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2,
		// an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte.
		++
	}

	if  == 0 {
		return .prevOffset[0]
	}
	var  int
	if  == 3 {
		 = .prevOffset[0] - 1
	} else {
		 = .prevOffset[]
	}

	if  == 0 {
		// 0 is not valid; input is corrupted; force offset to 1
		println("temp was 0")
		 = 1
	}

	if  != 1 {
		.prevOffset[2] = .prevOffset[1]
	}
	.prevOffset[1] = .prevOffset[0]
	.prevOffset[0] = 
	return 
}