From c8cb86b8fbb3fcc73e6f38bfb84e9cf115ed6377 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Thu, 14 Jun 2018 21:22:49 +0200 Subject: [PATCH] bit_reader_c: fix `get_bit_position/get_remaining_bits` for empty buffers One side affect of the fixed bug was that trying to identify/mux an empty file (file with a size of 0) resulted in the following error message: > Error: buffer_c: num > m_filled. Should not have happened. Please > file a bug report. --- src/common/bit_reader.h | 4 ++-- tests/unit/common/bit_reader.cpp | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/common/bit_reader.h b/src/common/bit_reader.h index 7bc4ab391..dd9ddfef9 100644 --- a/src/common/bit_reader.h +++ b/src/common/bit_reader.h @@ -194,11 +194,11 @@ public: } int get_bit_position() const { - return (m_byte_position - m_start_of_data) * 8 + 8 - m_bits_valid; + return (m_byte_position - m_start_of_data) * 8 + (m_bits_valid ? 8 - m_bits_valid : 0); } int get_remaining_bits() const { - return (m_end_of_data - m_byte_position) * 8 - 8 + m_bits_valid; + return (m_end_of_data - m_byte_position) * 8 - (m_bits_valid ? 8 - m_bits_valid : 0); } void skip_bits(std::size_t num) { diff --git a/tests/unit/common/bit_reader.cpp b/tests/unit/common/bit_reader.cpp index 82a6f1a15..e20675f10 100644 --- a/tests/unit/common/bit_reader.cpp +++ b/tests/unit/common/bit_reader.cpp @@ -20,6 +20,15 @@ TEST(BitReader, Initialization) { EXPECT_FALSE(b.eof()); } +TEST(BitReader, InitializationEmpty) { + unsigned char value{}; + auto b = mtx::bits::reader_c{&value, 0}; + + EXPECT_EQ(0, b.get_bit_position()); + EXPECT_EQ(0, b.get_remaining_bits()); + EXPECT_TRUE(b.eof()); +} + TEST(BitReader, GetBit) { unsigned char value[4]; put_uint32_be(value, 0xf7234a81);