Skip to content

Instantly share code, notes, and snippets.

@mexus
Last active May 31, 2018 00:34
Show Gist options
  • Save mexus/cb8907fc6c29dd6832596bd01f3e467a to your computer and use it in GitHub Desktop.
Save mexus/cb8907fc6c29dd6832596bd01f3e467a to your computer and use it in GitHub Desktop.
extern crate bincode;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use rand::distributions::{Alphanumeric, Uniform};
use rand::prelude::*;
use std::fs::File;
use std::iter;
use std::time::Instant;
#[derive(Debug, Serialize, Deserialize)]
struct Node1 {
node1_field: String,
children: Vec<Tree>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Node2 {
node2_field: String,
children: Vec<Tree>,
}
#[derive(Debug, Serialize, Deserialize)]
enum Tree {
Node1(Node1),
Node2(Node2),
}
impl Tree {
fn get_children(&self) -> impl Iterator<Item = &Tree> {
match self {
Tree::Node1(Node1 { children, .. }) | Tree::Node2(Node2 { children, .. }) => {
children.iter()
}
}
}
}
fn generate<R: Rng>(rng: &mut R, level: usize) -> Tree {
let children = if level == 20 {
vec![]
} else {
iter::repeat(0)
.take(rng.sample(Uniform::new(0, 5)))
.map(|_| generate(rng, level + 1))
.collect()
};
let name = rng.sample_iter(&Alphanumeric).take(4).collect();
if rng.gen() {
Tree::Node1(Node1 {
node1_field: name,
children,
})
} else {
Tree::Node2(Node2 {
node2_field: name,
children,
})
}
}
fn count_nodes(node: &Tree) -> usize {
1 + node.get_children().map(count_nodes).sum::<usize>()
}
fn main() {
let mut rng = SmallRng::from_entropy();
let begin = Instant::now();
let tree = generate(&mut rng, 0);
println!("Generated in {:?}", Instant::now().duration_since(begin));
let begin = Instant::now();
let total_nodes = count_nodes(&tree);
println!(
"Total {} nodes, traversed in {:?}",
total_nodes,
Instant::now().duration_since(begin)
);
let file_name = "dump.bincode";
let begin = Instant::now();
bincode::serialize_into(File::create(file_name).unwrap(), &tree).unwrap();
println!("Serialized in {:?}", Instant::now().duration_since(begin));
let begin = Instant::now();
let _: Tree = bincode::deserialize_from(File::open(file_name).unwrap()).unwrap();
println!("Deserialized in {:?}", Instant::now().duration_since(begin));
}
// Sample execution:
// % cargo run --release
// ...
// Generated in 280.744041ms
// Total 3792133 nodes, traversed in 23.91291ms
// Serialized in 12.840281246s
// Deserialized in 5.846506544s
// ...
// % l dump.bincode
// -rw-r--r-- 1 mexus mexus 87M May 31 02:30 dump.bincode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment