Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

const-oid: replace panics with checked_*! macros #1601

Merged
merged 1 commit into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading