Skip to content

Commit 154bcd4

Browse files
committed
Avoid >> above type width in BitWriter
1 parent 67b87ac commit 154bcd4

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/int_utils.h

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,10 @@ class BitWriter {
5555
int offset = 0;
5656
unsigned char* out;
5757

58-
public:
59-
BitWriter(unsigned char* output) : out(output) {}
60-
6158
template<int BITS, typename I>
62-
inline void Write(I val) {
59+
inline void WriteInner(I val) {
60+
// We right shift by up to 8 bits below. Verify that's well defined for the type I.
61+
static_assert(std::numeric_limits<I>::digits > 8, "BitWriter::WriteInner needs I > 8 bits");
6362
int bits = BITS;
6463
if (bits + offset >= 8) {
6564
state |= ((val & ((I(1) << (8 - offset)) - 1)) << offset);
@@ -78,6 +77,19 @@ class BitWriter {
7877
offset += bits;
7978
}
8079

80+
81+
public:
82+
BitWriter(unsigned char* output) : out(output) {}
83+
84+
template<int BITS, typename I>
85+
inline void Write(I val) {
86+
// If I is smaller than an unsigned int, invoke WriteInner with argument converted to unsigned.
87+
using compute_type = typename std::conditional<
88+
(std::numeric_limits<I>::digits < std::numeric_limits<unsigned>::digits),
89+
unsigned, I>::type;
90+
return WriteInner<BITS, compute_type>(val);
91+
}
92+
8193
inline void Flush() {
8294
if (offset) {
8395
*(out++) = state;

0 commit comments

Comments
 (0)