Skip to content

Commit c3445fc

Browse files
authored
fix: don't panic on non minimal varints (#293)
If a varint it non-minimally encoded in a no_std environment, don't panic, but return an error. Also some minor Clippy warnings were fixed. Fixes #282.
1 parent f015e0a commit c3445fc

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/multihash.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,8 @@ impl<const S: usize> Multihash<S> {
247247
}
248248

249249
// Don't hash the whole allocated space, but just the actual digest
250-
#[allow(clippy::derive_hash_xor_eq)]
250+
#[allow(unknown_lints, renamed_and_removed_lints)]
251+
#[allow(clippy::derived_hash_with_manual_eq, clippy::derive_hash_xor_eq)]
251252
impl<const S: usize> core::hash::Hash for Multihash<S> {
252253
fn hash<T: core::hash::Hasher>(&self, state: &mut T) {
253254
self.code.hash(state);
@@ -362,7 +363,9 @@ pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> {
362363
if n == 0 {
363364
return Err(Error::Varint(decode::Error::Insufficient));
364365
} else if decode::is_last(b[i]) {
365-
return Ok(decode::u64(&b[..=i]).unwrap().0);
366+
return decode::u64(&b[..=i])
367+
.map(|decoded| decoded.0)
368+
.map_err(Error::Varint);
366369
}
367370
}
368371
Err(Error::Varint(decode::Error::Overflow))
@@ -452,4 +455,12 @@ mod tests {
452455
let mh2 = Multihash::<64>::default();
453456
assert_eq!(mh1, mh2);
454457
}
458+
459+
#[test]
460+
fn decode_non_minimal_error() {
461+
// This is a non-minimal varint.
462+
let data = [241, 0, 0, 0, 0, 0, 128, 132, 132, 132, 58];
463+
let result = read_u64(&data[..]);
464+
assert!(result.is_err());
465+
}
455466
}

tests/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ where
231231
H: Hasher + Default,
232232
{
233233
let digest = hex::decode(digest_str).unwrap();
234-
let expected_bytes = hex::decode(&format!("{}{}", prefix, digest_str)).unwrap();
234+
let expected_bytes = hex::decode(format!("{}{}", prefix, digest_str)).unwrap();
235235
let mut expected_cursor = Cursor::new(&expected_bytes);
236236
let multihash = code.digest(b"hello world");
237237

0 commit comments

Comments
 (0)