Last active
August 31, 2024 00:04
-
-
Save LoZack19/d1e3354c783ed4b273b92ee67719dd5b to your computer and use it in GitHub Desktop.
Random ego-tree from reverse regex json deserialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Depends on: | |
// - rand | |
// - rand_regex | |
// - ego_tree | |
use std::{borrow::Borrow, cell::LazyCell}; | |
use ego_tree::Tree; | |
use rand::Rng; | |
use rand_regex::Regex; | |
fn json_node(depth: usize, value_repr: &str) -> String { | |
if depth == 0 { | |
format!("\\{{\"value\":({value_repr}),\"children\":\\[\\]\\}}") | |
} else { | |
let node = json_node(depth - 1, value_repr); | |
format!( | |
"\\{{\"value\":({value_repr}),\"children\":\\[((({}),)*({}))?\\]\\}}", | |
node, node, | |
) | |
} | |
} | |
fn sample_json_random_tree(depth: usize) -> String { | |
const VALUE: &str = "\"\\w+\""; | |
let json_tree_gen = LazyCell::new(|| Regex::compile(&json_node(depth, VALUE), 5).unwrap()); | |
rand::thread_rng().sample::<String, _>((*json_tree_gen).borrow()) | |
} | |
fn main() { | |
let rand_json_tree = sample_json_random_tree(10); | |
let rand_tree: Tree<String> = | |
serde_json::from_str(&rand_json_tree).expect("Failed to deserialize random tree"); | |
println!("{rand_tree}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment