Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nibbles_into_bytes for an arbitrary iterator #435

Merged
merged 6 commits into from
Dec 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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![]);
}
}