pub fn writeBits(self: *BcWriter, value: anytype, bits: u16) Error!void self: *BcWritervaluebits: u16OutOfMemory53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 pub fn writeBits(self: *BcWriter, value: anytype, bits: u16) Error!void {
if (bits == 0) return;
var in_buffer = bufValue(value, 32);
var in_bits = bits;
// Store input bits in buffer if they fit otherwise store as many as possible and flush
if (self.bit_count > 0) {
const bits_remaining = 31 - self.bit_count + 1;
const n: u5 = @intCast(@min(bits_remaining, in_bits));
const v = @as(u32, @truncate(in_buffer)) << self.bit_count;
self.bit_buffer |= v;
in_buffer >>= n;
self.bit_count +%= n;
in_bits -= n;
if (self.bit_count != 0) return;
try self.buffer.append(std.mem.nativeToLittle(u32, self.bit_buffer));
self.bit_buffer = 0;
}
// Write 32-bit chunks of input bits
while (in_bits >= 32) {
try self.buffer.append(std.mem.nativeToLittle(u32, @truncate(in_buffer)));
in_buffer >>= 31;
in_buffer >>= 1;
in_bits -= 32;
}
// Store remaining input bits in buffer
if (in_bits > 0) {
self.bit_count = @intCast(in_bits);
self.bit_buffer = @truncate(in_buffer);
}
}