// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reads the Brotli bit stream, least significant bit of each byte first, //! out of whatever input the caller has handed over so far. //! //! Bits are drawn from the caller's slice into a 64-bit accumulator, and the //! accumulator survives between calls, so a value split across two of the //! caller's buffers is read as if it were not. Every read is all or nothing: //! if the bits it needs are not there yet it takes none of them and says so, //! which is what lets the decompressor stop at any point and pick up again when //! more input arrives. const std = @import("std"); const BitReader = @This(); /// Unread bits, the next one in the least significant position. Bits above /// `count` are always zero. acc: u64 = 0, /// How many bits of `acc` are unread. count: u32 = 0, /// The caller's input for the current call, and how far into it the /// accumulator has drawn. input: []const u8 = &.{}, pos: usize = 0, /// Starts a call with fresh input. pub fn begin(br: *BitReader, input: []const u8) void { br.input = input; br.pos = 0; } /// Draws as many whole bytes from the input as fit in the accumulator. pub fn refill(br: *BitReader) void { if (br.count > 56) return; if (br.input.len - br.pos >= 8) { const word = std.mem.readInt(u64, br.input[br.pos..][0..8], .little); const bytes = (64 - br.count) / 8; br.acc |= word << @intCast(br.count); br.count += bytes * 8; br.pos += bytes; if (br.count < 64) br.acc &= (@as(u64, 1) << @intCast(br.count)) - 1; return; } while (br.count <= 56 and br.pos < br.input.len) { br.acc |= @as(u64, br.input[br.pos]) << @intCast(br.count); br.count += 8; br.pos += 1; } } /// Whether at least `n` bits are ready to be read, drawing more if not. /// `n` may be at most 57, which a refill always reaches when the input /// allows. pub inline fn has(br: *BitReader, n: u32) bool { std.debug.assert(n <= 57); if (br.count < n) br.refill(); return br.count >= n; } /// The next `n` bits, without consuming them. They must be present. pub inline fn peek(br: *const BitReader, n: u32) u32 { std.debug.assert(n <= 32 and n <= br.count); return @truncate(br.acc & ((@as(u64, 1) << @intCast(n)) - 1)); } pub inline fn consume(br: *BitReader, n: u32) void { std.debug.assert(n <= br.count); // A shift by 64 is not defined, and only `n == 64` would need one. br.acc = if (n == 64) 0 else br.acc >> @intCast(n); br.count -= n; } /// Reads an `n`-bit value, or returns null and reads nothing if fewer than /// `n` bits are available. pub inline fn read(br: *BitReader, n: u32) ?u32 { if (!br.has(n)) return null; const v = br.peek(n); br.consume(n); return v; } /// Consumes the bits left in the current byte, returning them. The format /// requires them to be zero wherever it skips to a byte boundary. pub fn alignToByte(br: *BitReader) u32 { const n = br.count % 8; const v = br.peek(n); br.consume(n); return v; } /// The next byte of a byte-aligned stretch of the stream, or null if the /// input is exhausted. Only valid on a byte boundary. pub fn readByte(br: *BitReader) ?u8 { std.debug.assert(br.count % 8 == 0); if (br.count >= 8) { const b: u8 = @truncate(br.acc); br.consume(8); return b; } if (br.pos == br.input.len) return null; defer br.pos += 1; return br.input[br.pos]; } /// Up to `max` bytes of a byte-aligned stretch straight from the caller's /// input, consumed. Only valid once the accumulator holds no whole bytes. pub fn takeBytes(br: *BitReader, max: usize) []const u8 { std.debug.assert(br.count == 0); const n = @min(max, br.input.len - br.pos); defer br.pos += n; return br.input[br.pos..][0..n]; } /// Gives back to the input the whole bytes the accumulator drew from it /// during this call but has not used, so that the caller is told they were /// not consumed. Bytes drawn during an earlier call cannot be given back. pub fn unload(br: *BitReader) void { const bytes = @min(br.count / 8, br.pos); br.pos -= bytes; br.count -= @intCast(bytes * 8); br.acc &= if (br.count == 0) 0 else (@as(u64, 1) << @intCast(br.count)) - 1; } test "bits come out least significant first, across refills" { var br: BitReader = .{}; br.begin(&.{ 0b1010_0110, 0xff }); try std.testing.expectEqual(0b0, br.read(1)); try std.testing.expectEqual(0b011, br.read(3)); try std.testing.expectEqual(0b1_1010, br.read(5)); try std.testing.expectEqual(null, br.read(8)); try std.testing.expectEqual(0b111_1111, br.read(7)); try std.testing.expectEqual(null, br.read(1)); br.begin(&.{0x01}); try std.testing.expectEqual(1, br.read(1)); } test "the fast refill keeps the accumulator clean" { var br: BitReader = .{}; const bytes = [_]u8{ 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa }; br.begin(&bytes); try std.testing.expectEqual(0x1, br.read(4)); try std.testing.expectEqual(0x21, br.read(8)); try std.testing.expectEqual(0x44332, br.read(20)); try std.testing.expectEqual(0x88776655, br.read(32)); try std.testing.expectEqual(0xaa99, br.read(16)); try std.testing.expectEqual(null, br.read(1)); } test "unload returns unread whole bytes" { var br: BitReader = .{}; br.begin(&.{ 0x01, 0x02, 0x03 }); try std.testing.expectEqual(1, br.read(3)); br.unload(); try std.testing.expectEqual(1, br.pos); try std.testing.expectEqual(5, br.count); }