// Copyright 2019 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 ccitt

import (
	
	
)

type bitWriter struct {
	w io.Writer

	// order is whether to process w's bytes LSB first or MSB first.
	order Order

	// The high nBits bits of the bits field hold encoded bits to be written to w.
	bits  uint64
	nBits uint32

	// bytes[:bw] holds encoded bytes not yet written to w.
	// Overflow protection is ensured by using a multiple of 8 as bytes length.
	bw    uint32
	bytes [1024]uint8
}

// flushBits copies 64 bits from b.bits to b.bytes. If b.bytes is then full, it
// is written to b.w.
func ( *bitWriter) () error {
	binary.BigEndian.PutUint64(.bytes[.bw:], .bits)
	.bits = 0
	.nBits = 0
	.bw += 8
	if .bw < uint32(len(.bytes)) {
		return nil
	}
	.bw = 0
	if .order != MSB {
		reverseBitsWithinBytes(.bytes[:])
	}
	,  := .w.Write(.bytes[:])
	return 
}

// close finalizes a bitcode stream by writing any
// pending bits to bitWriter's underlying io.Writer.
func ( *bitWriter) () error {
	// Write any encoded bits to bytes.
	if .nBits > 0 {
		binary.BigEndian.PutUint64(.bytes[.bw:], .bits)
		.bw += (.nBits + 7) >> 3
	}

	if .order != MSB {
		reverseBitsWithinBytes(.bytes[:.bw])
	}

	// Write b.bw bytes to b.w.
	,  := .w.Write(.bytes[:.bw])
	return 
}

// alignToByteBoundary rounds b.nBits up to a multiple of 8.
// If all 64 bits are used, flush them to bitWriter's bytes.
func ( *bitWriter) () error {
	if .nBits = (.nBits + 7) &^ 7; .nBits == 64 {
		return .flushBits()
	}
	return nil
}

// writeCode writes a variable length bitcode to b's underlying io.Writer.
func ( *bitWriter) ( bitString) error {
	 := .bits
	 := .nBits
	if 64-.nBits >=  {
		// b.bits has sufficient room for storing nBits bits.
		.bits |= uint64() << (64 -  - .nBits)
		.nBits += 
		if .nBits == 64 {
			return .flushBits()
		}
		return nil
	}

	// Number of leading bits that fill b.bits.
	 := 64 - .nBits

	// Fill b.bits then flush and write remaining bits.
	.bits |= uint64() >> ( - )
	.nBits = 64

	if  := .flushBits();  != nil {
		return 
	}

	 -= 
	.bits = uint64() << (64 - )
	.nBits = 
	return nil
}