Added rustfmt utility to project.

This commit is contained in:
Jacob VanDomelen 2019-05-31 23:36:42 -07:00
parent feadba1a65
commit 048ea8d564
7 changed files with 302 additions and 249 deletions

View file

@ -10,7 +10,11 @@ impl tree::Tree<Uuid> {
pub fn run_simulation(&self) { pub fn run_simulation(&self) {
println!("================================"); println!("================================");
println!("Running simulation for node: {}", self.val); println!("Running simulation for node: {}", self.val);
println!("With children {} and {}", tree::fmt_node(&self.left), tree::fmt_node(&self.right)); println!(
"With children {} and {}",
tree::fmt_node(&self.left),
tree::fmt_node(&self.right)
);
} }
} }
@ -26,10 +30,14 @@ fn build_tree(h: u32) -> Option<Box<tree::Tree<Uuid>>> {
// Recursively building a tree and running the simulation after wards to ensure a bottom-up // Recursively building a tree and running the simulation after wards to ensure a bottom-up
// execution order. // execution order.
if h != 0 { if h != 0 {
result = Some(Box::new(tree::Tree::new(Uuid::new_v4(), build_tree(h - 1), build_tree(h - 1)))); result = Some(Box::new(tree::Tree::new(
Uuid::new_v4(),
build_tree(h - 1),
build_tree(h - 1),
)));
match &result { match &result {
Some(r) => (*r).run_simulation(), Some(r) => (*r).run_simulation(),
_ => () _ => (),
} }
} }
@ -41,8 +49,10 @@ fn build_tree(h: u32) -> Option<Box<tree::Tree<Uuid>>> {
/// TODO: Explain reasoning for bracket system against genetic algorithm. /// TODO: Explain reasoning for bracket system against genetic algorithm.
pub fn run_bracket() { pub fn run_bracket() {
let mut height = 1; let mut height = 1;
let mut tree = FileLinked::new(*build_tree(height).expect("Error getting result from build_tree"), "temp") let mut tree = FileLinked::new(
.expect("Unable to create file linked object from tree"); *build_tree(height).expect("Error getting result from build_tree"),
"temp",
).expect("Unable to create file linked object from tree");
// Building tree one node at a time, appending to the top. // Building tree one node at a time, appending to the top.
@ -50,8 +60,11 @@ pub fn run_bracket() {
println!("========================================="); println!("=========================================");
println!("Running bracket..."); println!("Running bracket...");
height += 1; height += 1;
tree.replace(tree::Tree::new(Uuid::new_v4(), Some(Box::new(tree.readonly().clone())), build_tree(height))) tree.replace(tree::Tree::new(
.expect("Error building up tree node"); Uuid::new_v4(),
Some(Box::new(tree.readonly().clone())),
build_tree(height),
)).expect("Error building up tree node");
tree.readonly().run_simulation(); tree.readonly().run_simulation();
if height == 3 { if height == 3 {

View file

@ -7,35 +7,43 @@ use std::io::Write;
pub struct FileLinked<T> { pub struct FileLinked<T> {
val: T, val: T,
path: String path: String,
} }
impl<T> FileLinked<T> where T: FromStr + fmt::Display + Default { impl<T> FileLinked<T>
where
T: FromStr + fmt::Display + Default,
{
pub fn from_file(path: &str) -> Result<FileLinked<T>, String> { pub fn from_file(path: &str) -> Result<FileLinked<T>, String> {
let meta = fs::metadata(path); let meta = fs::metadata(path);
match &meta { match &meta {
Ok(m) if m.is_file() => { Ok(m) if m.is_file() => {
let mut file = fs::OpenOptions::new().read(true).open(path) let mut file = fs::OpenOptions::new().read(true).open(path).or(
.or(Err(format!("Unable to open file {}", path)))?; Err(format!(
"Unable to open file {}",
path
)),
)?;
let mut s = String::new(); let mut s = String::new();
file.read_to_string(&mut s) file.read_to_string(&mut s).or(Err(String::from(
.or(Err(String::from("Unable to read from file.")))?; "Unable to read from file.",
)))?;
let val = T::from_str(&s).or(Err(String::from("Unable to parse value from file.")))?; let val = T::from_str(&s).or(Err(String::from(
"Unable to parse value from file.",
)))?;
Ok(FileLinked { Ok(FileLinked {
val, val,
path: String::from(path) path: String::from(path),
}) })
}, }
Ok(_) => { Ok(_) => Err(format!("{} is not a file.", path)),
Err(format!("{} is not a file.", path))
},
_ => { _ => {
let result = FileLinked { let result = FileLinked {
val: T::default(), val: T::default(),
path: String::from(path) path: String::from(path),
}; };
result.write_data()?; result.write_data()?;
@ -48,7 +56,7 @@ impl<T> FileLinked<T> where T: FromStr + fmt::Display + Default {
pub fn new(val: T, path: &str) -> Result<FileLinked<T>, String> { pub fn new(val: T, path: &str) -> Result<FileLinked<T>, String> {
let result = FileLinked { let result = FileLinked {
val, val,
path: String::from(path) path: String::from(path),
}; };
result.write_data()?; result.write_data()?;
@ -64,8 +72,9 @@ impl<T> FileLinked<T> where T: FromStr + fmt::Display + Default {
.open(&self.path) .open(&self.path)
.or(Err(format!("Unable to open path {}", self.path)))?; .or(Err(format!("Unable to open path {}", self.path)))?;
write!(file, "{}", self.val) write!(file, "{}", self.val).or(Err(String::from(
.or(Err(String::from("Unable to write to file.")))?; "Unable to write to file.",
)))?;
Ok(()) Ok(())
} }
@ -82,7 +91,7 @@ impl<T> FileLinked<T> where T: FromStr + fmt::Display + Default {
Ok(result) Ok(result)
} }
pub fn replace(&mut self, val: T) -> Result<(), String>{ pub fn replace(&mut self, val: T) -> Result<(), String> {
self.val = val; self.val = val;
self.write_data() self.write_data()

View file

@ -30,11 +30,13 @@ fn main() {
bracket::run_bracket(); bracket::run_bracket();
println!("\n\nReading tree from temp file."); println!("\n\nReading tree from temp file.");
let tree: file_linked::FileLinked<tree::Tree<uuid::Uuid>> = file_linked::FileLinked::from_file("temp") let tree: file_linked::FileLinked<tree::Tree<uuid::Uuid>> =
.expect("Unable to read tree from existing file"); file_linked::FileLinked::from_file("temp").expect(
"Unable to read tree from existing file",
);
println!("Value read from file:\n{}", tree); println!("Value read from file:\n{}", tree);
}, }
Ok(_) => println!("{} is not a valid directory!", directory), Ok(_) => println!("{} is not a valid directory!", directory),
_ => println!("{} does not exist!", directory) _ => println!("{} does not exist!", directory),
} }
} }

View file

@ -6,16 +6,12 @@ use regex::Regex;
pub struct Tree<T> { pub struct Tree<T> {
pub val: T, pub val: T,
pub left: Option<Box<Tree<T>>>, pub left: Option<Box<Tree<T>>>,
pub right: Option<Box<Tree<T>>> pub right: Option<Box<Tree<T>>>,
} }
impl<T> Tree<T> { impl<T> Tree<T> {
pub fn new(val: T, left: Option<Box<Tree<T>>>, right: Option<Box<Tree<T>>>) -> Tree<T> { pub fn new(val: T, left: Option<Box<Tree<T>>>, right: Option<Box<Tree<T>>>) -> Tree<T> {
Tree { Tree { val, left, right }
val,
left,
right
}
} }
} }
@ -24,23 +20,31 @@ impl<T: fmt::Display> fmt::Display for Tree<T> {
let node_str = |t: &Option<Box<Tree<T>>>| -> String { let node_str = |t: &Option<Box<Tree<T>>>| -> String {
match t { match t {
Some(n) => format!("{}", *n), Some(n) => format!("{}", *n),
_ => String::from("_") _ => String::from("_"),
} }
}; };
write!(f, "({} :{}|{})", self.val, node_str(&self.left), node_str(&self.right)) write!(
f,
"({} :{}|{})",
self.val,
node_str(&self.left),
node_str(&self.right)
)
} }
} }
pub fn fmt_node<T: fmt::Display>(t: &Option<Box<Tree<T>>>) -> String { pub fn fmt_node<T: fmt::Display>(t: &Option<Box<Tree<T>>>) -> String {
match t { match t {
Some(n) => format!("{}", (*n).val), Some(n) => format!("{}", (*n).val),
_ => String::from("_") _ => String::from("_"),
} }
} }
fn seperate_nodes(s: &str) -> Result<(&str, &str), ParseTreeError> { fn seperate_nodes(s: &str) -> Result<(&str, &str), ParseTreeError> {
let mut result = Err(ParseTreeError::new(format!("Unable to seperate string: {}", s))); let mut result = Err(ParseTreeError::new(
format!("Unable to seperate string: {}", s),
));
let mut stack: Vec<char> = Vec::new(); let mut stack: Vec<char> = Vec::new();
for (i, c) in s.char_indices() { for (i, c) in s.char_indices() {
@ -48,13 +52,15 @@ fn seperate_nodes(s: &str) -> Result<(&str, &str), ParseTreeError> {
stack.push(c); stack.push(c);
} else if c == ')' { } else if c == ')' {
if stack.is_empty() { if stack.is_empty() {
result = Err(ParseTreeError::new(format!("Unbalanced parenthesis found in string: {}", s))); result = Err(ParseTreeError::new(
format!("Unbalanced parenthesis found in string: {}", s),
));
break; break;
} }
stack.pop(); stack.pop();
} else if c == '|' && stack.is_empty() { } else if c == '|' && stack.is_empty() {
result = Ok((&s[..i], &s[i+1..])); result = Ok((&s[..i], &s[i + 1..]));
break; break;
} }
} }
@ -63,14 +69,24 @@ fn seperate_nodes(s: &str) -> Result<(&str, &str), ParseTreeError> {
} }
fn from_str_helper<T: FromStr>(s: &str) -> Result<Option<Box<Tree<T>>>, ParseTreeError> { fn from_str_helper<T: FromStr>(s: &str) -> Result<Option<Box<Tree<T>>>, ParseTreeError> {
let mut result = Err(ParseTreeError::new(String::from("Unable to parse tree, string format unrecognized."))); let mut result = Err(ParseTreeError::new(String::from(
"Unable to parse tree, string format unrecognized.",
)));
let emptyre = Regex::new(r"\s*_\s*").unwrap(); let emptyre = Regex::new(r"\s*_\s*").unwrap();
let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap(); let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s); let caps = re.captures(s);
if let Some(c) = caps { if let Some(c) = caps {
let val = T::from_str(c.get(1).unwrap().as_str()) let val = T::from_str(c.get(1).unwrap().as_str()).or(Err(
.or(Err(ParseTreeError::new(format!("Unable to parse node value: {}", c.get(1).unwrap().as_str()))))?; ParseTreeError::new(
format!(
"Unable to parse node value: {}",
c.get(1)
.unwrap()
.as_str()
),
),
))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?; let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?; let left = from_str_helper(left)?;
let right = from_str_helper(right)?; let right = from_str_helper(right)?;
@ -83,17 +99,30 @@ fn from_str_helper<T: FromStr>(s: &str) -> Result<Option<Box<Tree<T>>>, ParseTre
result result
} }
impl<T> FromStr for Tree<T> where T: FromStr { impl<T> FromStr for Tree<T>
where
T: FromStr,
{
type Err = ParseTreeError; type Err = ParseTreeError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut result = Err(ParseTreeError::new(String::from("Unable to parse tree, string format unreognized."))); let mut result = Err(ParseTreeError::new(String::from(
"Unable to parse tree, string format unreognized.",
)));
let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap(); let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s); let caps = re.captures(s);
if let Some(c) = caps { if let Some(c) = caps {
let val = T::from_str(c.get(1).unwrap().as_str()) let val = T::from_str(c.get(1).unwrap().as_str()).or(Err(
.or(Err(ParseTreeError::new(format!("Unable to parse node value: {}", c.get(1).unwrap().as_str()))))?; ParseTreeError::new(
format!(
"Unable to parse node value: {}",
c.get(1)
.unwrap()
.as_str()
),
),
))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?; let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?; let left = from_str_helper(left)?;
let right = from_str_helper(right)?; let right = from_str_helper(right)?;
@ -103,7 +132,8 @@ impl<T> FromStr for Tree<T> where T: FromStr {
// if let Some(c) = caps { // if let Some(c) = caps {
// result = T::from_str(c.get(1).unwrap().as_str()) // result = T::from_str(c.get(1).unwrap().as_str())
// .or(Err(ParseTreeError::new(format!("Unable to parse node value: {}", c.get(1).unwrap().as_str())))) // .or(Err(ParseTreeError::new(
// format!("Unable to parse node value: {}", c.get(1).unwrap().as_str()))))
// .and_then(|v| { // .and_then(|v| {
// seperate_nodes(c.get(2).unwrap().as_str()) // seperate_nodes(c.get(2).unwrap().as_str())
// .and_then(|(left, right)| { // .and_then(|(left, right)| {
@ -140,7 +170,8 @@ impl<T> FromStr for Tree<T> where T: FromStr {
// } // }
// } // }
// } else { // } else {
// result = Err(ParseTreeError::new(format!("Unable to parse node value: {}", c.get(1).unwrap().as_str()))); // result = Err(ParseTreeError::new(
// format!("Unable to parse node value: {}", c.get(1).unwrap().as_str())));
// } // }
// } // }
@ -150,13 +181,11 @@ impl<T> FromStr for Tree<T> where T: FromStr {
#[derive(Debug)] #[derive(Debug)]
pub struct ParseTreeError { pub struct ParseTreeError {
pub msg: String pub msg: String,
} }
impl ParseTreeError { impl ParseTreeError {
fn new(msg: String) -> ParseTreeError { fn new(msg: String) -> ParseTreeError {
ParseTreeError { ParseTreeError { msg }
msg
}
} }
} }