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: elimiate arithmetic side effects in arc encoder #1598

Merged
merged 1 commit into from
Nov 2, 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
16 changes: 13 additions & 3 deletions const-oid/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ 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 @@ -61,15 +62,24 @@ impl<const MAX_SIZE: usize> Encoder<MAX_SIZE> {
self.state = State::FirstArc(arc);
Ok(self)
}
// Ensured not to overflow by `ARC_MAX_SECOND` check
#[allow(clippy::arithmetic_side_effects)]
State::FirstArc(first_arc) => {
if arc > ARC_MAX_SECOND {
return Err(Error::ArcInvalid { arc });
}

self.state = State::Body;
self.bytes[0] = (first_arc * (ARC_MAX_SECOND + 1)) as u8 + arc as u8;
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.cursor = 1;
Ok(self)
}
Expand Down
1 change: 1 addition & 0 deletions const-oid/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ impl Parser {
None => 0,
};

// TODO(tarcieri): use `and_then` when const traits are stable
self.current_arc = match arc.checked_mul(10) {
Some(arc) => match arc.checked_add(digit as Arc) {
None => return Err(Error::ArcTooBig),
Expand Down
Loading