mirror of
https://github.com/TomHarte/CLK.git
synced 2025-10-25 09:27:01 +00:00
Work in terms of the number of bits to be handled.
This commit is contained in:
@@ -14,13 +14,25 @@
|
||||
|
||||
namespace Numeric {
|
||||
|
||||
template <typename MaxIntT, bool lsb_first>
|
||||
/*!
|
||||
Given a means to fetch the next byte from a byte stream, serialises those bytes into a bit stream.
|
||||
|
||||
@c max_bits is the largest number of bits that'll be read at once.
|
||||
@c lsb_first if true then the LSB of each byte from the byte stream is the first bit read. Otherwise it's the MSB.
|
||||
*/
|
||||
template <int max_bits, bool lsb_first>
|
||||
class BitStream {
|
||||
public:
|
||||
using IntT = min_int_size_t<max_bits + 8>;
|
||||
|
||||
BitStream(std::function<uint8_t(void)> next_byte) : next_byte_(next_byte) {}
|
||||
|
||||
/// @returns An integer composed of the next n bits of the bitstream where n is:
|
||||
/// * the template parameter `bits` if it is non-zero; or
|
||||
/// * the function argument `rbits` otherwise.
|
||||
/// `rbits` is ignored if `bits` is non-zero.
|
||||
template <size_t bits = 0>
|
||||
MaxIntT next(size_t rbits = 0) {
|
||||
IntT next([[maybe_unused]] const size_t rbits = 0) {
|
||||
const size_t required = bits ? bits : rbits;
|
||||
while(enqueued_ < required) {
|
||||
uint8_t next = next_byte_();
|
||||
@@ -28,11 +40,11 @@ public:
|
||||
next = bit_reverse(next);
|
||||
}
|
||||
|
||||
input_ |= ShiftT(next) << (BitSize - 8 - enqueued_);
|
||||
input_ |= IntT(next) << (BitSize - 8 - enqueued_);
|
||||
enqueued_ += 8;
|
||||
}
|
||||
|
||||
const auto result = MaxIntT(input_ >> (BitSize - required));
|
||||
const auto result = IntT(input_ >> (BitSize - required));
|
||||
input_ <<= required;
|
||||
enqueued_ -= required;
|
||||
return result;
|
||||
@@ -43,9 +55,8 @@ private:
|
||||
|
||||
size_t enqueued_{};
|
||||
|
||||
using ShiftT = uint_t<sizeof(MaxIntT) * 8 * 2>;
|
||||
ShiftT input_{};
|
||||
static constexpr size_t BitSize = sizeof(ShiftT) * 8;
|
||||
IntT input_{};
|
||||
static constexpr size_t BitSize = sizeof(IntT) * 8;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user