Skip to content
Snippets Groups Projects
Unverified Commit a3825d3f authored by Cheuk Pui Lam's avatar Cheuk Pui Lam
Browse files

feat(logarithmic-brc): Implemented function to load brc tree from file

parent 67dd2b8c
No related branches found
No related tags found
No related merge requests found
pub mod brc_tree {
use std::io::Write;
use std::{io::Write, path::Path};
use indexmap::IndexMap;
......@@ -102,13 +102,72 @@ pub mod brc_tree {
pub fn write_structure(&self, mut file: &std::fs::File) -> anyhow::Result<()> {
match &self.0 {
Some(node) => {
file.write_all(format!("{},{};", node.min, node.max).as_bytes())?;
file.write_all(format!("{},{}", node.min, node.max).as_bytes())?;
file.write_all("(".as_bytes())?;
node.left.write_structure(file)?;
file.write_all(")".as_bytes())?;
file.write_all("(".as_bytes())?;
node.right.write_structure(file)?;
file.write_all(");".as_bytes())?;
}
None => {}
}
Ok(())
}
}
pub fn parse_from_file(file_name: &Path) -> anyhow::Result<Subtree> {
let contents = std::fs::read_to_string(file_name)?;
parse_from_string(contents)
}
fn parse_from_string(s: String) -> anyhow::Result<Subtree> {
let s = s.trim();
if s.is_empty() {
return Ok(Subtree(None));
}
let (min_max, rest) = s.split_at(s.find('(').unwrap());
println!("MM:{:?}", min_max);
let (min, max) = {
let mut parts = min_max.split(',');
(
parts.next().unwrap().parse::<isize>()?,
parts.next().unwrap().parse::<isize>()?,
)
};
let mut balance = 0;
let mut split_index = 0;
for (i, c) in rest.chars().enumerate() {
match c {
'(' => balance += 1,
')' => balance -= 1,
_ => {}
}
if balance == 0 {
split_index = i;
break;
}
}
let left_str = &rest[1..split_index];
let right_str = &rest[split_index + 2..rest.len() - 2];
let left = parse_from_string(left_str.to_string())?;
let right = parse_from_string(right_str.to_string())?;
Ok(Subtree(Some(Box::new(Node {
min,
max,
contents: vec![],
left,
right,
}))))
}
#[test]
fn test_parse() {
let test_data = "1,1()();".to_string();
let tree = parse_from_file("../brc_table.partitions".as_ref()).unwrap();
println!("{:?}", tree);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment