Skip to content

Commit 97e5de0

Browse files
Johannes Ballécopybara-github
authored andcommitted
Small fix for potential off-by-one error in bit coder.
PiperOrigin-RevId: 471584417 Change-Id: I9d0a37ec723daf800f8031e389ddad7e83b7102a
1 parent 60b1db8 commit 97e5de0

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

tensorflow_compression/cc/lib/bit_coder.cc

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ limitations under the License.
1818
#include <cassert>
1919
#include <cstddef>
2020
#include <cstdint>
21+
#include <limits>
2122

2223
#include "absl/base/internal/endian.h"
2324
#include "absl/status/status.h"
@@ -26,13 +27,16 @@ namespace tensorflow_compression {
2627

2728
BitWriter::BitWriter(size_t maximum_bit_size)
2829
// We write 8 bytes at a time, so we might over-write by 8 bytes.
29-
: data_(std::make_unique<char[]>(maximum_bit_size / 8 + 8)),
30+
// +1 byte since we need to round bits *up* to bytes.
31+
: data_(std::make_unique<char[]>(maximum_bit_size / 8 + 9)),
3032
next_byte_(data_.get()),
3133
bits_in_buffer_(0),
3234
buffer_(0) {}
3335

3436
void BitWriter::WriteBits(uint32_t count, uint64_t bits) {
35-
assert(count <= kMaxBitsPerCall); // Max remaining room in buffer.
37+
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)));
3640
buffer_ |= bits << bits_in_buffer_;
3741
bits_in_buffer_ += count;
3842
absl::little_endian::Store64(next_byte_, buffer_);

0 commit comments

Comments
 (0)