// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package vp9

import 

var errNotEnoughBits = errors.New("not enough bits")

func hasSpace( []byte,  int,  int) error {
	if  > ((len() * 8) - ) {
		return errNotEnoughBits
	}

	return nil
}

func readFlag( []byte,  *int) (bool, error) {
	 := hasSpace(, *, 1)
	if  != nil {
		return false, 
	}

	return readFlagUnsafe(, ), nil
}

func readFlagUnsafe( []byte,  *int) bool {
	 := ([*>>0x03] >> (7 - (* & 0x07))) & 0x01
	*++

	return  == 1
}

func readBits( []byte,  *int,  int) (uint64, error) {
	 := hasSpace(, *, )
	if  != nil {
		return 0, 
	}

	return readBitsUnsafe(, , ), nil
}

func readBitsUnsafe( []byte,  *int,  int) uint64 {
	 := 8 - (* & 0x07)
	if  <  {
		 := uint64(([*>>0x03] >> ( - )) & (1<< - 1))
		* += 

		return 
	}

	 := uint64([*>>0x03] & (1<< - 1))
	* += 
	 -= 

	for  >= 8 {
		 = ( << 8) | uint64([*>>0x03])
		* += 8
		 -= 8
	}

	if  > 0 {
		 = ( << ) | uint64([*>>0x03]>>(8-))
		* += 
	}

	return 
}