Skip to content

Commit

Permalink
fix: varint_read_u64 panics on unwrap in no_std environment (#145)
Browse files Browse the repository at this point in the history
The goal of this pull request is to refactor `unwrap()` to return the `u64` value or an`Error:VarIntDecodeError` in the `no_std` environment.

This error was discovered in fuzz testing.

Tests were refactored to include a new `no_std_tests` module, in order to test the fix. 
`cargo test --no-default-features` will execute the `no_std` test.
  • Loading branch information
mattheworris authored Oct 17, 2023
1 parent 7427a7b commit 86c7912
Show file tree
Hide file tree
Showing 4 changed files with 207 additions and 177 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ You can also run this example from this checkout with `cargo run --example readm

You can run the tests using this command: `cargo test --all-features`

You can run the tests for `no_std` using this command: `cargo test --no-default-features`

## Maintainers

Captain: [@dignifiedquire](https://github.com/dignifiedquire).
Expand Down
16 changes: 10 additions & 6 deletions examples/readme.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use cid::Cid;
use multihash_codetable::{Code, MultihashDigest};
use std::convert::TryFrom;

const RAW: u64 = 0x55;

#[cfg(feature = "std")]
fn main() {
use cid::Cid;
use multihash_codetable::{Code, MultihashDigest};

const RAW: u64 = 0x55;
let h = Code::Sha2_256.digest(b"beep boop");

let cid = Cid::new_v1(RAW, h);
Expand All @@ -21,3 +20,8 @@ fn main() {
);
println!("{}", cid_string);
}
#[cfg(not(feature = "std"))]
// cargo test --no-default-features complains without this
fn main() {
print!("no_std");
}
5 changes: 4 additions & 1 deletion src/cid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ pub(crate) fn varint_read_u64<R: io::Read>(mut r: R) -> Result<u64> {
if n == 0 {
return Err(Error::VarIntDecodeError);
} else if decode::is_last(b[i]) {
return Ok(decode::u64(&b[..=i]).unwrap().0);
match decode::u64(&b[..=i]) {
Ok((value, _)) => return Ok(value),
Err(_) => return Err(Error::VarIntDecodeError),
}
}
}
Err(Error::VarIntDecodeError)
Expand Down
Loading

0 comments on commit 86c7912

Please sign in to comment.