Skip to content

Commit

Permalink
const-oid: replace panics with checked_*! macros
Browse files Browse the repository at this point in the history
Returns `Error::Overflow` if any operations overflow
  • Loading branch information
tarcieri committed Nov 3, 2024
1 parent 1f55cdb commit d527de5
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
12 changes: 11 additions & 1 deletion const-oid/src/checked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ macro_rules! checked_add {
};
}

/// `const fn`-friendly checked addition helper.
/// `const fn`-friendly checked subtraction helper.
macro_rules! checked_sub {
($a:expr, $b:expr) => {
match $a.checked_sub($b) {
Expand All @@ -19,3 +19,13 @@ macro_rules! checked_sub {
}
};
}

/// `const fn`-friendly checked multiplication helper.
macro_rules! checked_mul {
($a:expr, $b:expr) => {
match $a.checked_mul($b) {
Some(n) => n,
None => return Err(Error::Overflow),
}
};
}
17 changes: 4 additions & 13 deletions const-oid/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ impl<const MAX_SIZE: usize> Encoder<MAX_SIZE> {
}

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

self.state = State::Body;
self.bytes[0] = match (ARC_MAX_SECOND + 1).checked_mul(first_arc) {
// TODO(tarcieri): use `and_then` when const traits are stable
Some(n) => match n.checked_add(arc) {
Some(byte) => byte as u8,
None => {
// TODO(tarcieri): use `unreachable!`
panic!("overflow prevented by ARC_MAX_SECOND check")
}
},
// TODO(tarcieri): use `unreachable!`
None => panic!("overflow prevented by ARC_MAX_SECOND check"),
};
self.bytes[0] = checked_add!(
checked_mul!(checked_add!(ARC_MAX_SECOND, 1), first_arc),
arc
) as u8;
self.cursor = 1;
Ok(self)
}
Expand Down
2 changes: 2 additions & 0 deletions const-oid/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub enum Error {
Length,

/// Arithmetic overflow (or underflow) errors.
///
/// These generally indicate a bug in the `const-oid` crate.
Overflow,

/// Repeated `..` characters in input data.
Expand Down

0 comments on commit d527de5

Please sign in to comment.