Skip to content

Commit

Permalink
const-oid: elimiate arithmetic side effects in arc encoder (#1598)
Browse files Browse the repository at this point in the history
Ensures overflow will always cause a panic instead
  • Loading branch information
tarcieri authored Nov 2, 2024
1 parent ae85809 commit 35019bc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
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

0 comments on commit 35019bc

Please sign in to comment.