package lz4block

import (
	
	
	
)

// CompressorCCompat is a port of LZ4_compress_fast from the reference
// implementation (lz4 1.10), and produces the same output. It searches one
// position per step with a 16kiB table, where Compressor searches three per
// step with a 128kiB one and skips ahead faster when matches stop.
//
// Constants and names follow lz4.c.
const (
	ccompatHashLog   = 12          // LZ4_HASHLOG, for the default LZ4_MEMORY_USAGE of 14
	ccompatMFLimit   = 12          // MFLIMIT
	ccompatMinLength = 13          // LZ4_minLength
	lastLiterals     = 5           // LASTLITERALS
	skipTrigger      = 6           // LZ4_skipTrigger
	ccompatU16Limit  = 64<<10 + 11 // LZ4_64Klimit: smaller inputs use the byU16 table
	ccompatMaxInput  = 0x7E000000  // LZ4_MAX_INPUT_SIZE
	distanceMax      = 65535       // LZ4_DISTANCE_MAX
	accelerationMax  = 65537       // LZ4_ACCELERATION_MAX

	ccompatTableSize = 1 << (ccompatHashLog + 1)
)

type CompressorCCompat struct {
	// Inputs below ccompatU16Limit use all of table16 (byU16 in lz4.c), larger
	// ones the first half of table32 (byU32). The one in use is cleared on
	// each call.
	table16 [ccompatTableSize]uint16
	table32 [ccompatTableSize]uint32
}

var compressorCCompatPool = sync.Pool{New: func() any { return new(CompressorCCompat) }}

// CompressBlockCCompat is CompressorCCompat.CompressBlock with acceleration 1,
// using a pooled CompressorCCompat.
func (,  []byte) (int, error) {
	 := compressorCCompatPool.Get().(*CompressorCCompat)
	,  := .CompressBlock(, , 1)
	compressorCCompatPool.Put()
	return , 
}

// ccompatHasher is LZ4_hashPosition as (v<<shift)*prime>>bits, v being the
// 8 bytes at the position: with shift 32, only the low 4 bytes count, which
// is hash4 for byU16; with shift 24, hash5 for byU32.
type ccompatHasher struct {
	shift, bits uint
	prime       uint64
}

var (
	hash4 = ccompatHasher{shift: 32, prime: 2654435761, bits: 64 - (ccompatHashLog + 1)}
	hash5 = ccompatHasher{shift: 24, prime: 889523592379, bits: 64 - ccompatHashLog}
)

// hash returns a table index. Masking the shift counts spares the checks Go
// otherwise makes for shifts of 64 or more.
func ( ccompatHasher) ( uint64) uint32 {
	return uint32( << (.shift & 63) * .prime >> (.bits & 63))
}

// countMatch is LZ4_count: the length of the common prefix of src[in:limit]
// and src[match:], with match < in.
func countMatch( srcReader,  []byte, , ,  int) int {
	 := 
	for +8 <=  {
		if  := .load64(, ) ^ .load64(, );  != 0 {
			return  + bits.TrailingZeros64()>>3 - 
		}
		 += 8
		 += 8
	}
	if +4 <=  && .load32(, ) == .load32(, ) {
		 += 4
		 += 4
	}
	if +2 <=  && .load16(, ) == .load16(, ) {
		 += 2
		 += 2
	}
	if  <  && [] == [] {
		++
	}
	return  - 
}

// CompressBlock compresses src into dst with the given acceleration, as
// LZ4_compress_fast_extState does. It returns 0 if the result does not fit
// in dst, which cannot happen if len(dst) >= CompressBlockBound(len(src)).
func ( *CompressorCCompat) (,  []byte,  int) (int, error) {
	if  < 1 {
		 = 1
	} else if  > accelerationMax {
		 = accelerationMax
	}
	if len() == 0 {
		if len() == 0 {
			return 0, nil
		}
		[0] = 0
		return 1, nil
	}
	if len() > ccompatMaxInput {
		// Beyond what lz4.c accepts, and what 32-bit positions can hold.
		return CompressBlock(, )
	}
	if len() < ccompatU16Limit {
		.table16 = [ccompatTableSize]uint16{}
		return compressCCompat(&.table16, hash4, , , ), nil
	}
	 := .table32[:1<<ccompatHashLog]
	for  := range  {
		[] = 0
	}
	return compressCCompat(&.table32, hash5, , , ), nil
}

func compressCCompat[ uint16 | uint32]( *[ccompatTableSize],  ccompatHasher, ,  []byte,  int) int {
	// limitedOutput in lz4.c: check that the output fits as it is written.
	 := len() < CompressBlockBound(len())
	// Loads are within the input: the positions searched stop ccompatMFLimit
	// bytes before its end, and matches before lastLiterals bytes.
	 := newSrcReader()

	var (
		, ,  int
		 = len() - ccompatMFLimit + 1
		     = len() - lastLiterals
		       uint32
		       uint64 // the 8 bytes at the next position to search
		,    int
	)
	if len() < ccompatMinLength {
		goto 
	}

	// First byte.
	[.hash(.load64(, 0))&(ccompatTableSize-1)] = 0
	 = 1
	 = .load64(, )
	 = .hash()

	for {
		// Find a match.
		{
			 := 
			 := 1
			 :=  << skipTrigger
			for {
				 := 
				 := 
				 := uint32()
				 := int([&(ccompatTableSize-1)])
				 = 
				 += 
				 =  >> skipTrigger
				++
				if  >  {
					goto 
				}
				 = 
				 = .load64(, )
				 = .hash()
				[&(ccompatTableSize-1)] = ()
				// Never true for byU16 inputs, which are too short.
				if +distanceMax <  {
					continue // too far
				}
				if .load32(, ) ==  {
					break
				}
			}
		}

		// Catch up.
		if  > 0 && [-1] == [-1] {
			for {
				--
				--
				if  <=  ||  <= 0 || [-1] != [-1] {
					break
				}
			}
		}

		// Encode literals.
		{
			 :=  - 
			 = 
			++
			if  && ++(2+1+lastLiterals)+/255 > len() {
				return 0
			}
			if  >= 0xF {
				[] = 0xF0
				 :=  - 0xF
				for ;  >= 0xFF;  -= 0xFF {
					[] = 0xFF
					++
				}
				[] = byte()
				++
			} else {
				[] = byte( << 4)
			}
			// LZ4_wildCopy8: may write up to 7 bytes past the literals,
			// which the rest of the output always overwrites.
			for  := 0;  < ;  += 8 {
				binary.LittleEndian.PutUint64([+:], .load64(, +))
			}
			 += 
		}

	:
		// Encode offset.
		 :=  - 
		[] = byte()
		[+1] = byte( >> 8)
		 += 2

		// Encode match length.
		{
			 := countMatch(, , +minMatch, +minMatch, )
			 +=  + minMatch
			if  && +(1+lastLiterals)+(+240)/255 > len() {
				return 0
			}
			if  >= 0xF {
				[] += 0xF
				 -= 0xF
				for ;  >= 0xFF;  -= 0xFF {
					[] = 0xFF
					++
				}
				[] = byte()
				++
			} else {
				[] += byte()
			}
		}
		 = 

		// Test end of chunk.
		if  >=  {
			break
		}

		// Fill table.
		[.hash(.load64(, -2))&(ccompatTableSize-1)] = ( - 2)

		// Test next position.
		{
			 := .load64(, )
			 := .hash() & (ccompatTableSize - 1)
			 := int([])
			[] = ()
			if +distanceMax >=  && .load32(, ) == uint32() {
				 = 
				[] = 0
				++
				 = 
				goto 
			}
		}

		// Prepare next loop.
		++
		 = .load64(, )
		 = .hash()
	}

:
	 := len() - 
	if  && ++1+(+255-0xF)/255 > len() {
		return 0
	}
	if  >= 0xF {
		[] = 0xF0
		++
		 :=  - 0xF
		for ;  >= 0xFF;  -= 0xFF {
			[] = 0xFF
			++
		}
		[] = byte()
		++
	} else {
		[] = byte( << 4)
		++
	}
	 += copy([:], [:])
	return 
}