Skip to content

Commit 5ffe063

Browse files
Johannes Ballécopybara-github
authored andcommitted
Makes WriteBits() safer by clearing unused bits rather than assuming zero.
PiperOrigin-RevId: 471852533 Change-Id: Ibd54692687b03591655967299150bf50ea99396d
1 parent 97e5de0 commit 5ffe063

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

tensorflow_compression/cc/lib/bit_coder.cc

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@ BitWriter::BitWriter(size_t maximum_bit_size)
3535

3636
void BitWriter::WriteBits(uint32_t count, uint64_t bits) {
3737
assert(count <= kMaxBitsPerCall);
38-
// This implementation relies on the unused MSBs in `bits` to be zero.
39-
assert(!(bits & (std::numeric_limits<uint64_t>::max() << count)));
38+
// This implementation assumes unwritten MSBs in the buffer are zero.
39+
// Clear the unused MSBs in bits first, then "or" it into the buffer.
40+
bits &= (uint64_t{1} << count) - 1;
4041
buffer_ |= bits << bits_in_buffer_;
4142
bits_in_buffer_ += count;
4243
absl::little_endian::Store64(next_byte_, buffer_);
@@ -54,7 +55,7 @@ void BitWriter::WriteGamma(int32_t value) {
5455
WriteBits(n - 1, 0);
5556
// Must write most significant bit first.
5657
WriteBits(1, 1);
57-
WriteBits(n - 1, value - (1 << (n - 1)));
58+
WriteBits(n - 1, value);
5859
}
5960

6061
absl::string_view BitWriter::GetData() {

0 commit comments

Comments
 (0)