Skip to content

Commit

Permalink
Add nibbles_into_bytes for an arbitrary iterator (#435)
Browse files Browse the repository at this point in the history
Co-authored-by: Richard Pringle <[email protected]>
  • Loading branch information
rkuris and richardpringle authored Dec 15, 2023
1 parent dd65b11 commit 57e8698
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions firewood/src/merkle/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,11 +287,27 @@ fn key_from_parents_and_leaf(parents: &[(ObjRef, u8)], leaf: &LeafNode) -> Vec<u
data
}

// CAUTION: only use with nibble iterators
trait IntoBytes: Iterator<Item = u8> {
fn nibbles_into_bytes(&mut self) -> Vec<u8> {
let mut data = Vec::with_capacity(self.size_hint().0 / 2);

while let (Some(hi), Some(lo)) = (self.next(), self.next()) {
data.push((hi << 4) + lo);
}

data
}
}
impl<T: Iterator<Item = u8>> IntoBytes for T {}

#[cfg(test)]
use super::tests::create_test_merkle;

#[cfg(test)]
mod tests {
use crate::nibbles::Nibbles;

use super::*;
use futures::StreamExt;
use test_case::test_case;
Expand Down Expand Up @@ -412,4 +428,21 @@ mod tests {

assert!(done.is_none());
}

#[test]
fn remaining_bytes() {
let data = &[1];
let nib: Nibbles<'_, 0> = Nibbles::<0>::new(data);
let mut it = nib.into_iter();
assert_eq!(it.nibbles_into_bytes(), data.to_vec());
}

#[test]
fn remaining_bytes_off() {
let data = &[1];
let nib: Nibbles<'_, 0> = Nibbles::<0>::new(data);
let mut it = nib.into_iter();
it.next();
assert_eq!(it.nibbles_into_bytes(), vec![]);
}
}

0 comments on commit 57e8698

Please sign in to comment.