package brotli

import (
	
	
)

type hasherCommon struct {
	params           hasherParams
	is_prepared_     bool
	dict_num_lookups uint
	dict_num_matches uint
}

func ( *hasherCommon) () *hasherCommon {
	return 
}

type hasherHandle interface {
	Common() *hasherCommon
	Initialize(params *encoderParams)
	Prepare(one_shot bool, input_size uint, data []byte)
	StitchToPreviousBlock(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint)
	HashTypeLength() uint
	StoreLookahead() uint
	PrepareDistanceCache(distance_cache []int)
	FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult)
	StoreRange(data []byte, mask uint, ix_start uint, ix_end uint)
	Store(data []byte, mask uint, ix uint)
}

const kCutoffTransformsCount uint32 = 10

/*   0,  12,   27,    23,    42,    63,    56,    48,    59,    64 */
/* 0+0, 4+8, 8+19, 12+11, 16+26, 20+43, 24+32, 28+20, 32+27, 36+28 */
const kCutoffTransforms uint64 = 0x071B520ADA2D3200

type hasherSearchResult struct {
	len            uint
	distance       uint
	score          uint
	len_code_delta int
}

/* kHashMul32 multiplier has these properties:
   * The multiplier must be odd. Otherwise we may lose the highest bit.
   * No long streaks of ones or zeros.
   * There is no effort to ensure that it is a prime, the oddity is enough
     for this use.
   * The number has been tuned heuristically against compression benchmarks. */
const kHashMul32 uint32 = 0x1E35A7BD

const kHashMul64 uint64 = 0x1E35A7BD1E35A7BD

const kHashMul64Long uint64 = 0x1FE35A7BD3579BD3

func hash14( []byte) uint32 {
	var  uint32 = binary.LittleEndian.Uint32() * kHashMul32

	/* The higher bits contain more mixture from the multiplication,
	   so we take our results from there. */
	return  >> (32 - 14)
}

func prepareDistanceCache( []int,  int) {
	if  > 4 {
		var  int = [0]
		[4] =  - 1
		[5] =  + 1
		[6] =  - 2
		[7] =  + 2
		[8] =  - 3
		[9] =  + 3
		if  > 10 {
			var  int = [1]
			[10] =  - 1
			[11] =  + 1
			[12] =  - 2
			[13] =  + 2
			[14] =  - 3
			[15] =  + 3
		}
	}
}

const literalByteScore = 135

const distanceBitPenalty = 30

/* Score must be positive after applying maximal penalty. */
const scoreBase = (distanceBitPenalty * 8 * 8)

/* Usually, we always choose the longest backward reference. This function
   allows for the exception of that rule.

   If we choose a backward reference that is further away, it will
   usually be coded with more bits. We approximate this by assuming
   log2(distance). If the distance can be expressed in terms of the
   last four distances, we use some heuristic constants to estimate
   the bits cost. For the first up to four literals we use the bit
   cost of the literals from the literal cost model, after that we
   use the average bit cost of the cost model.

   This function is used to sometimes discard a longer backward reference
   when it is not much longer and the bit cost for encoding it is more
   than the saved literals.

   backward_reference_offset MUST be positive. */
func backwardReferenceScore( uint,  uint) uint {
	return scoreBase + literalByteScore*uint() - distanceBitPenalty*uint(log2FloorNonZero())
}

func backwardReferenceScoreUsingLastDistance( uint) uint {
	return literalByteScore*uint() + scoreBase + 15
}

func backwardReferencePenaltyUsingLastDistance( uint) uint {
	return uint(39) + ((0x1CA10 >> ( & 0xE)) & 0xE)
}

func testStaticDictionaryItem( *encoderDictionary,  uint,  []byte,  uint,  uint,  uint,  *hasherSearchResult) bool {
	var  uint
	var  uint
	var  uint
	var  uint
	var  uint
	var  uint
	 =  & 0x1F
	 =  >> 5
	 = uint(.words.offsets_by_length[]) + *
	if  >  {
		return false
	}

	 = findMatchLengthWithLimit(, .words.data[:], uint())
	if +uint(.cutoffTransformsCount) <=  ||  == 0 {
		return false
	}
	{
		var  uint =  - 
		var  uint = ( << 2) + uint((.cutoffTransforms>>(*6))&0x3F)
		 =  + 1 +  + ( << .words.size_bits_by_length[])
	}

	if  >  {
		return false
	}

	 = backwardReferenceScore(, )
	if  < .score {
		return false
	}

	.len = 
	.len_code_delta = int() - int()
	.distance = 
	.score = 
	return true
}

func searchInStaticDictionary( *encoderDictionary,  hasherHandle,  []byte,  uint,  uint,  uint,  *hasherSearchResult,  bool) {
	var  uint
	var  uint
	var  *hasherCommon = .Common()
	if .dict_num_matches < .dict_num_lookups>>7 {
		return
	}

	 = uint(hash14() << 1)
	for  = 0; ; (func() { ++; ++ })() {
		var  uint
		if  {
			 = 1
		} else {
			 = 2
		}
		if  >=  {
			break
		}
		var  uint = uint(.hash_table[])
		.dict_num_lookups++
		if  != 0 {
			var  bool = testStaticDictionaryItem(, , , , , , )
			if  {
				.dict_num_matches++
			}
		}
	}
}

type backwardMatch struct {
	distance        uint32
	length_and_code uint32
}

func initBackwardMatch( *backwardMatch,  uint,  uint) {
	.distance = uint32()
	.length_and_code = uint32( << 5)
}

func initDictionaryBackwardMatch( *backwardMatch,  uint,  uint,  uint) {
	.distance = uint32()
	var  uint
	if  ==  {
		 = 0
	} else {
		 = 
	}
	.length_and_code = uint32(<<5 | )
}

func backwardMatchLength( *backwardMatch) uint {
	return uint(.length_and_code >> 5)
}

func backwardMatchLengthCode( *backwardMatch) uint {
	var  uint = uint(.length_and_code) & 31
	if  != 0 {
		return 
	} else {
		return backwardMatchLength()
	}
}

func hasherReset( hasherHandle) {
	if  == nil {
		return
	}
	.Common().is_prepared_ = false
}

func newHasher( int) hasherHandle {
	switch  {
	case 2:
		return &hashLongestMatchQuickly{
			bucketBits:    16,
			bucketSweep:   1,
			hashLen:       5,
			useDictionary: true,
		}
	case 3:
		return &hashLongestMatchQuickly{
			bucketBits:    16,
			bucketSweep:   2,
			hashLen:       5,
			useDictionary: false,
		}
	case 4:
		return &hashLongestMatchQuickly{
			bucketBits:    17,
			bucketSweep:   4,
			hashLen:       5,
			useDictionary: true,
		}
	case 5:
		return new(h5)
	case 6:
		return new(h6)
	case 10:
		return new(h10)
	case 35:
		return &hashComposite{
			ha: (3),
			hb: &hashRolling{jump: 4},
		}
	case 40:
		return &hashForgetfulChain{
			bucketBits:              15,
			numBanks:                1,
			bankBits:                16,
			numLastDistancesToCheck: 4,
		}
	case 41:
		return &hashForgetfulChain{
			bucketBits:              15,
			numBanks:                1,
			bankBits:                16,
			numLastDistancesToCheck: 10,
		}
	case 42:
		return &hashForgetfulChain{
			bucketBits:              15,
			numBanks:                512,
			bankBits:                9,
			numLastDistancesToCheck: 16,
		}
	case 54:
		return &hashLongestMatchQuickly{
			bucketBits:    20,
			bucketSweep:   4,
			hashLen:       7,
			useDictionary: false,
		}
	case 55:
		return &hashComposite{
			ha: (54),
			hb: &hashRolling{jump: 4},
		}
	case 65:
		return &hashComposite{
			ha: (6),
			hb: &hashRolling{jump: 1},
		}
	}

	panic(fmt.Sprintf("unknown hasher type: %d", ))
}

func hasherSetup( *hasherHandle,  *encoderParams,  []byte,  uint,  uint,  bool) {
	var  hasherHandle = nil
	var  *hasherCommon = nil
	var  bool = ( == 0 && )
	if * == nil {
		chooseHasher(, &.hasher)
		 = newHasher(.hasher.type_)

		* = 
		 = .Common()
		.params = .hasher
		.Initialize()
	}

	 = *
	 = .Common()
	if !.is_prepared_ {
		.Prepare(, , )

		if  == 0 {
			.dict_num_lookups = 0
			.dict_num_matches = 0
		}

		.is_prepared_ = true
	}
}

func initOrStitchToPreviousBlock( *hasherHandle,  []byte,  uint,  *encoderParams,  uint,  uint,  bool) {
	var  hasherHandle
	hasherSetup(, , , , , )
	 = *
	.StitchToPreviousBlock(, , , )
}