package brotli

import (
	
	
)

/* Copyright 2016 Google Inc. All Rights Reserved.

   Distributed under MIT license.
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/

/** Minimal value for ::BROTLI_PARAM_LGWIN parameter. */
const minWindowBits = 10

/**
 * Maximal value for ::BROTLI_PARAM_LGWIN parameter.
 *
 * @note equal to @c BROTLI_MAX_DISTANCE_BITS constant.
 */
const maxWindowBits = 24

/**
 * Maximal value for ::BROTLI_PARAM_LGWIN parameter
 * in "Large Window Brotli" (32-bit).
 */
const largeMaxWindowBits = 30

/** Minimal value for ::BROTLI_PARAM_LGBLOCK parameter. */
const minInputBlockBits = 16

/** Maximal value for ::BROTLI_PARAM_LGBLOCK parameter. */
const maxInputBlockBits = 24

/** Minimal value for ::BROTLI_PARAM_QUALITY parameter. */
const minQuality = 0

/** Maximal value for ::BROTLI_PARAM_QUALITY parameter. */
const maxQuality = 11

/** Options for ::BROTLI_PARAM_MODE parameter. */
const (
	modeGeneric = 0
	modeText    = 1
	modeFont    = 2
)

/** Default value for ::BROTLI_PARAM_QUALITY parameter. */
const defaultQuality = 11

/** Default value for ::BROTLI_PARAM_LGWIN parameter. */
const defaultWindow = 22

/** Default value for ::BROTLI_PARAM_MODE parameter. */
const defaultMode = modeGeneric

/** Operations that can be performed by streaming encoder. */
const (
	operationProcess      = 0
	operationFlush        = 1
	operationFinish       = 2
	operationEmitMetadata = 3
)

const (
	streamProcessing     = 0
	streamFlushRequested = 1
	streamFinished       = 2
	streamMetadataHead   = 3
	streamMetadataBody   = 4
)

type Writer struct {
	dst     io.Writer
	options WriterOptions
	err     error

	params              encoderParams
	hasher_             hasherHandle
	input_pos_          uint64
	ringbuffer_         ringBuffer
	commands            []command
	num_literals_       uint
	last_insert_len_    uint
	last_flush_pos_     uint64
	last_processed_pos_ uint64
	dist_cache_         [numDistanceShortCodes]int
	saved_dist_cache_   [4]int
	last_bytes_         uint16
	last_bytes_bits_    byte
	prev_byte_          byte
	prev_byte2_         byte
	storage             []byte
	small_table_        [1 << 10]int
	large_table_        []int
	large_table_size_   uint
	cmd_depths_         [128]byte
	cmd_bits_           [128]uint16
	cmd_code_           [512]byte
	cmd_code_numbits_   uint
	command_buf_        []uint32
	literal_buf_        []byte
	tiny_buf_           struct {
		u64 [2]uint64
		u8  [16]byte
	}
	remaining_metadata_bytes_ uint32
	stream_state_             int
	is_last_block_emitted_    bool
	is_initialized_           bool
}

func inputBlockSize( *Writer) uint {
	return uint(1) << uint(.params.lgblock)
}

func unprocessedInputSize( *Writer) uint64 {
	return .input_pos_ - .last_processed_pos_
}

func remainingInputBlockSize( *Writer) uint {
	var  uint64 = unprocessedInputSize()
	var  uint = inputBlockSize()
	if  >= uint64() {
		return 0
	}
	return  - uint()
}

/* Wraps 64-bit input position to 32-bit ring-buffer position preserving
   "not-a-first-lap" feature. */
func wrapPosition( uint64) uint32 {
	var  uint32 = uint32()
	var  uint64 =  >> 30
	if  > 2 {
		/* Wrap every 2GiB; The first 3GB are continuous. */
		 = &((1<<30)-1) | (uint32((-1)&1)+1)<<30
	}

	return 
}

func ( *Writer) ( int) []byte {
	if len(.storage) <  {
		.storage = make([]byte, )
	}

	return .storage
}

func hashTableSize( uint,  uint) uint {
	var  uint = 256
	for  <  &&  <  {
		 <<= 1
	}

	return 
}

func getHashTable( *Writer,  int,  uint,  *uint) []int {
	var  uint = maxHashTableSize()
	var  uint = hashTableSize(, )
	/* Use smaller hash table when input.size() is smaller, since we
	   fill the table, incurring O(hash table size) overhead for
	   compression, and if the input is short, we won't need that
	   many hash table entries anyway. */

	var  []int
	assert( >= 256)
	if  == fastOnePassCompressionQuality {
		/* Only odd shifts are supported by fast-one-pass. */
		if &0xAAAAA == 0 {
			 <<= 1
		}
	}

	if  <= uint(len(.small_table_)) {
		 = .small_table_[:]
	} else {
		if  > .large_table_size_ {
			.large_table_size_ = 
			.large_table_ = nil
			.large_table_ = make([]int, )
		}

		 = .large_table_
	}

	* = 
	for  := 0;  < int(); ++ {
		[] = 0
	}
	return 
}

func encodeWindowBits( int,  bool,  *uint16,  *byte) {
	if  {
		* = uint16((&0x3F)<<8 | 0x11)
		* = 14
	} else {
		if  == 16 {
			* = 0
			* = 1
		} else if  == 17 {
			* = 1
			* = 7
		} else if  > 17 {
			* = uint16((-17)<<1 | 0x01)
			* = 4
		} else {
			* = uint16((-8)<<4 | 0x01)
			* = 7
		}
	}
}

/* Decide about the context map based on the ability of the prediction
   ability of the previous byte UTF8-prefix on the next byte. The
   prediction ability is calculated as Shannon entropy. Here we need
   Shannon entropy instead of 'BitsEntropy' since the prefix will be
   encoded with the remaining 6 bits of the following byte, and
   BitsEntropy will assume that symbol to be stored alone using Huffman
   coding. */

var kStaticContextMapContinuation = [64]uint32{
	1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}
var kStaticContextMapSimpleUTF8 = [64]uint32{
	0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}

func chooseContextMap( int,  []uint32,  *uint,  *[]uint32) {
	var  = [3]uint32{0}
	var  = [6]uint32{0}
	var  uint
	var  uint
	var  uint
	var  [4]float64
	for  = 0;  < 9; ++ {
		[%3] += []
		[%6] += []
	}

	[1] = shannonEntropy([:], 3, &)
	[2] = (shannonEntropy([:], 3, &) + shannonEntropy([3:], 3, &))
	[3] = 0
	for  = 0;  < 3; ++ {
		[3] += shannonEntropy([3*:], 3, &)
	}

	 = uint([0] + [1] + [2])
	assert( != 0)
	[0] = 1.0 / float64()
	[1] *= [0]
	[2] *= [0]
	[3] *= [0]

	if  < minQualityForHqContextModeling {
		/* 3 context models is a bit slower, don't use it at lower qualities. */
		[3] = [1] * 10
	}

	/* If expected savings by symbol are less than 0.2 bits, skip the
	   context modeling -- in exchange for faster decoding speed. */
	if [1]-[2] < 0.2 && [1]-[3] < 0.2 {
		* = 1
	} else if [2]-[3] < 0.02 {
		* = 2
		* = kStaticContextMapSimpleUTF8[:]
	} else {
		* = 3
		* = kStaticContextMapContinuation[:]
	}
}

/* Decide if we want to use a more complex static context map containing 13
   context values, based on the entropy reduction of histograms over the
   first 5 bits of literals. */

var kStaticContextMapComplexUTF8 = [64]uint32{
	11, 11, 12, 12, /* 0 special */
	0, 0, 0, 0, /* 4 lf */
	1, 1, 9, 9, /* 8 space */
	2, 2, 2, 2, /* !, first after space/lf and after something else. */
	1, 1, 1, 1, /* " */
	8, 3, 3, 3, /* % */
	1, 1, 1, 1, /* ({[ */
	2, 2, 2, 2, /* }]) */
	8, 4, 4, 4, /* :; */
	8, 7, 4, 4, /* . */
	8, 0, 0, 0, /* > */
	3, 3, 3, 3, /* [0..9] */
	5, 5, 10, 5, /* [A-Z] */
	5, 5, 10, 5,
	6, 6, 6, 6, /* [a-z] */
	6, 6, 6, 6,
}

func shouldUseComplexStaticContextMap( []byte,  uint,  uint,  uint,  int,  uint,  *uint,  *[]uint32) bool {
	/* Try the more complex static context map only for long data. */
	if  < 1<<20 {
		return false
	} else {
		var  uint =  + 
		var  = [32]uint32{0}
		var  = [13][32]uint32{[32]uint32{0}}
		var  uint32 = 0
		var  [3]float64
		var  uint
		var  uint
		var  contextLUT = getContextLUT(contextUTF8)
		/* To make entropy calculations faster and to fit on the stack, we collect
		   histograms over the 5 most significant bits of literals. One histogram
		   without context and 13 additional histograms for each context value. */
		for ; +64 <= ;  += 4096 {
			var  uint =  + 64
			var  byte = [&]
			var  byte = [(+1)&]
			var  uint

			/* To make the analysis of the data faster we only examine 64 byte long
			   strides at every 4kB intervals. */
			for  =  + 2;  < ; ++ {
				var  byte = [&]
				var  byte = byte(kStaticContextMapComplexUTF8[getContext(, , )])
				++
				[>>3]++
				[][>>3]++
				 = 
				 = 
			}
		}

		[1] = shannonEntropy([:], 32, &)
		[2] = 0
		for  = 0;  < 13; ++ {
			[2] += shannonEntropy([][0:], 32, &)
		}

		[0] = 1.0 / float64()
		[1] *= [0]
		[2] *= [0]

		/* The triggering heuristics below were tuned by compressing the individual
		   files of the silesia corpus. If we skip this kind of context modeling
		   for not very well compressible input (i.e. entropy using context modeling
		   is 60% of maximal entropy) or if expected savings by symbol are less
		   than 0.2 bits, then in every case when it triggers, the final compression
		   ratio is improved. Note however that this heuristics might be too strict
		   for some cases and could be tuned further. */
		if [2] > 3.0 || [1]-[2] < 0.2 {
			return false
		} else {
			* = 13
			* = kStaticContextMapComplexUTF8[:]
			return true
		}
	}
}

func decideOverLiteralContextModeling( []byte,  uint,  uint,  uint,  int,  uint,  *uint,  *[]uint32) {
	if  < minQualityForContextModeling ||  < 64 {
		return
	} else if shouldUseComplexStaticContextMap(, , , , , , , ) {
	} else /* Context map was already set, nothing else to do. */
	{
		var  uint =  + 
		/* Gather bi-gram data of the UTF8 byte prefixes. To make the analysis of
		   UTF8 data faster we only examine 64 byte long strides at every 4kB
		   intervals. */

		var  = [9]uint32{0}
		for ; +64 <= ;  += 4096 {
			var  = [4]int{0, 0, 1, 2}
			var  uint =  + 64
			var  int = [[&]>>6] * 3
			var  uint
			for  =  + 1;  < ; ++ {
				var  byte = [&]
				[+[>>6]]++
				 = [>>6] * 3
			}
		}

		chooseContextMap(, [0:], , )
	}
}

func shouldCompress_encode( []byte,  uint,  uint64,  uint,  uint,  uint) bool {
	/* TODO: find more precise minimal block overhead. */
	if  <= 2 {
		return false
	}
	if  < (>>8)+2 {
		if float64() > 0.99*float64() {
			var  = [256]uint32{0}
			const  uint32 = 13
			const  float64 = 7.92
			var  float64 = float64() *  / float64()
			var  uint = uint((uint32() +  - 1) / )
			var  uint32 = uint32()
			var  uint
			for  = 0;  < ; ++ {
				[[&uint32()]]++
				 += 
			}

			if bitsEntropy([:], 256) >  {
				return false
			}
		}
	}

	return true
}

/* Chooses the literal context mode for a metablock */
func chooseContextMode( *encoderParams,  []byte,  uint,  uint,  uint) int {
	/* We only do the computation for the option of something else than
	   CONTEXT_UTF8 for the highest qualities */
	if .quality >= minQualityForHqBlockSplitting && !isMostlyUTF8(, , , , kMinUTF8Ratio) {
		return contextSigned
	}

	return contextUTF8
}

func writeMetaBlockInternal( []byte,  uint,  uint64,  uint,  bool,  int,  *encoderParams,  byte,  byte,  uint,  []command,  []int,  []int,  *uint,  []byte) {
	var  uint32 = wrapPosition()
	var  uint16
	var  byte
	var  contextLUT = getContextLUT()
	var  encoderParams = *

	if  == 0 {
		/* Write the ISLAST and ISEMPTY bits. */
		writeBits(2, 3, , )

		* = (* + 7) &^ 7
		return
	}

	if !shouldCompress_encode(, , , , , uint(len())) {
		/* Restore the distance cache, as its last update by
		   CreateBackwardReferences is now unused. */
		copy(, [:4])

		storeUncompressedMetaBlock(, , uint(), , , , )
		return
	}

	assert(* <= 14)
	 = uint16([1])<<8 | uint16([0])
	 = byte(*)
	if .quality <= maxQualityForStaticEntropyCodes {
		storeMetaBlockFast(, uint(), , , , , , , )
	} else if .quality < minQualityForBlockSplit {
		storeMetaBlockTrivial(, uint(), , , , , , , )
	} else {
		 := getMetaBlockSplit()
		if .quality < minQualityForHqBlockSplitting {
			var  uint = 1
			var  []uint32 = nil
			if !.disable_literal_context_modeling {
				decideOverLiteralContextModeling(, uint(), , , .quality, .size_hint, &, &)
			}

			buildMetaBlockGreedy(, uint(), , , , , , , , )
		} else {
			buildMetaBlock(, uint(), , &, , , , , )
		}

		if .quality >= minQualityForOptimizeHistograms {
			/* The number of distance symbols effectively used for distance
			   histograms. It might be less than distance alphabet size
			   for "Large Window Brotli" (32-bit). */
			var  uint32 = .dist.alphabet_size
			if  > numHistogramDistanceSymbols {
				 = numHistogramDistanceSymbols
			}

			optimizeHistograms(, )
		}

		storeMetaBlock(, uint(), , , , , , &, , , , , )
		freeMetaBlockSplit()
	}

	if +4 < *>>3 {
		/* Restore the distance cache and last byte. */
		copy(, [:4])

		[0] = byte()
		[1] = byte( >> 8)
		* = uint()
		storeUncompressedMetaBlock(, , uint(), , , , )
	}
}

func chooseDistanceParams( *encoderParams) {
	var  uint32 = 0
	var  uint32 = 0

	if .quality >= minQualityForNonzeroDistanceParams {
		var  uint32
		if .mode == modeFont {
			 = 1
			 = 12
		} else {
			 = .dist.distance_postfix_bits
			 = .dist.num_direct_distance_codes
		}

		 = ( >> ) & 0x0F
		if  > maxNpostfix ||  > maxNdirect || << !=  {
			 = 0
			 = 0
		}
	}

	initDistanceParams(, , )
}

func ensureInitialized( *Writer) bool {
	if .is_initialized_ {
		return true
	}

	.last_bytes_bits_ = 0
	.last_bytes_ = 0
	.remaining_metadata_bytes_ = math.MaxUint32

	sanitizeParams(&.params)
	.params.lgblock = computeLgBlock(&.params)
	chooseDistanceParams(&.params)

	ringBufferSetup(&.params, &.ringbuffer_)

	/* Initialize last byte with stream header. */
	{
		var  int = int(.params.lgwin)
		if .params.quality == fastOnePassCompressionQuality || .params.quality == fastTwoPassCompressionQuality {
			 = brotli_max_int(, 18)
		}

		encodeWindowBits(, .params.large_window, &.last_bytes_, &.last_bytes_bits_)
	}

	if .params.quality == fastOnePassCompressionQuality {
		.cmd_depths_ = [128]byte{
			0, 4, 4, 5, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
			0, 0, 0, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7,
			7, 7, 10, 10, 10, 10, 10, 10, 0, 4, 4, 5, 5, 5, 6, 6,
			7, 8, 8, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
			5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4,
			4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 10,
			12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		}
		.cmd_bits_ = [128]uint16{
			0, 0, 8, 9, 3, 35, 7, 71,
			39, 103, 23, 47, 175, 111, 239, 31,
			0, 0, 0, 4, 12, 2, 10, 6,
			13, 29, 11, 43, 27, 59, 87, 55,
			15, 79, 319, 831, 191, 703, 447, 959,
			0, 14, 1, 25, 5, 21, 19, 51,
			119, 159, 95, 223, 479, 991, 63, 575,
			127, 639, 383, 895, 255, 767, 511, 1023,
			14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			27, 59, 7, 39, 23, 55, 30, 1, 17, 9, 25, 5, 0, 8, 4, 12,
			2, 10, 6, 21, 13, 29, 3, 19, 11, 15, 47, 31, 95, 63, 127, 255,
			767, 2815, 1791, 3839, 511, 2559, 1535, 3583, 1023, 3071, 2047, 4095,
		}
		.cmd_code_ = [512]byte{
			0xff, 0x77, 0xd5, 0xbf, 0xe7, 0xde, 0xea, 0x9e, 0x51, 0x5d, 0xde, 0xc6,
			0x70, 0x57, 0xbc, 0x58, 0x58, 0x58, 0xd8, 0xd8, 0x58, 0xd5, 0xcb, 0x8c,
			0xea, 0xe0, 0xc3, 0x87, 0x1f, 0x83, 0xc1, 0x60, 0x1c, 0x67, 0xb2, 0xaa,
			0x06, 0x83, 0xc1, 0x60, 0x30, 0x18, 0xcc, 0xa1, 0xce, 0x88, 0x54, 0x94,
			0x46, 0xe1, 0xb0, 0xd0, 0x4e, 0xb2, 0xf7, 0x04, 0x00,
		}
		.cmd_code_numbits_ = 448
	}

	.is_initialized_ = true
	return true
}

func encoderInitParams( *encoderParams) {
	.mode = defaultMode
	.large_window = false
	.quality = defaultQuality
	.lgwin = defaultWindow
	.lgblock = 0
	.size_hint = 0
	.disable_literal_context_modeling = false
	initEncoderDictionary(&.dictionary)
	.dist.distance_postfix_bits = 0
	.dist.num_direct_distance_codes = 0
	.dist.alphabet_size = uint32(distanceAlphabetSize(0, 0, maxDistanceBits))
	.dist.max_distance = maxDistance
}

func encoderInitState( *Writer) {
	encoderInitParams(&.params)
	.input_pos_ = 0
	.commands = .commands[:0]
	.num_literals_ = 0
	.last_insert_len_ = 0
	.last_flush_pos_ = 0
	.last_processed_pos_ = 0
	.prev_byte_ = 0
	.prev_byte2_ = 0
	if .hasher_ != nil {
		.hasher_.Common().is_prepared_ = false
	}
	.cmd_code_numbits_ = 0
	.stream_state_ = streamProcessing
	.is_last_block_emitted_ = false
	.is_initialized_ = false

	ringBufferInit(&.ringbuffer_)

	/* Initialize distance cache. */
	.dist_cache_[0] = 4

	.dist_cache_[1] = 11
	.dist_cache_[2] = 15
	.dist_cache_[3] = 16

	/* Save the state of the distance cache in case we need to restore it for
	   emitting an uncompressed block. */
	copy(.saved_dist_cache_[:], .dist_cache_[:])
}

/*
   Copies the given input data to the internal ring buffer of the compressor.
   No processing of the data occurs at this time and this function can be
   called multiple times before calling WriteBrotliData() to process the
   accumulated input. At most input_block_size() bytes of input data can be
   copied to the ring buffer, otherwise the next WriteBrotliData() will fail.
*/
func copyInputToRingBuffer( *Writer,  uint,  []byte) {
	var  *ringBuffer = &.ringbuffer_
	ringBufferWrite(, , )
	.input_pos_ += uint64()

	/* TL;DR: If needed, initialize 7 more bytes in the ring buffer to make the
	   hashing not depend on uninitialized data. This makes compression
	   deterministic and it prevents uninitialized memory warnings in Valgrind.
	   Even without erasing, the output would be valid (but nondeterministic).

	   Background information: The compressor stores short (at most 8 bytes)
	   substrings of the input already read in a hash table, and detects
	   repetitions by looking up such substrings in the hash table. If it
	   can find a substring, it checks whether the substring is really there
	   in the ring buffer (or it's just a hash collision). Should the hash
	   table become corrupt, this check makes sure that the output is
	   still valid, albeit the compression ratio would be bad.

	   The compressor populates the hash table from the ring buffer as it's
	   reading new bytes from the input. However, at the last few indexes of
	   the ring buffer, there are not enough bytes to build full-length
	   substrings from. Since the hash table always contains full-length
	   substrings, we erase with dummy zeros here to make sure that those
	   substrings will contain zeros at the end instead of uninitialized
	   data.

	   Please note that erasing is not necessary (because the
	   memory region is already initialized since he ring buffer
	   has a `tail' that holds a copy of the beginning,) so we
	   skip erasing if we have already gone around at least once in
	   the ring buffer.

	   Only clear during the first round of ring-buffer writes. On
	   subsequent rounds data in the ring-buffer would be affected. */
	if .pos_ <= .mask_ {
		/* This is the first time when the ring buffer is being written.
		   We clear 7 bytes just after the bytes that have been copied from
		   the input buffer.

		   The ring-buffer has a "tail" that holds a copy of the beginning,
		   but only once the ring buffer has been fully written once, i.e.,
		   pos <= mask. For the first time, we need to write values
		   in this tail (where index may be larger than mask), so that
		   we have exactly defined behavior and don't read uninitialized
		   memory. Due to performance reasons, hashing reads data using a
		   LOAD64, which can go 7 bytes beyond the bytes written in the
		   ring-buffer. */
		for  := 0;  < int(7); ++ {
			.buffer_[.pos_:][] = 0
		}
	}
}

/* Marks all input as processed.
   Returns true if position wrapping occurs. */
func updateLastProcessedPos( *Writer) bool {
	var  uint32 = wrapPosition(.last_processed_pos_)
	var  uint32 = wrapPosition(.input_pos_)
	.last_processed_pos_ = .input_pos_
	return  < 
}

func extendLastCommand( *Writer,  *uint32,  *uint32) {
	var  *command = &.commands[len(.commands)-1]
	var  []byte = .ringbuffer_.buffer_
	var  uint32 = .ringbuffer_.mask_
	var  uint64 = ((uint64(1)) << .params.lgwin) - windowGap
	var  uint64 = uint64(.copy_len_) & 0x1FFFFFF
	var  uint64 = .last_processed_pos_ - 
	var  uint64
	if  <  {
		 = 
	} else {
		 = 
	}
	var  uint64 = uint64(.dist_cache_[0])
	var  uint32 = commandRestoreDistanceCode(, &.params.dist)
	if  < numDistanceShortCodes || uint64(-(numDistanceShortCodes-1)) ==  {
		if  <=  {
			for * != 0 && [*&] == [(uint64(*)-)&uint64()] {
				.copy_len_++
				(*)--
				(*)++
			}
		}

		/* The copy length is at most the metablock size, and thus expressible. */
		getLengthCode(uint(.insert_len_), uint(int(.copy_len_&0x1FFFFFF)+int(.copy_len_>>25)), (.dist_prefix_&0x3FF == 0), &.cmd_prefix_)
	}
}

/*
   Processes the accumulated input data and writes
   the new output meta-block to s.dest, if one has been
   created (otherwise the processed input data is buffered internally).
   If |is_last| or |force_flush| is true, an output meta-block is
   always created. However, until |is_last| is true encoder may retain up
   to 7 bits of the last byte of output. To force encoder to dump the remaining
   bits use WriteMetadata() to append an empty meta-data block.
   Returns false if the size of the input data is larger than
   input_block_size().
*/
func encodeData( *Writer,  bool,  bool) bool {
	var  uint64 = unprocessedInputSize()
	var  uint32 = uint32()
	var  uint32 = wrapPosition(.last_processed_pos_)
	var  []byte
	var  uint32
	var  int

	 = .ringbuffer_.buffer_
	 = .ringbuffer_.mask_

	/* Adding more blocks after "last" block is forbidden. */
	if .is_last_block_emitted_ {
		return false
	}
	if  {
		.is_last_block_emitted_ = true
	}

	if  > uint64(inputBlockSize()) {
		return false
	}

	if .params.quality == fastTwoPassCompressionQuality {
		if .command_buf_ == nil || cap(.command_buf_) < int(kCompressFragmentTwoPassBlockSize) {
			.command_buf_ = make([]uint32, kCompressFragmentTwoPassBlockSize)
			.literal_buf_ = make([]byte, kCompressFragmentTwoPassBlockSize)
		} else {
			.command_buf_ = .command_buf_[:kCompressFragmentTwoPassBlockSize]
			.literal_buf_ = .literal_buf_[:kCompressFragmentTwoPassBlockSize]
		}
	}

	if .params.quality == fastOnePassCompressionQuality || .params.quality == fastTwoPassCompressionQuality {
		var  []byte
		var  uint = uint(.last_bytes_bits_)
		var  uint
		var  []int

		if  == 0 && ! {
			/* We have no new input data and we don't have to finish the stream, so
			   nothing to do. */
			return true
		}

		 = .getStorage(int(2* + 503))
		[0] = byte(.last_bytes_)
		[1] = byte(.last_bytes_ >> 8)
		 = getHashTable(, .params.quality, uint(), &)
		if .params.quality == fastOnePassCompressionQuality {
			compressFragmentFast([&:], uint(), , , , .cmd_depths_[:], .cmd_bits_[:], &.cmd_code_numbits_, .cmd_code_[:], &, )
		} else {
			compressFragmentTwoPass([&:], uint(), , .command_buf_, .literal_buf_, , , &, )
		}

		.last_bytes_ = uint16([>>3])
		.last_bytes_bits_ = byte( & 7)
		updateLastProcessedPos()
		.writeOutput([:>>3])
		return true
	}
	{
		/* Theoretical max number of commands is 1 per 2 bytes. */
		 := len(.commands) + int()/2 + 1
		if  > cap(.commands) {
			/* Reserve a bit more memory to allow merging with a next block
			   without reallocation: that would impact speed. */
			 += int(/4) + 16

			 := make([]command, len(.commands), )
			if .commands != nil {
				copy(, .commands)
			}

			.commands = 
		}
	}

	initOrStitchToPreviousBlock(&.hasher_, , uint(), &.params, uint(), uint(), )

	 = chooseContextMode(&.params, , uint(wrapPosition(.last_flush_pos_)), uint(), uint(.input_pos_-.last_flush_pos_))

	if len(.commands) != 0 && .last_insert_len_ == 0 {
		extendLastCommand(, &, &)
	}

	if .params.quality == zopflificationQuality {
		assert(.params.hasher.type_ == 10)
		createZopfliBackwardReferences(uint(), uint(), , uint(), &.params, .hasher_.(*h10), .dist_cache_[:], &.last_insert_len_, &.commands, &.num_literals_)
	} else if .params.quality == hqZopflificationQuality {
		assert(.params.hasher.type_ == 10)
		createHqZopfliBackwardReferences(uint(), uint(), , uint(), &.params, .hasher_, .dist_cache_[:], &.last_insert_len_, &.commands, &.num_literals_)
	} else {
		createBackwardReferences(uint(), uint(), , uint(), &.params, .hasher_, .dist_cache_[:], &.last_insert_len_, &.commands, &.num_literals_)
	}
	{
		var  uint = maxMetablockSize(&.params)
		var  uint =  / 8
		 := int( / 8)
		var  uint = uint(.input_pos_ - .last_flush_pos_)
		var  bool = (+inputBlockSize() <= )
		var  bool = (.params.quality < minQualityForBlockSplit && .num_literals_+uint(len(.commands)) >= maxNumDelayedSymbols)
		/* If maximal possible additional block doesn't fit metablock, flush now. */
		/* TODO: Postpone decision until next block arrives? */

		/* If block splitting is not used, then flush as soon as there is some
		   amount of commands / literals produced. */
		if ! && ! && ! &&  && .num_literals_ <  && len(.commands) <  {
			/* Merge with next input block. Everything will happen later. */
			if updateLastProcessedPos() {
				hasherReset(.hasher_)
			}

			return true
		}
	}

	/* Create the last insert-only command. */
	if .last_insert_len_ > 0 {
		.commands = append(.commands, makeInsertCommand(.last_insert_len_))
		.num_literals_ += .last_insert_len_
		.last_insert_len_ = 0
	}

	if ! && .input_pos_ == .last_flush_pos_ {
		/* We have no new input data and we don't have to finish the stream, so
		   nothing to do. */
		return true
	}

	assert(.input_pos_ >= .last_flush_pos_)
	assert(.input_pos_ > .last_flush_pos_ || )
	assert(.input_pos_-.last_flush_pos_ <= 1<<24)
	{
		var  uint32 = uint32(.input_pos_ - .last_flush_pos_)
		var  []byte = .getStorage(int(2* + 503))
		var  uint = uint(.last_bytes_bits_)
		[0] = byte(.last_bytes_)
		[1] = byte(.last_bytes_ >> 8)
		writeMetaBlockInternal(, uint(), .last_flush_pos_, uint(), , , &.params, .prev_byte_, .prev_byte2_, .num_literals_, .commands, .saved_dist_cache_[:], .dist_cache_[:], &, )
		.last_bytes_ = uint16([>>3])
		.last_bytes_bits_ = byte( & 7)
		.last_flush_pos_ = .input_pos_
		if updateLastProcessedPos() {
			hasherReset(.hasher_)
		}

		if .last_flush_pos_ > 0 {
			.prev_byte_ = [(uint32(.last_flush_pos_)-1)&]
		}

		if .last_flush_pos_ > 1 {
			.prev_byte2_ = [uint32(.last_flush_pos_-2)&]
		}

		.commands = .commands[:0]
		.num_literals_ = 0

		/* Save the state of the distance cache in case we need to restore it for
		   emitting an uncompressed block. */
		copy(.saved_dist_cache_[:], .dist_cache_[:])

		.writeOutput([:>>3])
		return true
	}
}

/* Dumps remaining output bits and metadata header to |header|.
   Returns number of produced bytes.
   REQUIRED: |header| should be 8-byte aligned and at least 16 bytes long.
   REQUIRED: |block_size| <= (1 << 24). */
func writeMetadataHeader( *Writer,  uint,  []byte) uint {
	 := uint(.last_bytes_bits_)
	[0] = byte(.last_bytes_)
	[1] = byte(.last_bytes_ >> 8)
	.last_bytes_ = 0
	.last_bytes_bits_ = 0

	writeBits(1, 0, &, )
	writeBits(2, 3, &, )
	writeBits(1, 0, &, )
	if  == 0 {
		writeBits(2, 0, &, )
	} else {
		var  uint32
		if  == 1 {
			 = 0
		} else {
			 = log2FloorNonZero(uint(uint32()-1)) + 1
		}
		var  uint32 = ( + 7) / 8
		writeBits(2, uint64(), &, )
		writeBits(uint(8*), uint64()-1, &, )
	}

	return ( + 7) >> 3
}

func injectBytePaddingBlock( *Writer) {
	var  uint32 = uint32(.last_bytes_)
	var  uint = uint(.last_bytes_bits_)
	.last_bytes_ = 0
	.last_bytes_bits_ = 0

	/* is_last = 0, data_nibbles = 11, reserved = 0, meta_nibbles = 00 */
	 |= 0x6 << 

	 += 6

	 := .tiny_buf_.u8[:]

	[0] = byte()
	if  > 8 {
		[1] = byte( >> 8)
	}
	if  > 16 {
		[2] = byte( >> 16)
	}
	.writeOutput([:(+7)>>3])
}

func checkFlushComplete( *Writer) {
	if .stream_state_ == streamFlushRequested && .err == nil {
		.stream_state_ = streamProcessing
	}
}

func encoderCompressStreamFast( *Writer,  int,  *uint,  *[]byte) bool {
	var  uint = uint(1) << .params.lgwin
	var  uint = brotli_min_size_t(kCompressFragmentTwoPassBlockSize, brotli_min_size_t(*, ))
	var  []uint32 = nil
	var  []byte = nil
	if .params.quality != fastOnePassCompressionQuality && .params.quality != fastTwoPassCompressionQuality {
		return false
	}

	if .params.quality == fastTwoPassCompressionQuality {
		if .command_buf_ == nil || cap(.command_buf_) < int() {
			.command_buf_ = make([]uint32, )
			.literal_buf_ = make([]byte, )
		} else {
			.command_buf_ = .command_buf_[:]
			.literal_buf_ = .literal_buf_[:]
		}

		 = .command_buf_
		 = .literal_buf_
	}

	for {
		if .stream_state_ == streamFlushRequested && .last_bytes_bits_ != 0 {
			injectBytePaddingBlock()
			continue
		}

		/* Compress block only when stream is not
		   finished, there is no pending flush request, and there is either
		   additional input or pending operation. */
		if .stream_state_ == streamProcessing && (* != 0 ||  != int(operationProcess)) {
			var  uint = brotli_min_size_t(, *)
			var  bool = (* == ) && ( == int(operationFinish))
			var  bool = (* == ) && ( == int(operationFlush))
			var  uint = 2* + 503
			var  []byte = nil
			var  uint = uint(.last_bytes_bits_)
			var  uint
			var  []int

			if  &&  == 0 {
				.stream_state_ = streamFlushRequested
				continue
			}

			 = .getStorage(int())

			[0] = byte(.last_bytes_)
			[1] = byte(.last_bytes_ >> 8)
			 = getHashTable(, .params.quality, , &)

			if .params.quality == fastOnePassCompressionQuality {
				compressFragmentFast(*, , , , , .cmd_depths_[:], .cmd_bits_[:], &.cmd_code_numbits_, .cmd_code_[:], &, )
			} else {
				compressFragmentTwoPass(*, , , , , , , &, )
			}

			* = (*)[:]
			* -= 
			var  uint =  >> 3
			.writeOutput([:])

			.last_bytes_ = uint16([>>3])
			.last_bytes_bits_ = byte( & 7)

			if  {
				.stream_state_ = streamFlushRequested
			}
			if  {
				.stream_state_ = streamFinished
			}
			continue
		}

		break
	}

	checkFlushComplete()
	return true
}

func processMetadata( *Writer,  *uint,  *[]byte) bool {
	if * > 1<<24 {
		return false
	}

	/* Switch to metadata block workflow, if required. */
	if .stream_state_ == streamProcessing {
		.remaining_metadata_bytes_ = uint32(*)
		.stream_state_ = streamMetadataHead
	}

	if .stream_state_ != streamMetadataHead && .stream_state_ != streamMetadataBody {
		return false
	}

	for {
		if .stream_state_ == streamFlushRequested && .last_bytes_bits_ != 0 {
			injectBytePaddingBlock()
			continue
		}

		if .input_pos_ != .last_flush_pos_ {
			var  bool = encodeData(, false, true)
			if ! {
				return false
			}
			continue
		}

		if .stream_state_ == streamMetadataHead {
			 := writeMetadataHeader(, uint(.remaining_metadata_bytes_), .tiny_buf_.u8[:])
			.writeOutput(.tiny_buf_.u8[:])
			.stream_state_ = streamMetadataBody
			continue
		} else {
			/* Exit workflow only when there is no more input and no more output.
			   Otherwise client may continue producing empty metadata blocks. */
			if .remaining_metadata_bytes_ == 0 {
				.remaining_metadata_bytes_ = math.MaxUint32
				.stream_state_ = streamProcessing
				break
			}

			/* This guarantees progress in "TakeOutput" workflow. */
			var  uint32 = brotli_min_uint32_t(.remaining_metadata_bytes_, 16)
			copy(.tiny_buf_.u8[:], (*)[:])
			* = (*)[:]
			* -= uint()
			.remaining_metadata_bytes_ -= 
			.writeOutput(.tiny_buf_.u8[:])

			continue
		}
	}

	return true
}

func updateSizeHint( *Writer,  uint) {
	if .params.size_hint == 0 {
		var  uint64 = unprocessedInputSize()
		var  uint64 = uint64()
		var  uint32 = 1 << 30
		var  uint32
		if ( >= uint64()) || ( >= uint64()) || (( + ) >= uint64()) {
			 = 
		} else {
			 = uint32( + )
		}

		.params.size_hint = uint()
	}
}

func encoderCompressStream( *Writer,  int,  *uint,  *[]byte) bool {
	if !ensureInitialized() {
		return false
	}

	/* Unfinished metadata block; check requirements. */
	if .remaining_metadata_bytes_ != math.MaxUint32 {
		if uint32(*) != .remaining_metadata_bytes_ {
			return false
		}
		if  != int(operationEmitMetadata) {
			return false
		}
	}

	if  == int(operationEmitMetadata) {
		updateSizeHint(, 0) /* First data metablock might be emitted here. */
		return processMetadata(, , )
	}

	if .stream_state_ == streamMetadataHead || .stream_state_ == streamMetadataBody {
		return false
	}

	if .stream_state_ != streamProcessing && * != 0 {
		return false
	}

	if .params.quality == fastOnePassCompressionQuality || .params.quality == fastTwoPassCompressionQuality {
		return encoderCompressStreamFast(, , , )
	}

	for {
		var  uint = remainingInputBlockSize()

		if  != 0 && * != 0 {
			var  uint = brotli_min_size_t(, *)
			copyInputToRingBuffer(, , *)
			* = (*)[:]
			* -= 
			continue
		}

		if .stream_state_ == streamFlushRequested && .last_bytes_bits_ != 0 {
			injectBytePaddingBlock()
			continue
		}

		/* Compress data only when stream is not
		   finished and there is no pending flush request. */
		if .stream_state_ == streamProcessing {
			if  == 0 ||  != int(operationProcess) {
				var  bool = ((* == 0) &&  == int(operationFinish))
				var  bool = ((* == 0) &&  == int(operationFlush))
				var  bool
				updateSizeHint(, *)
				 = encodeData(, , )
				if ! {
					return false
				}
				if  {
					.stream_state_ = streamFlushRequested
				}
				if  {
					.stream_state_ = streamFinished
				}
				continue
			}
		}

		break
	}

	checkFlushComplete()
	return true
}

func ( *Writer) ( []byte) {
	if .err != nil {
		return
	}

	_, .err = .dst.Write()
	if .err == nil {
		checkFlushComplete()
	}
}