//go:build (amd64 || arm64) && !appengine && !noasm && gc

package zstd

import (
	
	
)

// This file holds the parts of the assembly sequence decoder that are identical
// across architectures: the context structs exchanged with the asm, the error
// codes, and the decode/decodeSync/executeSimple wrappers. Each architecture
// supplies the small dispatch helpers (decodeAsm, decodeSyncAsm,
// executeSimpleAsm) that select the concrete asm routine — amd64 also chooses a
// BMI2 variant, arm64 has a single implementation.

type decodeSyncAsmContext struct {
	llTable     []decSymbol
	mlTable     []decSymbol
	ofTable     []decSymbol
	llState     uint64
	mlState     uint64
	ofState     uint64
	iteration   int
	litRemain   int
	out         []byte
	outPosition int
	literals    []byte
	litPosition int
	history     []byte
	windowSize  int
	ll          int // set on error (not for all errors, please refer to _generate/gen.go)
	ml          int // set on error (not for all errors, please refer to _generate/gen.go)
	mo          int // set on error (not for all errors, please refer to _generate/gen.go)
}

type decodeAsmContext struct {
	llTable   []decSymbol
	mlTable   []decSymbol
	ofTable   []decSymbol
	llState   uint64
	mlState   uint64
	ofState   uint64
	iteration int
	seqs      []seqVals
	litRemain int
}

type executeAsmContext struct {
	seqs        []seqVals
	seqIndex    int
	out         []byte
	history     []byte
	literals    []byte
	outPosition int
	litPosition int
	windowSize  int
}

const noError = 0

// error reported when mo == 0 && ml > 0
const errorMatchLenOfsMismatch = 1

// error reported when ml > maxMatchLen
const errorMatchLenTooBig = 2

// error reported when mo > available history or mo > s.windowSize
const errorMatchOffTooBig = 3

// error reported when the sum of literal lengths exeeceds the literal buffer size
const errorNotEnoughLiterals = 4

// error reported when capacity of `out` is too small
const errorNotEnoughSpace = 5

// error reported when bits are overread.
const errorOverread = 6

// useSafeDecodeSync reports whether decodeSyncSimple must use the bounds-exact
// ("safe") copy variants for the current buffer geometry.
//
// When the output and literal buffers have compressedBlockOverAlloc (16)
// bytes of slack past their logical use, the assembly may use extended
// memory copies that read and write in 16-byte blocks, overrunning the end
// of a literal run or match by up to 15 bytes. Otherwise it must use the
// bounds-exact ("safe") copies. This mirrors the analogous, always-dynamic
// selection in executeSimple below.
//
// The unsafe copies were disabled in #644 (2022) as a mitigation for a
// crash, but that crash's root cause — an unguarded bitReader overread that
// produced out-of-range match offsets/lengths — was fixed three days later
// in #645, which also added the fuzz corpus that has guarded this path since.
// See #1168. An asan-instrumented fuzz job (see .github/workflows/go.yml)
// covers the extended-copy path, which -race and plain fuzzing cannot.
func ( *sequenceDecs) () bool {
	if .maxSyncLen == 0 && cap(.out)-len(.out) < maxCompressedBlockSizeAlloc {
		return true
	}
	if .maxSyncLen > 0 && cap(.out)-len(.out)-compressedBlockOverAlloc < int(.maxSyncLen) {
		return true
	}
	if cap(.literals) < len(.literals)+compressedBlockOverAlloc {
		return true
	}
	return false
}

// decode sequences from the stream with the provided history but without a dictionary.
func ( *sequenceDecs) ( []byte) (bool, error) {
	if len(.dict) > 0 {
		return false, nil
	}
	if .maxSyncLen == 0 && cap(.out)-len(.out) < maxCompressedBlockSize {
		return false, nil
	}

	 := .useSafeDecodeSync()

	 := .br

	 := min(.windowSize, maxCompressedBlockSize)

	 := decodeSyncAsmContext{
		llTable:     .litLengths.fse.dt[:maxTablesize],
		mlTable:     .matchLengths.fse.dt[:maxTablesize],
		ofTable:     .offsets.fse.dt[:maxTablesize],
		llState:     uint64(.litLengths.state.state),
		mlState:     uint64(.matchLengths.state.state),
		ofState:     uint64(.offsets.state.state),
		iteration:   .nSeqs - 1,
		litRemain:   len(.literals),
		out:         .out,
		outPosition: len(.out),
		literals:    .literals,
		windowSize:  .windowSize,
		history:     ,
	}

	.seqSize = 0
	 := len(.out)

	 := decodeSyncAsm(, , &, )
	switch  {
	case noError:
		break

	case errorMatchLenOfsMismatch:
		return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", .ml)

	case errorMatchLenTooBig:
		return true, fmt.Errorf("match len (%d) bigger than max allowed length", .ml)

	case errorMatchOffTooBig:
		return true, fmt.Errorf("match offset (%d) bigger than current history (%d)",
			.mo, .outPosition+len()-)

	case errorNotEnoughLiterals:
		return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available",
			.ll, .litRemain+.ll)

	case errorOverread:
		return true, io.ErrUnexpectedEOF

	case errorNotEnoughSpace:
		 := .outPosition + .ll + .ml
		if debugDecoder {
			println("msl:", .maxSyncLen, "cap", cap(.out), "bef:", , "sz:", -, "mbs:", , "outsz:", cap(.out)-)
		}
		return true, fmt.Errorf("output bigger than max block size (%d)", )

	default:
		return true, fmt.Errorf("sequenceDecs_decode returned erroneous code %d", )
	}

	.seqSize += .litRemain
	if .seqSize >  {
		return true, fmt.Errorf("output bigger than max block size (%d)", )
	}
	 := .close()
	if  != nil {
		printf("Closing sequences: %v, %+v\n", , *)
		return true, 
	}

	.literals = .literals[.litPosition:]
	 := .outPosition
	.out = .out[:]

	// Add final literals
	.out = append(.out, .literals...)
	if debugDecoder {
		 += len(.literals)
		if  != len(.out) {
			panic(fmt.Errorf("length mismatch, want %d, got %d", len(.out), ))
		}
	}

	return true, nil
}

// decode sequences from the stream without the provided history.
func ( *sequenceDecs) ( []seqVals) error {
	 := .br

	 := min(.windowSize, maxCompressedBlockSize)

	 := decodeAsmContext{
		llTable:   .litLengths.fse.dt[:maxTablesize],
		mlTable:   .matchLengths.fse.dt[:maxTablesize],
		ofTable:   .offsets.fse.dt[:maxTablesize],
		llState:   uint64(.litLengths.state.state),
		mlState:   uint64(.matchLengths.state.state),
		ofState:   uint64(.offsets.state.state),
		seqs:      ,
		iteration: len() - 1,
		litRemain: len(.literals),
	}

	if debugDecoder {
		println("decode: decoding", len(), "sequences", .remain(), "bits remain on stream")
	}

	.seqSize = 0
	 := .maxBits+.offsets.fse.actualTableLog+.matchLengths.fse.actualTableLog+.litLengths.fse.actualTableLog <= 56
	 := decodeAsm(, , &, )
	if  != 0 {
		 := len() - .iteration - 1
		switch  {
		case errorMatchLenOfsMismatch:
			 := .seqs[].ml
			return fmt.Errorf("zero matchoff and matchlen (%d) > 0", )

		case errorMatchLenTooBig:
			 := .seqs[].ml
			return fmt.Errorf("match len (%d) bigger than max allowed length", )

		case errorNotEnoughLiterals:
			 := .seqs[].ll
			return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", , .litRemain+)
		case errorOverread:
			return io.ErrUnexpectedEOF
		}

		return fmt.Errorf("sequenceDecs_decode_amd64 returned erroneous code %d", )
	}

	if .litRemain < 0 {
		return fmt.Errorf("literal count is too big: total available %d, total requested %d",
			len(.literals), len(.literals)-.litRemain)
	}

	.seqSize += .litRemain
	if .seqSize >  {
		return fmt.Errorf("output bigger than max block size (%d)", )
	}
	if debugDecoder {
		println("decode: ", .remain(), "bits remain on stream. code:", )
	}
	 := .close()
	if  != nil {
		printf("Closing sequences: %v, %+v\n", , *)
	}
	return 
}

// executeSimple handles cases when dictionary is not used.
func ( *sequenceDecs) ( []seqVals,  []byte) error {
	// Ensure we have enough output size...
	if len(.out)+.seqSize+compressedBlockOverAlloc > cap(.out) {
		 := .seqSize + len(.out) + compressedBlockOverAlloc
		.out = append(.out, make([]byte, )...)
		.out = .out[:len(.out)-]
	}

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

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

	 := executeAsmContext{
		seqs:        ,
		seqIndex:    0,
		out:         ,
		history:     ,
		outPosition: ,
		litPosition: 0,
		literals:    .literals,
		windowSize:  .windowSize,
	}
	// useSafe avoids overwriting the output buffer when the literals slice has
	// not been allocated with the required over-allocation slack.
	 := cap(.literals) < len(.literals)+compressedBlockOverAlloc

	 := executeSimpleAsm(&, )
	if ! {
		return fmt.Errorf("match offset (%d) bigger than current history (%d)",
			[.seqIndex].mo, .outPosition+len())
	}
	.literals = .literals[.litPosition:]
	 = .outPosition

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

	return nil
}