Skip to content

Commit

Permalink
Add saturating add for Varint
Browse files Browse the repository at this point in the history
  • Loading branch information
divagant-martian committed Nov 21, 2024
1 parent fe5fc25 commit 2071a7c
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions quinn-proto/src/varint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ impl VarInt {
self.0
}

/// Saturating integer addition. Computes self + rhs, saturating at the numeric bounds instead
/// of overflowing.
pub fn saturating_add(self, rhs: impl Into<Self>) -> Self {
let rhs = rhs.into();
let inner = self.0.saturating_add(rhs.0).min(Self::MAX.0);
Self(inner)
}

/// Compute the number of bytes needed to encode this value
pub(crate) const fn size(self) -> usize {
let x = self.0;
Expand Down Expand Up @@ -191,3 +199,19 @@ impl Codec for VarInt {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_saturating_add() {
// add within range behaves normally
let large: VarInt = u32::MAX.into();
let next = u64::from(u32::MAX) + 1;
assert_eq!(large.saturating_add(1u8), VarInt::from_u64(next).unwrap());

// outside range saturates
assert_eq!(VarInt::MAX.saturating_add(1u8), VarInt::MAX)
}
}

0 comments on commit 2071a7c

Please sign in to comment.