// 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 blockType uint8

//go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex

const (
	blockTypeRaw blockType = iota
	blockTypeRLE
	blockTypeCompressed
	blockTypeReserved
)

type literalsBlockType uint8

const (
	literalsBlockRaw literalsBlockType = iota
	literalsBlockRLE
	literalsBlockCompressed
	literalsBlockTreeless
)

const (
	// maxCompressedBlockSize is the biggest allowed compressed block size (128KB)
	maxCompressedBlockSize = 128 << 10

	compressedBlockOverAlloc    = 16
	maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc

	// Maximum possible block size (all Raw+Uncompressed).
	maxBlockSize = (1 << 21) - 1

	maxMatchLen  = 131074
	maxSequences = 0x7f00 + 0xffff

	// We support slightly less than the reference decoder to be able to
	// use ints on 32 bit archs.
	maxOffsetBits = 30
)

var (
	huffDecoderPool = sync.Pool{New: func() interface{} {
		return &huff0.Scratch{}
	}}

	fseDecoderPool = sync.Pool{New: func() interface{} {
		return &fseDecoder{}
	}}
)

type blockDec struct {
	// Raw source data of the block.
	data        []byte
	dataStorage []byte

	// Destination of the decoded data.
	dst []byte

	// Buffer for literals data.
	literalBuf []byte

	// Window size of the block.
	WindowSize uint64

	err error

	// Check against this crc, if hasCRC is true.
	checkCRC uint32
	hasCRC   bool

	// Frame to use for singlethreaded decoding.
	// Should not be used by the decoder itself since parent may be another frame.
	localFrame *frameDec

	sequence []seqVals

	async struct {
		newHist  *history
		literals []byte
		seqData  []byte
		seqSize  int // Size of uncompressed sequences
		fcs      uint64
	}

	// Block is RLE, this is the size.
	RLESize uint32

	Type blockType

	// Is this the last block of a frame?
	Last bool

	// Use less memory
	lowMem bool
}

func ( *blockDec) () string {
	if  == nil {
		return "<nil>"
	}
	return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(.data), .Type, .Last, .WindowSize)
}

func newBlockDec( bool) *blockDec {
	 := blockDec{
		lowMem: ,
	}
	return &
}

// reset will reset the block.
// Input must be a start of a block and will be at the end of the block when returned.
func ( *blockDec) ( byteBuffer,  uint64) error {
	.WindowSize = 
	,  := .readSmall(3)
	if  != nil {
		println("Reading block header:", )
		return 
	}
	 := uint32([0]) | (uint32([1]) << 8) | (uint32([2]) << 16)
	.Last = &1 != 0
	.Type = blockType(( >> 1) & 3)
	// find size.
	 := int( >> 3)
	 := maxCompressedBlockSizeAlloc
	switch .Type {
	case blockTypeReserved:
		return ErrReservedBlockType
	case blockTypeRLE:
		if  > maxCompressedBlockSize ||  > int(.WindowSize) {
			if debugDecoder {
				printf("rle block too big: csize:%d block: %+v\n", uint64(), )
			}
			return ErrWindowSizeExceeded
		}
		.RLESize = uint32()
		if .lowMem {
			 = 
		}
		 = 1
	case blockTypeCompressed:
		if debugDecoder {
			println("Data size on stream:", )
		}
		.RLESize = 0
		 = maxCompressedBlockSizeAlloc
		if  < maxCompressedBlockSize && .lowMem {
			 = int() + compressedBlockOverAlloc
		}
		if  > maxCompressedBlockSize || uint64() > .WindowSize {
			if debugDecoder {
				printf("compressed block too big: csize:%d block: %+v\n", uint64(), )
			}
			return ErrCompressedSizeTooBig
		}
		// Empty compressed blocks must at least be 2 bytes
		// for Literals_Block_Type and one for Sequences_Section_Header.
		if  < 2 {
			return ErrBlockTooSmall
		}
	case blockTypeRaw:
		if  > maxCompressedBlockSize ||  > int(.WindowSize) {
			if debugDecoder {
				printf("rle block too big: csize:%d block: %+v\n", uint64(), )
			}
			return ErrWindowSizeExceeded
		}

		.RLESize = 0
		// We do not need a destination for raw blocks.
		 = -1
	default:
		panic("Invalid block type")
	}

	// Read block data.
	if ,  := .(*byteBuf); ! && cap(.dataStorage) <  {
		// byteBuf doesn't need a destination buffer.
		if .lowMem ||  > maxCompressedBlockSize {
			.dataStorage = make([]byte, 0, +compressedBlockOverAlloc)
		} else {
			.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc)
		}
	}
	.data,  = .readBig(, .dataStorage)
	if  != nil {
		if debugDecoder {
			println("Reading block:", , "(", , ")", len(.data))
			printf("%T", )
		}
		return 
	}
	if cap(.dst) <=  {
		.dst = make([]byte, 0, +1)
	}
	return nil
}

// sendEOF will make the decoder send EOF on this frame.
func ( *blockDec) ( error) {
	.Last = true
	.Type = blockTypeReserved
	.err = 
}

// Close will release resources.
// Closed blockDec cannot be reset.
func ( *blockDec) () {
}

// decodeBuf
func ( *blockDec) ( *history) error {
	switch .Type {
	case blockTypeRLE:
		if cap(.dst) < int(.RLESize) {
			if .lowMem {
				.dst = make([]byte, .RLESize)
			} else {
				.dst = make([]byte, maxCompressedBlockSize)
			}
		}
		.dst = .dst[:.RLESize]
		 := .data[0]
		for  := range .dst {
			.dst[] = 
		}
		.appendKeep(.dst)
		return nil
	case blockTypeRaw:
		.appendKeep(.data)
		return nil
	case blockTypeCompressed:
		 := .dst
		// Append directly to history
		if .ignoreBuffer == 0 {
			.dst = .b
			.b = nil
		} else {
			.dst = .dst[:0]
		}
		 := .decodeCompressed()
		if debugDecoder {
			println("Decompressed to total", len(.dst), "bytes, hash:", xxhash.Sum64(.dst), "error:", )
		}
		if .ignoreBuffer == 0 {
			.b = .dst
			.dst = 
		} else {
			.appendKeep(.dst)
		}
		return 
	case blockTypeReserved:
		// Used for returning errors.
		return .err
	default:
		panic("Invalid block type")
	}
}

func ( *blockDec) ( []byte,  *history) ( []byte,  error) {
	// There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header
	if len() < 2 {
		return , ErrBlockTooSmall
	}

	 := literalsBlockType([0] & 3)
	var  int
	var  int
	 := ([0] >> 2) & 3
	var  bool
	var  []byte
	switch  {
	case literalsBlockRaw, literalsBlockRLE:
		switch  {
		case 0, 2:
			// Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte.
			 = int([0] >> 3)
			 = [1:]
		case 1:
			// Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes.
			 = int([0]>>4) + (int([1]) << 4)
			 = [2:]
		case 3:
			//  Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes.
			if len() < 3 {
				println("too small: litType:", , " sizeFormat", , len())
				return , ErrBlockTooSmall
			}
			 = int([0]>>4) + (int([1]) << 4) + (int([2]) << 12)
			 = [3:]
		}
	case literalsBlockCompressed, literalsBlockTreeless:
		switch  {
		case 0, 1:
			// Both Regenerated_Size and Compressed_Size use 10 bits (0-1023).
			if len() < 3 {
				println("too small: litType:", , " sizeFormat", , len())
				return , ErrBlockTooSmall
			}
			 := uint64([0]>>4) + (uint64([1]) << 4) + (uint64([2]) << 12)
			 = int( & 1023)
			 = int( >> 10)
			 =  == 1
			 = [3:]
		case 2:
			 = true
			if len() < 4 {
				println("too small: litType:", , " sizeFormat", , len())
				return , ErrBlockTooSmall
			}
			 := uint64([0]>>4) + (uint64([1]) << 4) + (uint64([2]) << 12) + (uint64([3]) << 20)
			 = int( & 16383)
			 = int( >> 14)
			 = [4:]
		case 3:
			 = true
			if len() < 5 {
				println("too small: litType:", , " sizeFormat", , len())
				return , ErrBlockTooSmall
			}
			 := uint64([0]>>4) + (uint64([1]) << 4) + (uint64([2]) << 12) + (uint64([3]) << 20) + (uint64([4]) << 28)
			 = int( & 262143)
			 = int( >> 18)
			 = [5:]
		}
	}
	if debugDecoder {
		println("literals type:", , "litRegenSize:", , "litCompSize:", , "sizeFormat:", , "4X:", )
	}
	if  > int(.WindowSize) ||  > maxCompressedBlockSize {
		return , ErrWindowSizeExceeded
	}

	switch  {
	case literalsBlockRaw:
		if len() <  {
			println("too small: litType:", , " sizeFormat", , "remain:", len(), "want:", )
			return , ErrBlockTooSmall
		}
		 = [:]
		 = [:]
		//printf("Found %d uncompressed literals\n", litRegenSize)
	case literalsBlockRLE:
		if len() < 1 {
			println("too small: litType:", , " sizeFormat", , "remain:", len(), "want:", 1)
			return , ErrBlockTooSmall
		}
		if cap(.literalBuf) <  {
			if .lowMem {
				.literalBuf = make([]byte, , +compressedBlockOverAlloc)
			} else {
				.literalBuf = make([]byte, , maxCompressedBlockSize+compressedBlockOverAlloc)
			}
		}
		 = .literalBuf[:]
		 := [0]
		for  := range  {
			[] = 
		}
		 = [1:]
		if debugDecoder {
			printf("Found %d RLE compressed literals\n", )
		}
	case literalsBlockTreeless:
		if len() <  {
			println("too small: litType:", , " sizeFormat", , "remain:", len(), "want:", )
			return , ErrBlockTooSmall
		}
		// Store compressed literals, so we defer decoding until we get history.
		 = [:]
		 = [:]
		if debugDecoder {
			printf("Found %d compressed literals\n", )
		}
		 := .huffTree
		if  == nil {
			return , errors.New("literal block was treeless, but no history was defined")
		}
		// Ensure we have space to store it.
		if cap(.literalBuf) <  {
			if .lowMem {
				.literalBuf = make([]byte, 0, +compressedBlockOverAlloc)
			} else {
				.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
			}
		}
		var  error
		// Use our out buffer.
		.MaxDecodedSize = 
		if  {
			,  = .Decoder().Decompress4X(.literalBuf[:0:], )
		} else {
			,  = .Decoder().Decompress1X(.literalBuf[:0:], )
		}
		// Make sure we don't leak our literals buffer
		if  != nil {
			println("decompressing literals:", )
			return , 
		}
		if len() !=  {
			return , fmt.Errorf("literal output size mismatch want %d, got %d", , len())
		}

	case literalsBlockCompressed:
		if len() <  {
			println("too small: litType:", , " sizeFormat", , "remain:", len(), "want:", )
			return , ErrBlockTooSmall
		}
		 = [:]
		 = [:]
		// Ensure we have space to store it.
		if cap(.literalBuf) <  {
			if .lowMem {
				.literalBuf = make([]byte, 0, +compressedBlockOverAlloc)
			} else {
				.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
			}
		}
		 := .huffTree
		if  == nil || (.dict != nil &&  == .dict.litEnc) {
			 = huffDecoderPool.Get().(*huff0.Scratch)
			if  == nil {
				 = &huff0.Scratch{}
			}
		}
		var  error
		if debugDecoder {
			println("huff table input:", len(), "CRC:", crc32.ChecksumIEEE())
		}
		, ,  = huff0.ReadTable(, )
		if  != nil {
			println("reading huffman table:", )
			return , 
		}
		.huffTree = 
		.MaxDecodedSize = 
		// Use our out buffer.
		if  {
			,  = .Decoder().Decompress4X(.literalBuf[:0:], )
		} else {
			,  = .Decoder().Decompress1X(.literalBuf[:0:], )
		}
		if  != nil {
			println("decoding compressed literals:", )
			return , 
		}
		// Make sure we don't leak our literals buffer
		if len() !=  {
			return , fmt.Errorf("literal output size mismatch want %d, got %d", , len())
		}
		// Re-cap to get extra size.
		 = .literalBuf[:len()]
		if debugDecoder {
			printf("Decompressed %d literals into %d bytes\n", , )
		}
	}
	.decoders.literals = 
	return , nil
}

// decodeCompressed will start decompressing a block.
func ( *blockDec) ( *history) error {
	 := .data
	,  := .decodeLiterals(, )
	if  != nil {
		return 
	}
	 = .prepareSequences(, )
	if  != nil {
		return 
	}
	if .decoders.nSeqs == 0 {
		.dst = append(.dst, .decoders.literals...)
		return nil
	}
	 := len(.decoders.out)
	 = .decoders.decodeSync(.b[.ignoreBuffer:])
	if  != nil {
		return 
	}
	if .decoders.maxSyncLen > 0 {
		.decoders.maxSyncLen += uint64()
		.decoders.maxSyncLen -= uint64(len(.decoders.out))
	}
	.dst = .decoders.out
	.recentOffsets = .decoders.prevOffset
	return nil
}

func ( *blockDec) ( []byte,  *history) ( error) {
	if debugDecoder {
		printf("prepareSequences: %d byte(s) input\n", len())
	}
	// Decode Sequences
	// https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section
	if len() < 1 {
		return ErrBlockTooSmall
	}
	var  int
	 := [0]
	switch {
	case  < 128:
		 = int()
		 = [1:]
	case  < 255:
		if len() < 2 {
			return ErrBlockTooSmall
		}
		 = int(-128)<<8 | int([1])
		 = [2:]
	case  == 255:
		if len() < 3 {
			return ErrBlockTooSmall
		}
		 = 0x7f00 + int([1]) + (int([2]) << 8)
		 = [3:]
	}
	if  == 0 && len() != 0 {
		// When no sequences, there should not be any more data...
		if debugDecoder {
			printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len())
		}
		return ErrUnexpectedBlockSize
	}

	var  = &.decoders
	.nSeqs = 
	if  > 0 {
		if len() < 1 {
			return ErrBlockTooSmall
		}
		 := byteReader{b: , off: 0}
		 := .Uint8()
		.advance(1)
		if debugDecoder {
			printf("Compression modes: 0b%b", )
		}
		if &3 != 0 {
			return errors.New("corrupt block: reserved bits not zero")
		}
		for  := uint(0);  < 3; ++ {
			 := seqCompMode(( >> (6 - *2)) & 3)
			if debugDecoder {
				println("Table", tableIndex(), "is", )
			}
			var  *sequenceDec
			switch tableIndex() {
			case tableLiteralLengths:
				 = &.litLengths
			case tableOffsets:
				 = &.offsets
			case tableMatchLengths:
				 = &.matchLengths
			default:
				panic("unknown table")
			}
			switch  {
			case compModePredefined:
				if .fse != nil && !.fse.preDefined {
					fseDecoderPool.Put(.fse)
				}
				.fse = &fsePredef[]
			case compModeRLE:
				if .remain() < 1 {
					return ErrBlockTooSmall
				}
				 := .Uint8()
				.advance(1)
				if .fse == nil || .fse.preDefined {
					.fse = fseDecoderPool.Get().(*fseDecoder)
				}
				,  := decSymbolValue(, symbolTableX[])
				if  != nil {
					printf("RLE Transform table (%v) error: %v", tableIndex(), )
					return 
				}
				.fse.setRLE()
				if debugDecoder {
					printf("RLE set to 0x%x, code: %v", , )
				}
			case compModeFSE:
				if debugDecoder {
					println("Reading table for", tableIndex())
				}
				if .fse == nil || .fse.preDefined {
					.fse = fseDecoderPool.Get().(*fseDecoder)
				}
				 := .fse.readNCount(&, uint16(maxTableSymbol[]))
				if  != nil {
					println("Read table error:", )
					return 
				}
				 = .fse.transform(symbolTableX[])
				if  != nil {
					println("Transform table error:", )
					return 
				}
				if debugDecoder {
					println("Read table ok", "symbolLen:", .fse.symbolLen)
				}
			case compModeRepeat:
				.repeat = true
			}
			if .overread() {
				return io.ErrUnexpectedEOF
			}
		}
		 = .unread()
	}
	if debugDecoder {
		println("Literals:", len(.literals), "hash:", xxhash.Sum64(.literals), "and", .nSeqs, "sequences.")
	}

	if  == 0 {
		if len(.sequence) > 0 {
			.sequence = .sequence[:0]
		}
		return nil
	}
	 := .br
	if  == nil {
		 = &bitReader{}
	}
	if  := .init();  != nil {
		return 
	}

	if  := .initialize(, , .dst);  != nil {
		println("initializing sequences:", )
		return 
	}

	return nil
}

func ( *blockDec) ( *history) error {
	if cap(.sequence) < .decoders.nSeqs {
		if .lowMem {
			.sequence = make([]seqVals, 0, .decoders.nSeqs)
		} else {
			.sequence = make([]seqVals, 0, 0x7F00+0xffff)
		}
	}
	.sequence = .sequence[:.decoders.nSeqs]
	if .decoders.nSeqs == 0 {
		.decoders.seqSize = len(.decoders.literals)
		return nil
	}
	.decoders.windowSize = .windowSize
	.decoders.prevOffset = .recentOffsets

	 := .decoders.decode(.sequence)
	.recentOffsets = .decoders.prevOffset
	return 
}

func ( *blockDec) ( *history) error {
	 := .b
	if len() > .windowSize {
		 = [len()-.windowSize:]
		// We do not need history anymore.
		if .dict != nil {
			.dict.content = nil
		}
	}
	.decoders.windowSize = .windowSize
	.decoders.out = .dst[:0]
	 := .decoders.execute(.sequence, )
	if  != nil {
		return 
	}
	return .updateHistory()
}

func ( *blockDec) ( *history) error {
	if len(.data) > maxCompressedBlockSize {
		return fmt.Errorf("compressed block size too large (%d)", len(.data))
	}
	// Set output and release references.
	.dst = .decoders.out
	.recentOffsets = .decoders.prevOffset

	if .Last {
		// if last block we don't care about history.
		println("Last block, no history returned")
		.b = .b[:0]
		return nil
	} else {
		.append(.dst)
		if debugDecoder {
			println("Finished block with ", len(.sequence), "sequences. Added", len(.dst), "to history, now length", len(.b))
		}
	}
	.decoders.out, .decoders.literals = nil, nil

	return nil
}