Skip to content

Commit 35019bc

Browse files
authored
const-oid: elimiate arithmetic side effects in arc encoder (#1598)
Ensures overflow will always cause a panic instead
1 parent ae85809 commit 35019bc

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

const-oid/src/encoder.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ 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)]
5455
pub(crate) const fn arc(mut self, arc: Arc) -> Result<Self> {
5556
match self.state {
5657
State::Initial => {
@@ -61,15 +62,24 @@ impl<const MAX_SIZE: usize> Encoder<MAX_SIZE> {
6162
self.state = State::FirstArc(arc);
6263
Ok(self)
6364
}
64-
// Ensured not to overflow by `ARC_MAX_SECOND` check
65-
#[allow(clippy::arithmetic_side_effects)]
6665
State::FirstArc(first_arc) => {
6766
if arc > ARC_MAX_SECOND {
6867
return Err(Error::ArcInvalid { arc });
6968
}
7069

7170
self.state = State::Body;
72-
self.bytes[0] = (first_arc * (ARC_MAX_SECOND + 1)) as u8 + arc as u8;
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+
};
7383
self.cursor = 1;
7484
Ok(self)
7585
}

const-oid/src/parser.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ impl Parser {
5959
None => 0,
6060
};
6161

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

0 commit comments

Comments
 (0)