// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package flate

import (
	
)

const (
	// The largest offset code.
	offsetCodeCount = 30

	// The special code used to mark the end of a block.
	endBlockMarker = 256

	// The first length code.
	lengthCodesStart = 257

	// The number of codegen codes.
	codegenCodeCount = 19
	badCode          = 255

	maxNumLit         = 286
	maxStoreBlockSize = 65535
	baseMatchLength   = 3 // The smallest match length per the RFC section 3.2.5
	baseMatchOffset   = 1 // The smallest match offset
)

// The number of extra bits needed by length code X - LENGTH_CODES_START.
var lengthExtraBits = []int8{
	/* 257 */ 0, 0, 0,
	/* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
	/* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
	/* 280 */ 4, 5, 5, 5, 5, 0,
}

// The length indicated by length code X - LENGTH_CODES_START.
var lengthBase = []int{
	0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
	12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
	64, 80, 96, 112, 128, 160, 192, 224, 255,
}

// offset code word extra bits.
var offsetExtraBits = []int8{
	0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
	4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
	9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
}

var offsetBase = []int{
	0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
	0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
	0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
	0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
	0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
	0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
}

// The odd order in which the codegen code sizes are written.
var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}

type huffmanBitWriter struct {
	dst []byte

	// Data waiting to be written is the low nbits of bits.
	bits            uint64
	nbits           uint
	codegenFreq     [codegenCodeCount]int32
	literalFreq     []int32
	offsetFreq      []int32
	codegen         []uint8
	literalEncoding *huffmanEncoder
	offsetEncoding  *huffmanEncoder
	codegenEncoding *huffmanEncoder
}

func () matchfinder.Encoder {
	return &huffmanBitWriter{
		literalFreq:     make([]int32, maxNumLit),
		offsetFreq:      make([]int32, offsetCodeCount),
		codegen:         make([]uint8, maxNumLit+offsetCodeCount+1),
		literalEncoding: newHuffmanEncoder(maxNumLit),
		codegenEncoding: newHuffmanEncoder(codegenCodeCount),
		offsetEncoding:  newHuffmanEncoder(offsetCodeCount),
	}
}

func ( *huffmanBitWriter) () {
	.bits, .nbits = 0, 0
}

func ( *huffmanBitWriter) () {
	 := .dst
	for .nbits != 0 {
		 = append(, byte(.bits))
		.bits >>= 8
		if .nbits > 8 { // Avoid underflow
			.nbits -= 8
		} else {
			.nbits = 0
		}
	}
	.bits = 0
	.dst = 
}

func ( *huffmanBitWriter) ( int32,  uint) {
	.bits |= uint64() << .nbits
	.nbits += 
	if .nbits >= 48 {
		 := .bits
		.bits >>= 48
		.nbits -= 48
		.dst = append(.dst,
			byte(),
			byte(>>8),
			byte(>>16),
			byte(>>24),
			byte(>>32),
			byte(>>40),
		)
	}
}

func ( *huffmanBitWriter) ( []byte) {
	if .nbits&7 != 0 {
		panic("writeBytes with unfinished bits")
	}
	for .nbits != 0 {
		.dst = append(.dst, byte(.bits))
		.bits >>= 8
		.nbits -= 8
	}
	.dst = append(.dst, ...)
}

// RFC 1951 3.2.7 specifies a special run-length encoding for specifying
// the literal and offset lengths arrays (which are concatenated into a single
// array).  This method generates that run-length encoding.
//
// The result is written into the codegen array, and the frequencies
// of each code is written into the codegenFreq array.
// Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
// information. Code badCode is an end marker
//
//	numLiterals      The number of literals in literalEncoding
//	numOffsets       The number of offsets in offsetEncoding
//	litenc, offenc   The literal and offset encoder to use
func ( *huffmanBitWriter) ( int,  int, ,  *huffmanEncoder) {
	for  := range .codegenFreq {
		.codegenFreq[] = 0
	}
	// Note that we are using codegen both as a temporary variable for holding
	// a copy of the frequencies, and as the place where we put the result.
	// This is fine because the output is always shorter than the input used
	// so far.
	 := .codegen // cache
	// Copy the concatenated code sizes to codegen. Put a marker at the end.
	 := [:]
	for  := range  {
		[] = uint8(.codes[].len)
	}

	 = [ : +]
	for  := range  {
		[] = uint8(.codes[].len)
	}
	[+] = badCode

	 := [0]
	 := 1
	 := 0
	for  := 1;  != badCode; ++ {
		// INVARIANT: We have seen "count" copies of size that have not yet
		// had output generated for them.
		 := []
		if  ==  {
			++
			continue
		}
		// We need to generate codegen indicating "count" of size.
		if  != 0 {
			[] = 
			++
			.codegenFreq[]++
			--
			for  >= 3 {
				 := 6
				if  >  {
					 = 
				}
				[] = 16
				++
				[] = uint8( - 3)
				++
				.codegenFreq[16]++
				 -= 
			}
		} else {
			for  >= 11 {
				 := 138
				if  >  {
					 = 
				}
				[] = 18
				++
				[] = uint8( - 11)
				++
				.codegenFreq[18]++
				 -= 
			}
			if  >= 3 {
				// count >= 3 && count <= 10
				[] = 17
				++
				[] = uint8( - 3)
				++
				.codegenFreq[17]++
				 = 0
			}
		}
		--
		for ;  >= 0; -- {
			[] = 
			++
			.codegenFreq[]++
		}
		// Set up invariant for next time through the loop.
		 = 
		 = 1
	}
	// Marker indicating the end of the codegen.
	[] = badCode
}

// dynamicSize returns the size of dynamically encoded data in bits.
func ( *huffmanBitWriter) (,  *huffmanEncoder,  int) (,  int) {
	 = len(.codegenFreq)
	for  > 4 && .codegenFreq[codegenOrder[-1]] == 0 {
		--
	}
	 := 3 + 5 + 5 + 4 + (3 * ) +
		.codegenEncoding.bitLength(.codegenFreq[:]) +
		int(.codegenFreq[16])*2 +
		int(.codegenFreq[17])*3 +
		int(.codegenFreq[18])*7
	 =  +
		.bitLength(.literalFreq) +
		.bitLength(.offsetFreq) +
		

	return , 
}

// fixedSize returns the size of dynamically encoded data in bits.
func ( *huffmanBitWriter) ( int) int {
	return 3 +
		fixedLiteralEncoding.bitLength(.literalFreq) +
		fixedOffsetEncoding.bitLength(.offsetFreq) +
		
}

// storedSize calculates the stored size, including header.
// The function returns the size in bits and whether the block
// fits inside a single block.
func ( *huffmanBitWriter) ( []byte) (int, bool) {
	if  == nil {
		return 0, false
	}
	if len() <= maxStoreBlockSize {
		return (len() + 5) * 8, true
	}
	return 0, false
}

func ( *huffmanBitWriter) ( hcode) {
	.bits |= uint64(.code) << .nbits
	.nbits += uint(.len)
	if .nbits >= 48 {
		 := .bits
		.bits >>= 48
		.nbits -= 48
		.dst = append(.dst,
			byte(),
			byte(>>8),
			byte(>>16),
			byte(>>24),
			byte(>>32),
			byte(>>40),
		)
	}
}

// Write the header of a dynamic Huffman block to the output stream.
//
//	numLiterals  The number of literals specified in codegen
//	numOffsets   The number of offsets specified in codegen
//	numCodegens  The number of codegens used in codegen
func ( *huffmanBitWriter) ( int,  int,  int,  bool) {
	var  int32 = 4
	if  {
		 = 5
	}
	.writeBits(, 3)
	.writeBits(int32(-257), 5)
	.writeBits(int32(-1), 5)
	.writeBits(int32(-4), 4)

	for  := 0;  < ; ++ {
		 := uint(.codegenEncoding.codes[codegenOrder[]].len)
		.writeBits(int32(), 3)
	}

	 := 0
	for {
		var  int = int(.codegen[])
		++
		if  == badCode {
			break
		}
		.writeCode(.codegenEncoding.codes[uint32()])

		switch  {
		case 16:
			.writeBits(int32(.codegen[]), 2)
			++
		case 17:
			.writeBits(int32(.codegen[]), 3)
			++
		case 18:
			.writeBits(int32(.codegen[]), 7)
			++
		}
	}
}

func ( *huffmanBitWriter) ( int,  bool) {
	var  int32
	if  {
		 = 1
	}
	.writeBits(, 3)
	.flush()
	.writeBits(int32(), 16)
	.writeBits(int32(^uint16()), 16)
}

func ( *huffmanBitWriter) ( bool) {
	// Indicate that we are a fixed Huffman block
	var  int32 = 2
	if  {
		 = 3
	}
	.writeBits(, 3)
}

// writeBlock will write a block of tokens with the smallest encoding.
func ( *huffmanBitWriter) ( []matchfinder.Match,  bool,  []byte) {
	,  := .makeStatistics(, )

	var  int
	,  := .storedSize()
	if  {
		// We only bother calculating the costs of the extra bits required by
		// the length of offset fields (which will be the same for both fixed
		// and dynamic encoding), if we need to compare those two encodings
		// against stored encoding.
		for  := lengthCodesStart + 8;  < ; ++ {
			// First eight length codes have extra size = 0.
			 += int(.literalFreq[]) * int(lengthExtraBits[-lengthCodesStart])
		}
		for  := 4;  < ; ++ {
			// First four offset codes have extra size = 0.
			 += int(.offsetFreq[]) * int(offsetExtraBits[])
		}
	}

	// Figure out smallest code.
	// Fixed Huffman baseline.
	var  = fixedLiteralEncoding
	var  = fixedOffsetEncoding
	var  = .fixedSize()

	// Dynamic Huffman?
	var  int

	// Generate codegen and codegenFrequencies, which indicates how to encode
	// the literalEncoding and the offsetEncoding.
	.generateCodegen(, , .literalEncoding, .offsetEncoding)
	.codegenEncoding.generate(.codegenFreq[:], 7)
	,  := .dynamicSize(.literalEncoding, .offsetEncoding, )

	if  <  {
		 = 
		 = .literalEncoding
		 = .offsetEncoding
	}

	// Stored bytes?
	if  &&  <  {
		.writeStoredHeader(len(), )
		.writeBytes()
		return
	}

	// Huffman.
	if  == fixedLiteralEncoding {
		.writeFixedHeader()
	} else {
		.writeDynamicHeader(, , , )
	}

	// Write the tokens.
	.writeTokens(, , .codes, .codes)
	.writeCode(.codes[endBlockMarker])
}

// makeStatistics indexes a slice of tokens, and updates
// literalFreq and offsetFreq, and generates literalEncoding
// and offsetEncoding.
// The number of literal and offset tokens is returned.
func ( *huffmanBitWriter) ( []matchfinder.Match,  []byte) (,  int) {
	for  := range .literalFreq {
		.literalFreq[] = 0
	}
	for  := range .offsetFreq {
		.offsetFreq[] = 0
	}

	 := 0
	for ,  := range  {
		for ,  := range [ : +.Unmatched] {
			.literalFreq[]++
		}
		 += .Unmatched

		if .Length == 0 {
			continue
		}
		.literalFreq[lengthCodesStart+lengthCode(.Length)]++
		.offsetFreq[offsetCode(.Distance)]++
		 += .Length
	}
	.literalFreq[endBlockMarker]++

	// get the number of literals
	 = len(.literalFreq)
	for .literalFreq[-1] == 0 {
		--
	}
	// get the number of offsets
	 = len(.offsetFreq)
	for  > 0 && .offsetFreq[-1] == 0 {
		--
	}
	if  == 0 {
		// We haven't found a single match. If we want to go with the dynamic encoding,
		// we should count at least one offset to be sure that the offset huffman tree could be encoded.
		.offsetFreq[0] = 1
		 = 1
	}
	.literalEncoding.generate(.literalFreq, 15)
	.offsetEncoding.generate(.offsetFreq, 15)
	return
}

// writeTokens writes a slice of tokens to the output.
// codes for literal and offset encoding must be supplied.
func ( *huffmanBitWriter) ( []matchfinder.Match,  []byte, ,  []hcode) {
	 := 0
	for ,  := range  {
		for ,  := range [ : +.Unmatched] {
			.writeCode([])
		}
		 += .Unmatched

		// Write the length
		 := .Length
		if  == 0 {
			continue
		}
		 := lengthCode()
		.writeCode([+lengthCodesStart])
		 := uint(lengthExtraBits[])
		if  > 0 {
			 := int32( - baseMatchLength - lengthBase[])
			.writeBits(, )
		}

		// Write the offset
		 := .Distance
		 := offsetCode()
		.writeCode([])
		 := uint(offsetExtraBits[])
		if  > 0 {
			 := int32( - baseMatchOffset - offsetBase[])
			.writeBits(, )
		}
		 += .Length
	}
}

func ( *huffmanBitWriter) ( []byte,  []byte,  []matchfinder.Match,  bool) []byte {
	.dst = 

	.writeBlock(, , )
	if  {
		.flush()
	}

	 = .dst
	.dst = nil
	return 
}