Skip to content

Commit

Permalink
fix: out-of-bound memory read on Nibbles::get_byte
Browse files Browse the repository at this point in the history
  • Loading branch information
rkrasiuk committed Feb 22, 2024
1 parent edca88d commit c1df87e
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/nibbles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,9 +397,13 @@ impl Nibbles {
/// assert_eq!(nibbles.get_byte(2), Some(0xCD));
/// assert_eq!(nibbles.get_byte(3), None);
/// ```
///
/// # Panics
///
/// If `i` equals to [usize::MAX] and next consecutive byte overflows.
#[inline]
pub fn get_byte(&self, i: usize) -> Option<u8> {
if i + 1 < self.len() {
if i.checked_add(1).expect("overflow") < self.len() {
Some(unsafe { self.get_byte_unchecked(i) })
} else {
None
Expand Down Expand Up @@ -737,6 +741,16 @@ mod tests {
assert_eq!(nibbles.len(), 0);
}

/// Test panic out-of-bound memory read.
/// This test only makes sense with no debug assertions in std environment.
#[cfg(all(feature = "std", not(debug_assertions)))]
#[test]
fn get_byte_max() {
let nibbles = Nibbles::from_nibbles_unchecked([0x0A, 0x0B, 0x0C, 0x0D]);
let result = std::panic::catch_unwind(|| nibbles.get_byte(usize::MAX));
assert!(result.is_err());
}

#[cfg(feature = "arbitrary")]
mod arbitrary {
use super::*;
Expand Down

0 comments on commit c1df87e

Please sign in to comment.