From 57e8698ef2b070833e3d324aacedc574b722239b Mon Sep 17 00:00:00 2001 From: Ron Kuris Date: Fri, 15 Dec 2023 10:50:06 -0800 Subject: [PATCH] Add nibbles_into_bytes for an arbitrary iterator (#435) Co-authored-by: Richard Pringle --- firewood/src/merkle/stream.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/firewood/src/merkle/stream.rs b/firewood/src/merkle/stream.rs index 4186d7e22..5a8fdc430 100644 --- a/firewood/src/merkle/stream.rs +++ b/firewood/src/merkle/stream.rs @@ -287,11 +287,27 @@ fn key_from_parents_and_leaf(parents: &[(ObjRef, u8)], leaf: &LeafNode) -> Vec { + fn nibbles_into_bytes(&mut self) -> Vec { + 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> 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; @@ -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![]); + } }