Skip to content

Commit ae85809

Browse files
authored
const-oid: eliminate split_high_bits side effects (#1597)
Prefer panicking instead so underflow bugs aren't silent
1 parent bbb0663 commit ae85809

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

const-oid/src/encoder.rs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -126,21 +126,29 @@ const fn base128_len(arc: Arc) -> usize {
126126
/// Split the highest 7-bits of an [`Arc`] from the rest of an arc.
127127
///
128128
/// Returns: `(hi, lo)`
129-
// TODO(tarcieri): always use checked arithmetic
130-
#[allow(clippy::arithmetic_side_effects)]
129+
#[inline]
131130
const fn split_high_bits(arc: Arc) -> (u8, Arc) {
132131
if arc < 0x80 {
133132
return (arc as u8, 0);
134133
}
135134

136-
let hi_bit = 32 - arc.leading_zeros();
135+
let hi_bit = match 32u32.checked_sub(arc.leading_zeros()) {
136+
Some(bit) => bit,
137+
None => unreachable!(),
138+
};
139+
137140
let hi_bit_mod7 = hi_bit % 7;
138-
let upper_bit_pos = hi_bit
139-
- if hi_bit > 0 && hi_bit_mod7 == 0 {
140-
7
141-
} else {
142-
hi_bit_mod7
143-
};
141+
let upper_bit_offset = if hi_bit > 0 && hi_bit_mod7 == 0 {
142+
7
143+
} else {
144+
hi_bit_mod7
145+
};
146+
147+
let upper_bit_pos = match hi_bit.checked_sub(upper_bit_offset) {
148+
Some(bit) => bit,
149+
None => unreachable!(),
150+
};
151+
144152
let upper_bits = arc >> upper_bit_pos;
145153
let lower_bits = arc ^ (upper_bits << upper_bit_pos);
146154
(upper_bits as u8, lower_bits)

0 commit comments

Comments
 (0)