// 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 fse

import (
	
	
	
)

// bitReader reads a bitstream in reverse.
// The last set bit indicates the start of the stream and is used
// for aligning the input.
type bitReader struct {
	in       []byte
	off      uint // next byte to read is at in[off - 1]
	value    uint64
	bitsRead uint8
}

// init initializes and resets the bit reader.
func ( *bitReader) ( []byte) error {
	if len() < 1 {
		return errors.New("corrupt stream: too short")
	}
	.in = 
	.off = uint(len())
	// The highest bit of the last byte indicates where to start
	 := [len()-1]
	if  == 0 {
		return errors.New("corrupt stream, did not find end of stream")
	}
	.bitsRead = 64
	.value = 0
	if len() >= 8 {
		.fillFastStart()
	} else {
		.fill()
		.fill()
	}
	.bitsRead += 8 - uint8(highBits(uint32()))
	return nil
}

// getBits will return n bits. n can be 0.
func ( *bitReader) ( uint8) uint16 {
	if  == 0 || .bitsRead >= 64 {
		return 0
	}
	return .getBitsFast()
}

// getBitsFast requires that at least one bit is requested every time.
// There are no checks if the buffer is filled.
func ( *bitReader) ( uint8) uint16 {
	const  = 64 - 1
	 := uint16((.value << (.bitsRead & )) >> (( + 1 - ) & ))
	.bitsRead += 
	return 
}

// fillFast() will make sure at least 32 bits are available.
// There must be at least 4 bytes available.
func ( *bitReader) () {
	if .bitsRead < 32 {
		return
	}
	// 2 bounds checks.
	 := .in[.off-4:]
	 = [:4]
	 := (uint32([0])) | (uint32([1]) << 8) | (uint32([2]) << 16) | (uint32([3]) << 24)
	.value = (.value << 32) | uint64()
	.bitsRead -= 32
	.off -= 4
}

// fill() will make sure at least 32 bits are available.
func ( *bitReader) () {
	if .bitsRead < 32 {
		return
	}
	if .off > 4 {
		 := .in[.off-4:]
		 = [:4]
		 := (uint32([0])) | (uint32([1]) << 8) | (uint32([2]) << 16) | (uint32([3]) << 24)
		.value = (.value << 32) | uint64()
		.bitsRead -= 32
		.off -= 4
		return
	}
	for .off > 0 {
		.value = (.value << 8) | uint64(.in[.off-1])
		.bitsRead -= 8
		.off--
	}
}

// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read.
func ( *bitReader) () {
	// Do single re-slice to avoid bounds checks.
	.value = binary.LittleEndian.Uint64(.in[.off-8:])
	.bitsRead = 0
	.off -= 8
}

// finished returns true if all bits have been read from the bit stream.
func ( *bitReader) () bool {
	return .bitsRead >= 64 && .off == 0
}

// close the bitstream and returns an error if out-of-buffer reads occurred.
func ( *bitReader) () error {
	// Release reference.
	.in = nil
	if .bitsRead > 64 {
		return io.ErrUnexpectedEOF
	}
	return nil
}