cargo fmt
This commit is contained in:
parent
5e1a2f9d3f
commit
46e88a5e69
|
@ -135,8 +135,8 @@ fn load_nodes(bytes: &'static [u8]) -> Vec<NodeData> {
|
|||
let mut res = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(bytes);
|
||||
while (cursor.position() as usize) < bytes.len() {
|
||||
let node_data =
|
||||
zcash_history::NodeData::read(0, &mut cursor).expect("Statically checked to be correct");
|
||||
let node_data = zcash_history::NodeData::read(0, &mut cursor)
|
||||
.expect("Statically checked to be correct");
|
||||
res.push(node_data);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,2 @@
|
|||
// dummy example
|
||||
pub fn main() {
|
||||
|
||||
}
|
||||
pub fn main() {}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use zcash_history:: {NodeData, Tree, Entry, EntryLink};
|
||||
use zcash_history::{Entry, EntryLink, NodeData, Tree};
|
||||
|
||||
pub struct NodeDataIterator {
|
||||
return_stack: Vec<NodeData>,
|
||||
|
@ -22,11 +22,20 @@ impl Iterator for NodeDataIterator {
|
|||
} else if self.return_stack.len() > 0 {
|
||||
self.return_stack.pop()
|
||||
} else {
|
||||
for n_append in
|
||||
self.tree.append_leaf(leaf(self.leaf_cursor as u32))
|
||||
.expect("full tree cannot fail").into_iter().rev()
|
||||
for n_append in self
|
||||
.tree
|
||||
.append_leaf(leaf(self.leaf_cursor as u32))
|
||||
.expect("full tree cannot fail")
|
||||
.into_iter()
|
||||
.rev()
|
||||
{
|
||||
self.return_stack.push(self.tree.resolve_link(n_append).expect("just pushed").data().clone())
|
||||
self.return_stack.push(
|
||||
self.tree
|
||||
.resolve_link(n_append)
|
||||
.expect("just pushed")
|
||||
.data()
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
self.leaf_cursor += 1;
|
||||
self.return_stack.pop()
|
||||
|
@ -42,14 +51,13 @@ impl NodeDataIterator {
|
|||
let root = Entry::new(
|
||||
NodeData::combine(&leaf(1), &leaf(2)),
|
||||
EntryLink::Stored(0),
|
||||
EntryLink::Stored(1)
|
||||
EntryLink::Stored(1),
|
||||
);
|
||||
let tree = Tree::new(
|
||||
3,
|
||||
vec![(2, root)],
|
||||
vec![(0, leaf(1).into()), (1, leaf(2).into())],
|
||||
);
|
||||
let tree =
|
||||
Tree::new(
|
||||
3,
|
||||
vec![(2, root)],
|
||||
vec![(0, leaf(1).into()), (1, leaf(2).into())]
|
||||
);
|
||||
|
||||
NodeDataIterator {
|
||||
return_stack: Vec::new(),
|
||||
|
@ -64,10 +72,10 @@ fn leaf(height: u32) -> NodeData {
|
|||
NodeData {
|
||||
consensus_branch_id: 0,
|
||||
subtree_commitment: [0u8; 32],
|
||||
start_time: height*10+1,
|
||||
end_time: (height+1)*10,
|
||||
start_target: 100 + height*10,
|
||||
end_target: 100 + (height+1)*10,
|
||||
start_time: height * 10 + 1,
|
||||
end_time: (height + 1) * 10,
|
||||
start_target: 100 + height * 10,
|
||||
end_target: 100 + (height + 1) * 10,
|
||||
start_sapling_root: [0u8; 32],
|
||||
end_sapling_root: [0u8; 32],
|
||||
subtree_total_work: 0.into(),
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
use zcash_history::{Entry, EntryLink, NodeData, Tree};
|
||||
|
||||
#[path= "lib/shared.rs"]
|
||||
#[path = "lib/shared.rs"]
|
||||
mod share;
|
||||
|
||||
fn draft(into: &mut Vec<(u32, Entry)>, vec: &Vec<NodeData>, peak_pos: usize, h: u32) {
|
||||
let node_data = vec[peak_pos-1].clone();
|
||||
let node_data = vec[peak_pos - 1].clone();
|
||||
let peak: Entry = match h {
|
||||
0 => node_data.into(),
|
||||
_ => Entry::new(
|
||||
|
@ -16,16 +16,15 @@ fn draft(into: &mut Vec<(u32, Entry)>, vec: &Vec<NodeData>, peak_pos: usize, h:
|
|||
|
||||
println!("Entry #{}: {}", into.len(), peak);
|
||||
|
||||
into.push(((peak_pos-1) as u32, peak));
|
||||
into.push(((peak_pos - 1) as u32, peak));
|
||||
}
|
||||
|
||||
fn prepare_tree(vec: &Vec<NodeData>) -> Tree {
|
||||
|
||||
assert!(vec.len() > 0);
|
||||
|
||||
// integer log2 of (vec.len()+1), -1
|
||||
let mut h = (32 - ((vec.len()+1) as u32).leading_zeros() - 1)-1;
|
||||
let mut peak_pos = (1 << (h+1)) - 1;
|
||||
let mut h = (32 - ((vec.len() + 1) as u32).leading_zeros() - 1) - 1;
|
||||
let mut peak_pos = (1 << (h + 1)) - 1;
|
||||
let mut nodes = Vec::new();
|
||||
|
||||
// used later
|
||||
|
@ -33,10 +32,9 @@ fn prepare_tree(vec: &Vec<NodeData>) -> Tree {
|
|||
let mut last_peak_h = 0;
|
||||
|
||||
loop {
|
||||
|
||||
if peak_pos > vec.len() {
|
||||
// left child, -2^h
|
||||
peak_pos = peak_pos - (1<<h);
|
||||
peak_pos = peak_pos - (1 << h);
|
||||
h = h - 1;
|
||||
}
|
||||
|
||||
|
@ -48,7 +46,7 @@ fn prepare_tree(vec: &Vec<NodeData>) -> Tree {
|
|||
last_peak_h = h;
|
||||
|
||||
// right sibling
|
||||
peak_pos = peak_pos + (1 << (h+1)) - 1;
|
||||
peak_pos = peak_pos + (1 << (h + 1)) - 1;
|
||||
}
|
||||
|
||||
if h == 0 {
|
||||
|
@ -62,7 +60,7 @@ fn prepare_tree(vec: &Vec<NodeData>) -> Tree {
|
|||
let mut peak_pos = last_peak_pos;
|
||||
|
||||
while h > 0 {
|
||||
let left_pos = peak_pos - (1<<h);
|
||||
let left_pos = peak_pos - (1 << h);
|
||||
let right_pos = peak_pos - 1;
|
||||
h = h - 1;
|
||||
|
||||
|
@ -82,14 +80,16 @@ fn prepare_tree(vec: &Vec<NodeData>) -> Tree {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
let number= match std::env::args().skip(1).next() {
|
||||
None => { eprintln!("writer <number of nodes> [<out_file>]"); std::process::exit(1); },
|
||||
Some(number) => {
|
||||
number.parse::<usize>().expect("invalid number")
|
||||
let number = match std::env::args().skip(1).next() {
|
||||
None => {
|
||||
eprintln!("writer <number of nodes> [<out_file>]");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Some(number) => number.parse::<usize>().expect("invalid number"),
|
||||
};
|
||||
|
||||
let long_vec = share::NodeDataIterator::new().take(number)
|
||||
let long_vec = share::NodeDataIterator::new()
|
||||
.take(number)
|
||||
.collect::<Vec<NodeData>>();
|
||||
|
||||
let now = std::time::Instant::now();
|
||||
|
@ -97,13 +97,17 @@ fn main() {
|
|||
let tree = prepare_tree(&long_vec);
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
println!("Tree final root: {}-{}",
|
||||
println!(
|
||||
"Tree final root: {}-{}",
|
||||
tree.root_node().expect("root").data().start_height,
|
||||
tree.root_node().expect("root").data().end_height,
|
||||
);
|
||||
|
||||
println!("Prepare tree of {} length: {} ns / {} mcs / {} ms",
|
||||
println!(
|
||||
"Prepare tree of {} length: {} ns / {} mcs / {} ms",
|
||||
number,
|
||||
elapsed.as_nanos(), elapsed.as_micros(), elapsed.as_millis()
|
||||
elapsed.as_nanos(),
|
||||
elapsed.as_micros(),
|
||||
elapsed.as_millis()
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
#[path= "lib/shared.rs"]
|
||||
#[path = "lib/shared.rs"]
|
||||
mod share;
|
||||
|
||||
// Test data generator
|
||||
|
@ -11,10 +11,14 @@ fn main() {
|
|||
let mut args = std::env::args().skip(1);
|
||||
|
||||
let (number, out_file) = match args.next() {
|
||||
None => { eprintln!("writer <number of nodes> [<out_file>]"); std::process::exit(1); },
|
||||
Some(number) => {
|
||||
(number.parse::<usize>().expect("invalid number"), args.next())
|
||||
None => {
|
||||
eprintln!("writer <number of nodes> [<out_file>]");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Some(number) => (
|
||||
number.parse::<usize>().expect("invalid number"),
|
||||
args.next(),
|
||||
),
|
||||
};
|
||||
|
||||
let iterator = share::NodeDataIterator::new().take(number);
|
||||
|
@ -24,12 +28,11 @@ fn main() {
|
|||
|
||||
let mut buf = Vec::new();
|
||||
|
||||
for node in iterator{
|
||||
for node in iterator {
|
||||
node.write(&mut buf).expect("Failed to write data");
|
||||
}
|
||||
|
||||
let mut file = std::fs::File::create(&out_file_path)
|
||||
.expect("Failed to create output file");
|
||||
let mut file = std::fs::File::create(&out_file_path).expect("Failed to create output file");
|
||||
|
||||
file.write_all(&buf[..])
|
||||
.expect("Failed to write data to file");
|
||||
|
@ -38,4 +41,4 @@ fn main() {
|
|||
println!("{:?}", n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||
|
||||
use crate::{EntryKind, NodeData, Error, EntryLink, MAX_NODE_DATA_SIZE};
|
||||
use crate::{EntryKind, EntryLink, Error, NodeData, MAX_NODE_DATA_SIZE};
|
||||
|
||||
/// Max serialized length of entry data.
|
||||
pub const MAX_ENTRY_SIZE: usize = MAX_NODE_DATA_SIZE + 9;
|
||||
|
@ -34,22 +34,26 @@ impl Entry {
|
|||
|
||||
/// Is this node a leaf.
|
||||
pub fn leaf(&self) -> bool {
|
||||
if let EntryKind::Leaf = self.kind { true } else { false }
|
||||
if let EntryKind::Leaf = self.kind {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Left child
|
||||
pub fn left(&self) -> Result<EntryLink, Error> {
|
||||
match self.kind {
|
||||
EntryKind::Leaf => { Err(Error::node_expected()) }
|
||||
EntryKind::Node(left, _) => Ok(left)
|
||||
EntryKind::Leaf => Err(Error::node_expected()),
|
||||
EntryKind::Node(left, _) => Ok(left),
|
||||
}
|
||||
}
|
||||
|
||||
/// Right child.
|
||||
pub fn right(&self) -> Result<EntryLink, Error> {
|
||||
match self.kind {
|
||||
EntryKind::Leaf => { Err(Error::node_expected()) }
|
||||
EntryKind::Node(_, right) => Ok(right)
|
||||
EntryKind::Leaf => Err(Error::node_expected()),
|
||||
EntryKind::Node(_, right) => Ok(right),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -61,22 +65,15 @@ impl Entry {
|
|||
let left = r.read_u32::<LittleEndian>()?;
|
||||
let right = r.read_u32::<LittleEndian>()?;
|
||||
EntryKind::Node(EntryLink::Stored(left), EntryLink::Stored(right))
|
||||
},
|
||||
1 => {
|
||||
EntryKind::Leaf
|
||||
},
|
||||
_ => {
|
||||
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData))
|
||||
},
|
||||
}
|
||||
1 => EntryKind::Leaf,
|
||||
_ => return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)),
|
||||
}
|
||||
};
|
||||
|
||||
let data = NodeData::read(consensus_branch_id, r)?;
|
||||
|
||||
Ok(Entry {
|
||||
kind,
|
||||
data,
|
||||
})
|
||||
Ok(Entry { kind, data })
|
||||
}
|
||||
|
||||
/// Write to byte representation.
|
||||
|
@ -86,11 +83,13 @@ impl Entry {
|
|||
w.write_u8(0)?;
|
||||
w.write_u32::<LittleEndian>(left)?;
|
||||
w.write_u32::<LittleEndian>(right)?;
|
||||
},
|
||||
}
|
||||
EntryKind::Leaf => {
|
||||
w.write_u8(1)?;
|
||||
},
|
||||
_ => { return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); }
|
||||
}
|
||||
_ => {
|
||||
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));
|
||||
}
|
||||
}
|
||||
|
||||
self.data.write(w)?;
|
||||
|
@ -107,7 +106,10 @@ impl Entry {
|
|||
|
||||
impl From<NodeData> for Entry {
|
||||
fn from(s: NodeData) -> Self {
|
||||
Entry { kind: EntryKind::Leaf, data: s }
|
||||
Entry {
|
||||
kind: EntryKind::Leaf,
|
||||
data: s,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -3,14 +3,13 @@
|
|||
//! To be used in zebra and via FFI bindings in zcashd
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod tree;
|
||||
mod node_data;
|
||||
mod entry;
|
||||
mod node_data;
|
||||
mod tree;
|
||||
|
||||
|
||||
pub use tree::Tree;
|
||||
pub use node_data::{NodeData, MAX_NODE_DATA_SIZE};
|
||||
pub use entry::{Entry, MAX_ENTRY_SIZE};
|
||||
pub use node_data::{NodeData, MAX_NODE_DATA_SIZE};
|
||||
pub use tree::Tree;
|
||||
|
||||
/// Crate-level error type
|
||||
#[derive(Debug)]
|
||||
|
@ -62,16 +61,19 @@ pub enum EntryKind {
|
|||
|
||||
impl Error {
|
||||
/// Entry expected to be a node (specifying for which link this is not true).
|
||||
pub fn link_node_expected(link: EntryLink) -> Self { Self::ExpectedNode(Some(link)) }
|
||||
pub fn link_node_expected(link: EntryLink) -> Self {
|
||||
Self::ExpectedNode(Some(link))
|
||||
}
|
||||
|
||||
/// Some entry is expected to be node
|
||||
pub fn node_expected() -> Self { Self::ExpectedNode(None) }
|
||||
pub fn node_expected() -> Self {
|
||||
Self::ExpectedNode(None)
|
||||
}
|
||||
|
||||
pub (crate) fn augment(self, link: EntryLink) -> Self {
|
||||
pub(crate) fn augment(self, link: EntryLink) -> Self {
|
||||
match self {
|
||||
Error::ExpectedNode(_) => Error::ExpectedNode(Some(link)),
|
||||
val => val
|
||||
val => val,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt, ByteOrder};
|
||||
use bigint::U256;
|
||||
use blake2::Params as Blake2Params;
|
||||
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||
|
||||
/// Maximum serialized size of the node metadata.
|
||||
pub const MAX_NODE_DATA_SIZE: usize =
|
||||
32 + // subtree commitment
|
||||
pub const MAX_NODE_DATA_SIZE: usize = 32 + // subtree commitment
|
||||
4 + // start time
|
||||
4 + // end time
|
||||
4 + // start target
|
||||
|
@ -14,8 +13,8 @@ pub const MAX_NODE_DATA_SIZE: usize =
|
|||
32 + // subtree total work
|
||||
9 + // start height (compact uint)
|
||||
9 + // end height (compact uint)
|
||||
9; // shielded tx count (compact uint)
|
||||
// = total of 171
|
||||
9; // shielded tx count (compact uint)
|
||||
// = total of 171
|
||||
|
||||
/// Node metadata.
|
||||
#[repr(C)]
|
||||
|
@ -75,14 +74,17 @@ impl NodeData {
|
|||
let mut hash_buf = [0u8; MAX_NODE_DATA_SIZE * 2];
|
||||
let size = {
|
||||
let mut cursor = ::std::io::Cursor::new(&mut hash_buf[..]);
|
||||
left.write(&mut cursor).expect("Writing to memory buf with enough length cannot fail; qed");
|
||||
right.write(&mut cursor).expect("Writing to memory buf with enough length cannot fail; qed");
|
||||
left.write(&mut cursor)
|
||||
.expect("Writing to memory buf with enough length cannot fail; qed");
|
||||
right
|
||||
.write(&mut cursor)
|
||||
.expect("Writing to memory buf with enough length cannot fail; qed");
|
||||
cursor.position() as usize
|
||||
};
|
||||
|
||||
let hash = blake2b_personal(
|
||||
&personalization(left.consensus_branch_id),
|
||||
&hash_buf[..size]
|
||||
&hash_buf[..size],
|
||||
);
|
||||
|
||||
NodeData {
|
||||
|
@ -103,17 +105,15 @@ impl NodeData {
|
|||
|
||||
fn write_compact<W: std::io::Write>(w: &mut W, compact: u64) -> std::io::Result<()> {
|
||||
match compact {
|
||||
0..=0xfc => {
|
||||
w.write_all(&[compact as u8])?
|
||||
},
|
||||
0..=0xfc => w.write_all(&[compact as u8])?,
|
||||
0xfd..=0xffff => {
|
||||
w.write_all(&[0xfd])?;
|
||||
w.write_u16::<LittleEndian>(compact as u16)?;
|
||||
},
|
||||
}
|
||||
0x10000..=0xffff_ffff => {
|
||||
w.write_all(&[0xfe])?;
|
||||
w.write_u32::<LittleEndian>(compact as u32)?;
|
||||
},
|
||||
}
|
||||
_ => {
|
||||
w.write_all(&[0xff])?;
|
||||
w.write_u64::<LittleEndian>(compact)?;
|
||||
|
@ -160,8 +160,8 @@ impl NodeData {
|
|||
r.read_exact(&mut data.subtree_commitment)?;
|
||||
data.start_time = r.read_u32::<LittleEndian>()?;
|
||||
data.end_time = r.read_u32::<LittleEndian>()?;
|
||||
data.start_target= r.read_u32::<LittleEndian>()?;
|
||||
data.end_target= r.read_u32::<LittleEndian>()?;
|
||||
data.start_target = r.read_u32::<LittleEndian>()?;
|
||||
data.end_target = r.read_u32::<LittleEndian>()?;
|
||||
r.read_exact(&mut data.start_sapling_root)?;
|
||||
r.read_exact(&mut data.end_sapling_root)?;
|
||||
|
||||
|
@ -230,10 +230,9 @@ mod tests {
|
|||
use super::NodeData;
|
||||
use quickcheck::{quickcheck, TestResult};
|
||||
|
||||
|
||||
quickcheck! {
|
||||
fn serialization_round_trip(node_data: NodeData) -> TestResult {
|
||||
TestResult::from_bool(NodeData::from_bytes(0, &node_data.to_bytes()).unwrap() == node_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use crate::{Entry, EntryLink, NodeData, Error, EntryKind};
|
||||
use crate::{Entry, EntryKind, EntryLink, Error, NodeData};
|
||||
|
||||
/// Represents partially loaded tree.
|
||||
///
|
||||
|
@ -28,15 +28,12 @@ pub struct Tree {
|
|||
impl Tree {
|
||||
/// Resolve link originated from this tree
|
||||
pub fn resolve_link(&self, link: EntryLink) -> Result<IndexedNode, Error> {
|
||||
match link {
|
||||
EntryLink::Generated(index) => self.generated.get(index as usize),
|
||||
EntryLink::Stored(index) => self.stored.get(&index),
|
||||
}
|
||||
.map(|node| IndexedNode {
|
||||
node,
|
||||
link,
|
||||
})
|
||||
.ok_or(Error::ExpectedInMemory(link))
|
||||
match link {
|
||||
EntryLink::Generated(index) => self.generated.get(index as usize),
|
||||
EntryLink::Stored(index) => self.stored.get(&index),
|
||||
}
|
||||
.map(|node| IndexedNode { node, link })
|
||||
.ok_or(Error::ExpectedInMemory(link))
|
||||
}
|
||||
|
||||
fn push(&mut self, data: Entry) -> EntryLink {
|
||||
|
@ -86,11 +83,7 @@ impl Tree {
|
|||
/// # Panics
|
||||
///
|
||||
/// Will panic if `peaks` is empty.
|
||||
pub fn new(
|
||||
length: u32,
|
||||
peaks: Vec<(u32, Entry)>,
|
||||
extra: Vec<(u32, Entry)>,
|
||||
) -> Self {
|
||||
pub fn new(length: u32, peaks: Vec<(u32, Entry)>, extra: Vec<(u32, Entry)>) -> Self {
|
||||
assert!(peaks.len() > 0);
|
||||
|
||||
let mut result = Tree::invalid();
|
||||
|
@ -102,11 +95,14 @@ impl Tree {
|
|||
for (idx, node) in peaks.into_iter() {
|
||||
result.stored.insert(idx, node);
|
||||
if gen != 0 {
|
||||
let next_generated =
|
||||
combine_nodes(result.
|
||||
resolve_link(root).expect("Inserted before, cannot fail; qed"),
|
||||
result.resolve_link(EntryLink::Stored(idx)).expect("Inserted before, cannot fail; qed")
|
||||
);
|
||||
let next_generated = combine_nodes(
|
||||
result
|
||||
.resolve_link(root)
|
||||
.expect("Inserted before, cannot fail; qed"),
|
||||
result
|
||||
.resolve_link(EntryLink::Stored(idx))
|
||||
.expect("Inserted before, cannot fail; qed"),
|
||||
);
|
||||
root = result.push_generated(next_generated);
|
||||
}
|
||||
gen += 1;
|
||||
|
@ -122,17 +118,13 @@ impl Tree {
|
|||
}
|
||||
|
||||
fn get_peaks(&self, root: EntryLink, target: &mut Vec<EntryLink>) -> Result<(), Error> {
|
||||
|
||||
let (left_child_link, right_child_link) = {
|
||||
let root = self.resolve_link(root)?;
|
||||
if root.node.complete() {
|
||||
target.push(root.link);
|
||||
return Ok(());
|
||||
}
|
||||
(
|
||||
root.left()?,
|
||||
root.right()?,
|
||||
)
|
||||
(root.left()?, root.right()?)
|
||||
};
|
||||
|
||||
self.get_peaks(left_child_link, target)?;
|
||||
|
@ -161,14 +153,18 @@ impl Tree {
|
|||
// complete subtrees. After this, merge_stack only contains peaks of
|
||||
// unequal-sized subtrees.
|
||||
while let Some(next_peak) = peaks.pop() {
|
||||
let next_merge = merge_stack.pop().expect("there should be at least one, initial or re-pushed");
|
||||
let next_merge = merge_stack
|
||||
.pop()
|
||||
.expect("there should be at least one, initial or re-pushed");
|
||||
|
||||
if let Some(stored) = {
|
||||
let peak = self.resolve_link(next_peak)?;
|
||||
let m = self.resolve_link(next_merge)?;
|
||||
if peak.node.leaf_count() == m.node.leaf_count() {
|
||||
Some(combine_nodes(peak, m))
|
||||
} else { None }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} {
|
||||
let link = self.push(stored);
|
||||
merge_stack.push(link);
|
||||
|
@ -180,16 +176,16 @@ impl Tree {
|
|||
}
|
||||
}
|
||||
|
||||
let mut new_root = merge_stack.pop().expect("Loop above cannot reduce the merge_stack");
|
||||
let mut new_root = merge_stack
|
||||
.pop()
|
||||
.expect("Loop above cannot reduce the merge_stack");
|
||||
// Scan the peaks left-to-right, producing new generated nodes that
|
||||
// connect the subtrees
|
||||
while let Some(next_child) = merge_stack.pop() {
|
||||
new_root = self.push_generated(
|
||||
combine_nodes(
|
||||
self.resolve_link(new_root)?,
|
||||
self.resolve_link(next_child)?,
|
||||
)
|
||||
)
|
||||
new_root = self.push_generated(combine_nodes(
|
||||
self.resolve_link(new_root)?,
|
||||
self.resolve_link(next_child)?,
|
||||
))
|
||||
}
|
||||
|
||||
self.root = new_root;
|
||||
|
@ -200,7 +196,9 @@ impl Tree {
|
|||
#[cfg(test)]
|
||||
fn for_children<F: Fn(EntryLink, EntryLink)>(&self, node: EntryLink, f: F) {
|
||||
let (left, right) = {
|
||||
let link = self.resolve_link(node).expect("Failed to resolve link in test");
|
||||
let link = self
|
||||
.resolve_link(node)
|
||||
.expect("Failed to resolve link in test");
|
||||
(
|
||||
link.left().expect("Failed to find node in test"),
|
||||
link.right().expect("Failed to find node in test"),
|
||||
|
@ -210,7 +208,7 @@ impl Tree {
|
|||
}
|
||||
|
||||
fn pop(&mut self) {
|
||||
self.stored.remove(&(self.stored_count-1));
|
||||
self.stored.remove(&(self.stored_count - 1));
|
||||
self.stored_count = self.stored_count - 1;
|
||||
}
|
||||
|
||||
|
@ -222,10 +220,7 @@ impl Tree {
|
|||
let root = {
|
||||
let (leaves, root_left_child) = {
|
||||
let n = self.resolve_link(self.root)?;
|
||||
(
|
||||
n.node.leaf_count(),
|
||||
n.node.left()?,
|
||||
)
|
||||
(n.node.leaf_count(), n.node.left()?)
|
||||
};
|
||||
if leaves & 1 != 0 {
|
||||
self.pop();
|
||||
|
@ -247,7 +242,9 @@ impl Tree {
|
|||
subtree_root_link = right;
|
||||
truncated += 1;
|
||||
} else {
|
||||
if root.node.complete() { truncated += 1; }
|
||||
if root.node.complete() {
|
||||
truncated += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -255,15 +252,15 @@ impl Tree {
|
|||
let mut new_root = *peaks.get(0).expect("At lest 1 elements in peaks");
|
||||
|
||||
for next_peak in peaks.into_iter().skip(1) {
|
||||
new_root = self.push_generated(
|
||||
combine_nodes(
|
||||
new_root = self.push_generated(combine_nodes(
|
||||
self.resolve_link(new_root)?,
|
||||
self.resolve_link(next_peak)?,
|
||||
)
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
for _ in 0..truncated { self.pop(); }
|
||||
for _ in 0..truncated {
|
||||
self.pop();
|
||||
}
|
||||
|
||||
self.root = new_root;
|
||||
|
||||
|
@ -276,7 +273,9 @@ impl Tree {
|
|||
}
|
||||
|
||||
/// Link to the root node
|
||||
pub fn root(&self) -> EntryLink { self.root }
|
||||
pub fn root(&self) -> EntryLink {
|
||||
self.root
|
||||
}
|
||||
|
||||
/// Reference to the root node.
|
||||
pub fn root_node(&self) -> Result<IndexedNode, Error> {
|
||||
|
@ -297,7 +296,6 @@ pub struct IndexedNode<'a> {
|
|||
}
|
||||
|
||||
impl<'a> IndexedNode<'a> {
|
||||
|
||||
fn left(&self) -> Result<EntryLink, Error> {
|
||||
self.node.left().map_err(|e| e.augment(self.link))
|
||||
}
|
||||
|
@ -332,9 +330,9 @@ fn combine_nodes<'a>(left: IndexedNode<'a>, right: IndexedNode<'a>) -> Entry {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::{Entry, NodeData, Tree, EntryLink, EntryKind};
|
||||
use quickcheck::{quickcheck, TestResult};
|
||||
use super::{Entry, EntryKind, EntryLink, NodeData, Tree};
|
||||
use assert_matches::assert_matches;
|
||||
use quickcheck::{quickcheck, TestResult};
|
||||
|
||||
fn leaf(height: u32) -> NodeData {
|
||||
NodeData {
|
||||
|
@ -370,7 +368,8 @@ mod tests {
|
|||
assert!(length >= 3);
|
||||
let mut tree = initial();
|
||||
for i in 2..length {
|
||||
tree.append_leaf(leaf(i+1).into()).expect("Failed to append");
|
||||
tree.append_leaf(leaf(i + 1).into())
|
||||
.expect("Failed to append");
|
||||
}
|
||||
|
||||
tree
|
||||
|
@ -381,9 +380,7 @@ mod tests {
|
|||
let mut tree = initial();
|
||||
|
||||
// ** APPEND 3 **
|
||||
let appended = tree
|
||||
.append_leaf(leaf(3))
|
||||
.expect("Failed to append");
|
||||
let appended = tree.append_leaf(leaf(3)).expect("Failed to append");
|
||||
let new_root = tree.root_node().expect("Failed to resolve root").node;
|
||||
|
||||
// initial tree: (2)
|
||||
|
@ -403,9 +400,7 @@ mod tests {
|
|||
assert_eq!(appended.len(), 1);
|
||||
|
||||
// ** APPEND 4 **
|
||||
let appended = tree
|
||||
.append_leaf(leaf(4))
|
||||
.expect("Failed to append");
|
||||
let appended = tree.append_leaf(leaf(4)).expect("Failed to append");
|
||||
|
||||
let new_root = tree.root_node().expect("Failed to resolve root").node;
|
||||
|
||||
|
@ -431,9 +426,7 @@ mod tests {
|
|||
|
||||
// ** APPEND 5 **
|
||||
|
||||
let appended = tree
|
||||
.append_leaf(leaf(5))
|
||||
.expect("Failed to append");
|
||||
let appended = tree.append_leaf(leaf(5)).expect("Failed to append");
|
||||
let new_root = tree.root_node().expect("Failed to resolve root").node;
|
||||
|
||||
// intermediate tree:
|
||||
|
@ -463,9 +456,7 @@ mod tests {
|
|||
});
|
||||
|
||||
// *** APPEND #6 ***
|
||||
let appended = tree
|
||||
.append_leaf(leaf(6))
|
||||
.expect("Failed to append");
|
||||
let appended = tree.append_leaf(leaf(6)).expect("Failed to append");
|
||||
let new_root = tree.root_node().expect("Failed to resolve root").node;
|
||||
|
||||
// intermediate tree:
|
||||
|
@ -498,13 +489,8 @@ mod tests {
|
|||
|
||||
// *** APPEND #7 ***
|
||||
|
||||
let appended = tree
|
||||
.append_leaf(leaf(7))
|
||||
.expect("Failed to append");
|
||||
let new_root = tree
|
||||
.root_node()
|
||||
.expect("Failed to resolve root")
|
||||
.node;
|
||||
let appended = tree.append_leaf(leaf(7)).expect("Failed to append");
|
||||
let new_root = tree.root_node().expect("Failed to resolve root").node;
|
||||
|
||||
// intermediate tree:
|
||||
// (---8g---)
|
||||
|
@ -533,9 +519,9 @@ mod tests {
|
|||
assert_matches!(tree.root(), EntryLink::Generated(_));
|
||||
tree.for_children(tree.root(), |l, r| {
|
||||
assert_matches!(l, EntryLink::Generated(_));
|
||||
tree.for_children(l, |l, r|
|
||||
tree.for_children(l, |l, r| {
|
||||
assert_matches!((l, r), (EntryLink::Stored(6), EntryLink::Stored(9)))
|
||||
);
|
||||
});
|
||||
assert_matches!(r, EntryLink::Stored(10));
|
||||
});
|
||||
}
|
||||
|
@ -606,12 +592,12 @@ mod tests {
|
|||
|
||||
assert_matches!(tree.root(), EntryLink::Generated(_));
|
||||
|
||||
tree.for_children(tree.root(),|left, right|
|
||||
tree.for_children(tree.root(), |left, right| {
|
||||
assert_matches!(
|
||||
(left, right),
|
||||
(EntryLink::Stored(14), EntryLink::Stored(15))
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
// two stored nodes should leave us (leaf 16 and no longer needed node 17)
|
||||
assert_eq!(deleted, 2);
|
||||
|
@ -625,7 +611,7 @@ mod tests {
|
|||
assert_eq!(tree.len(), 3);
|
||||
|
||||
for i in 0..2 {
|
||||
tree.append_leaf(leaf(i+3)).expect("Failed to append");
|
||||
tree.append_leaf(leaf(i + 3)).expect("Failed to append");
|
||||
}
|
||||
assert_eq!(tree.len(), 7);
|
||||
|
||||
|
@ -641,7 +627,7 @@ mod tests {
|
|||
assert_eq!(tree.len(), 3);
|
||||
|
||||
for i in 0..4094 {
|
||||
tree.append_leaf(leaf(i+3)).expect("Failed to append");
|
||||
tree.append_leaf(leaf(i + 3)).expect("Failed to append");
|
||||
}
|
||||
assert_eq!(tree.len(), 8191); // 4096*2-1 (full tree)
|
||||
|
||||
|
@ -652,7 +638,6 @@ mod tests {
|
|||
assert_eq!(tree.len(), 4083); // 4095 - log2(4096)
|
||||
}
|
||||
|
||||
|
||||
quickcheck! {
|
||||
fn there_and_back(number: u32) -> TestResult {
|
||||
if number > 1024*1024 {
|
||||
|
|
Loading…
Reference in New Issue