Skip to content

Commit 2f04080

Browse files
authored
const-oid: replace panics with checked_*! macros (#1601)
Returns `Error::Overflow` if any operations overflow
1 parent 1f55cdb commit 2f04080

File tree

3 files changed

+17
-14
lines changed

3 files changed

+17
-14
lines changed

const-oid/src/checked.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ macro_rules! checked_add {
1010
};
1111
}
1212

13-
/// `const fn`-friendly checked addition helper.
13+
/// `const fn`-friendly checked subtraction helper.
1414
macro_rules! checked_sub {
1515
($a:expr, $b:expr) => {
1616
match $a.checked_sub($b) {
@@ -19,3 +19,13 @@ macro_rules! checked_sub {
1919
}
2020
};
2121
}
22+
23+
/// `const fn`-friendly checked multiplication helper.
24+
macro_rules! checked_mul {
25+
($a:expr, $b:expr) => {
26+
match $a.checked_mul($b) {
27+
Some(n) => n,
28+
None => return Err(Error::Overflow),
29+
}
30+
};
31+
}

const-oid/src/encoder.rs

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ impl<const MAX_SIZE: usize> Encoder<MAX_SIZE> {
5151
}
5252

5353
/// Encode an [`Arc`] as base 128 into the internal buffer.
54-
#[allow(clippy::panic_in_result_fn)]
5554
pub(crate) const fn arc(mut self, arc: Arc) -> Result<Self> {
5655
match self.state {
5756
State::Initial => {
@@ -68,18 +67,10 @@ impl<const MAX_SIZE: usize> Encoder<MAX_SIZE> {
6867
}
6968

7069
self.state = State::Body;
71-
self.bytes[0] = match (ARC_MAX_SECOND + 1).checked_mul(first_arc) {
72-
// TODO(tarcieri): use `and_then` when const traits are stable
73-
Some(n) => match n.checked_add(arc) {
74-
Some(byte) => byte as u8,
75-
None => {
76-
// TODO(tarcieri): use `unreachable!`
77-
panic!("overflow prevented by ARC_MAX_SECOND check")
78-
}
79-
},
80-
// TODO(tarcieri): use `unreachable!`
81-
None => panic!("overflow prevented by ARC_MAX_SECOND check"),
82-
};
70+
self.bytes[0] = checked_add!(
71+
checked_mul!(checked_add!(ARC_MAX_SECOND, 1), first_arc),
72+
arc
73+
) as u8;
8374
self.cursor = 1;
8475
Ok(self)
8576
}

const-oid/src/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ pub enum Error {
3838
Length,
3939

4040
/// Arithmetic overflow (or underflow) errors.
41+
///
42+
/// These generally indicate a bug in the `const-oid` crate.
4143
Overflow,
4244

4345
/// Repeated `..` characters in input data.

0 commit comments

Comments
 (0)