// Copyright 2018 Klaus Post. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on work Copyright (c) 2013, Yann Collet, released under BSD License.

package huff0

// bitWriter will write bits.
// First bit will be LSB of the first byte of output.
type bitWriter struct {
	bitContainer uint64
	nBits        uint8
	out          []byte
}

// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated.
// It will not check if there is space for them, so the caller must ensure that it has flushed recently.
func ( *bitWriter) ( uint16,  uint8) {
	.bitContainer |= uint64() << (.nBits & 63)
	.nBits += 
}

// encSymbol will add up to 16 bits. value may not contain more set bits than indicated.
// It will not check if there is space for them, so the caller must ensure that it has flushed recently.
func ( *bitWriter) ( cTable,  byte) {
	 := []
	.bitContainer |= uint64(.val) << (.nBits & 63)
	if false {
		if .nBits == 0 {
			panic("nbits 0")
		}
	}
	.nBits += .nBits
}

// encTwoSymbols will add up to 32 bits. value may not contain more set bits than indicated.
// It will not check if there is space for them, so the caller must ensure that it has flushed recently.
func ( *bitWriter) ( cTable, ,  byte) {
	 := []
	 := []
	 := .nBits & 63
	 := uint64(.val) | (uint64(.val) << (.nBits & 63))
	.bitContainer |=  << 
	if false {
		if .nBits == 0 {
			panic("nbitsA 0")
		}
		if .nBits == 0 {
			panic("nbitsB 0")
		}
	}
	.nBits += .nBits + .nBits
}

// encFourSymbols adds up to 32 bits from four symbols.
// It will not check if there is space for them,
// so the caller must ensure that b has been flushed recently.
func ( *bitWriter) (, , ,  cTableEntry) {
	 := .nBits
	 :=  + .nBits
	 :=  + .nBits
	 :=  + .nBits
	 := uint64(.val) |
		(uint64(.val) << ( & 63)) |
		(uint64(.val) << ( & 63)) |
		(uint64(.val) << ( & 63))
	.bitContainer |=  << (.nBits & 63)
	.nBits += 
}

// flush32 will flush out, so there are at least 32 bits available for writing.
func ( *bitWriter) () {
	if .nBits < 32 {
		return
	}
	.out = append(.out,
		byte(.bitContainer),
		byte(.bitContainer>>8),
		byte(.bitContainer>>16),
		byte(.bitContainer>>24))
	.nBits -= 32
	.bitContainer >>= 32
}

// flushAlign will flush remaining full bytes and align to next byte boundary.
func ( *bitWriter) () {
	 := (.nBits + 7) >> 3
	for  := uint8(0);  < ; ++ {
		.out = append(.out, byte(.bitContainer>>(*8)))
	}
	.nBits = 0
	.bitContainer = 0
}

// close will write the alignment bit and write the final byte(s)
// to the output.
func ( *bitWriter) () {
	// End mark
	.addBits16Clean(1, 1)
	// flush until next byte.
	.flushAlign()
}