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

@ -7,11 +7,15 @@ use uuid::Uuid;
use std::str::FromStr;
impl tree::Tree<Uuid> {
pub fn run_simulation(&self) {
println!("================================");
println!("Running simulation for node: {}", self.val);
println!("With children {} and {}", tree::fmt_node(&self.left), tree::fmt_node(&self.right));
}
pub fn run_simulation(&self) {
println!("================================");
println!("Running simulation for node: {}", self.val);
println!(
"With children {} and {}",
tree::fmt_node(&self.left),
tree::fmt_node(&self.right)
);
}
}
// pub struct Bracket {
@ -21,46 +25,55 @@ impl tree::Tree<Uuid> {
/// Constructs a tree with a given height while simultaneously running a simulation on each node.
fn build_tree(h: u32) -> Option<Box<tree::Tree<Uuid>>> {
let mut result: Option<Box<tree::Tree<Uuid>>> = None;
let mut result: Option<Box<tree::Tree<Uuid>>> = None;
// Recursively building a tree and running the simulation after wards to ensure a bottom-up
// execution order.
if h != 0 {
result = Some(Box::new(tree::Tree::new(Uuid::new_v4(), build_tree(h - 1), build_tree(h - 1))));
match &result {
Some(r) => (*r).run_simulation(),
_ => ()
}
}
// Recursively building a tree and running the simulation after wards to ensure a bottom-up
// execution order.
if h != 0 {
result = Some(Box::new(tree::Tree::new(
Uuid::new_v4(),
build_tree(h - 1),
build_tree(h - 1),
)));
match &result {
Some(r) => (*r).run_simulation(),
_ => (),
}
}
result
result
}
/// Generates a bracket tree and runs simulation against each node.
///
///
/// TODO: Explain reasoning for bracket system against genetic algorithm.
pub fn run_bracket() {
let mut height = 1;
let mut tree = FileLinked::new(*build_tree(height).expect("Error getting result from build_tree"), "temp")
.expect("Unable to create file linked object from tree");
let mut height = 1;
let mut tree = FileLinked::new(
*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.
loop {
println!("=========================================");
println!("Running bracket...");
height += 1;
tree.replace(tree::Tree::new(Uuid::new_v4(), Some(Box::new(tree.readonly().clone())), build_tree(height)))
.expect("Error building up tree node");
tree.readonly().run_simulation();
// Building tree one node at a time, appending to the top.
loop {
println!("=========================================");
println!("Running bracket...");
height += 1;
tree.replace(tree::Tree::new(
Uuid::new_v4(),
Some(Box::new(tree.readonly().clone())),
build_tree(height),
)).expect("Error building up tree node");
tree.readonly().run_simulation();
if height == 3 {
println!("{}\n\n", tree);
let s = format!("{}", tree);
println!("{}\n\n", s);
let tree2: tree::Tree<Uuid> = tree::Tree::from_str(&s).unwrap();
println!("{}\n\n", tree2);
break;
}
}
}
if height == 3 {
println!("{}\n\n", tree);
let s = format!("{}", tree);
println!("{}\n\n", s);
let tree2: tree::Tree<Uuid> = tree::Tree::from_str(&s).unwrap();
println!("{}\n\n", tree2);
break;
}
}
}

View file

@ -15,4 +15,4 @@
// State {
// id: id.clone()
// }
// }
// }

View file

@ -1,2 +1,2 @@
/// Corresponds to the DIRECTORY command line argument used in accordance with the clap crate.
pub const DIRECTORY: &str = "DIRECTORY";
pub const DIRECTORY: &str = "DIRECTORY";

View file

@ -1 +1 @@
pub mod args;
pub mod args;

View file

@ -6,91 +6,100 @@ use std::io::Read;
use std::io::Write;
pub struct FileLinked<T> {
val: T,
path: String
val: T,
path: String,
}
impl<T> FileLinked<T> where T: FromStr + fmt::Display + Default {
pub fn from_file(path: &str) -> Result<FileLinked<T>, String> {
let meta = fs::metadata(path);
impl<T> FileLinked<T>
where
T: FromStr + fmt::Display + Default,
{
pub fn from_file(path: &str) -> Result<FileLinked<T>, String> {
let meta = fs::metadata(path);
match &meta {
Ok(m) if m.is_file() => {
let mut file = fs::OpenOptions::new().read(true).open(path)
.or(Err(format!("Unable to open file {}", path)))?;
let mut s = String::new();
file.read_to_string(&mut s)
.or(Err(String::from("Unable to read from file.")))?;
match &meta {
Ok(m) if m.is_file() => {
let mut file = fs::OpenOptions::new().read(true).open(path).or(
Err(format!(
"Unable to open file {}",
path
)),
)?;
let mut s = String::new();
file.read_to_string(&mut s).or(Err(String::from(
"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 {
val,
path: String::from(path)
})
},
Ok(_) => {
Err(format!("{} is not a file.", path))
},
_ => {
let result = FileLinked {
val: T::default(),
path: String::from(path)
};
Ok(FileLinked {
val,
path: String::from(path),
})
}
Ok(_) => Err(format!("{} is not a file.", path)),
_ => {
let result = FileLinked {
val: T::default(),
path: String::from(path),
};
result.write_data()?;
result.write_data()?;
Ok(result)
}
}
}
Ok(result)
}
}
}
pub fn new(val: T, path: &str) -> Result<FileLinked<T>, String> {
let result = FileLinked {
val,
path: String::from(path)
};
pub fn new(val: T, path: &str) -> Result<FileLinked<T>, String> {
let result = FileLinked {
val,
path: String::from(path),
};
result.write_data()?;
result.write_data()?;
Ok(result)
}
Ok(result)
}
pub fn write_data(&self) -> Result<(), String> {
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&self.path)
.or(Err(format!("Unable to open path {}", self.path)))?;
pub fn write_data(&self) -> Result<(), String> {
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&self.path)
.or(Err(format!("Unable to open path {}", self.path)))?;
write!(file, "{}", self.val)
.or(Err(String::from("Unable to write to file.")))?;
write!(file, "{}", self.val).or(Err(String::from(
"Unable to write to file.",
)))?;
Ok(())
}
Ok(())
}
pub fn readonly(&self) -> &T {
&self.val
}
pub fn readonly(&self) -> &T {
&self.val
}
pub fn mutate<U, F: FnOnce(&mut T) -> U>(&mut self, op: F) -> Result<U, String> {
let result = op(&mut self.val);
pub fn mutate<U, F: FnOnce(&mut T) -> U>(&mut self, op: F) -> Result<U, String> {
let result = op(&mut self.val);
self.write_data()?;
self.write_data()?;
Ok(result)
}
Ok(result)
}
pub fn replace(&mut self, val: T) -> Result<(), String>{
self.val = val;
pub fn replace(&mut self, val: T) -> Result<(), String> {
self.val = val;
self.write_data()
}
self.write_data()
}
}
impl<T: fmt::Display> fmt::Display for FileLinked<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.val)
}
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.val)
}
}

View file

@ -11,30 +11,32 @@ use clap::App;
use std::fs::metadata;
/// Runs a simluation of a genetic algorithm against a dataset.
///
///
/// Use the -h, --h, or --help flag to see usage syntax.
/// TODO
fn main() {
// Command line arguments are parsed with the clap crate. And this program uses
// the yaml method with clap.
let yaml = load_yaml!("../cli.yml");
let matches = App::from_yaml(yaml).get_matches();
// Command line arguments are parsed with the clap crate. And this program uses
// the yaml method with clap.
let yaml = load_yaml!("../cli.yml");
let matches = App::from_yaml(yaml).get_matches();
// Checking that the first argument <DIRECTORY> is a valid directory
let directory = matches.value_of(constants::args::DIRECTORY).unwrap();
let metadata = metadata(directory);
match &metadata {
Ok(m) if m.is_dir() == true => {
println!("{} is a valid directory!", directory);
println!("Building tree for {}.", directory);
bracket::run_bracket();
// Checking that the first argument <DIRECTORY> is a valid directory
let directory = matches.value_of(constants::args::DIRECTORY).unwrap();
let metadata = metadata(directory);
match &metadata {
Ok(m) if m.is_dir() == true => {
println!("{} is a valid directory!", directory);
println!("Building tree for {}.", directory);
bracket::run_bracket();
println!("\n\nReading tree from temp file.");
let tree: file_linked::FileLinked<tree::Tree<uuid::Uuid>> = file_linked::FileLinked::from_file("temp")
.expect("Unable to read tree from existing file");
println!("Value read from file:\n{}", tree);
},
Ok(_) => println!("{} is not a valid directory!", directory),
_ => println!("{} does not exist!", directory)
}
}
println!("\n\nReading tree from temp file.");
let tree: file_linked::FileLinked<tree::Tree<uuid::Uuid>> =
file_linked::FileLinked::from_file("temp").expect(
"Unable to read tree from existing file",
);
println!("Value read from file:\n{}", tree);
}
Ok(_) => println!("{} is not a valid directory!", directory),
_ => println!("{} does not exist!", directory),
}
}

View file

@ -4,159 +4,188 @@ use regex::Regex;
#[derive(Default, Clone)]
pub struct Tree<T> {
pub val: T,
pub left: Option<Box<Tree<T>>>,
pub right: Option<Box<Tree<T>>>
pub val: T,
pub left: Option<Box<Tree<T>>>,
pub right: Option<Box<Tree<T>>>,
}
impl<T> Tree<T> {
pub fn new(val: T, left: Option<Box<Tree<T>>>, right: Option<Box<Tree<T>>>) -> Tree<T> {
Tree {
val,
left,
right
}
}
pub fn new(val: T, left: Option<Box<Tree<T>>>, right: Option<Box<Tree<T>>>) -> Tree<T> {
Tree { val, left, right }
}
}
impl<T: fmt::Display> fmt::Display for Tree<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let node_str = |t: &Option<Box<Tree<T>>>| -> String {
match t {
Some(n) => format!("{}", *n),
_ => String::from("_")
}
};
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let node_str = |t: &Option<Box<Tree<T>>>| -> String {
match t {
Some(n) => format!("{}", *n),
_ => 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 {
match t {
Some(n) => format!("{}", (*n).val),
_ => String::from("_")
}
match t {
Some(n) => format!("{}", (*n).val),
_ => String::from("_"),
}
}
fn seperate_nodes(s: &str) -> Result<(&str, &str), ParseTreeError> {
let mut result = Err(ParseTreeError::new(format!("Unable to seperate string: {}", s)));
let mut stack: Vec<char> = Vec::new();
let mut result = Err(ParseTreeError::new(
format!("Unable to seperate string: {}", s),
));
let mut stack: Vec<char> = Vec::new();
for (i, c) in s.char_indices() {
if c == '(' {
stack.push(c);
} else if c == ')' {
if stack.is_empty() {
result = Err(ParseTreeError::new(format!("Unbalanced parenthesis found in string: {}", s)));
break;
}
for (i, c) in s.char_indices() {
if c == '(' {
stack.push(c);
} else if c == ')' {
if stack.is_empty() {
result = Err(ParseTreeError::new(
format!("Unbalanced parenthesis found in string: {}", s),
));
break;
}
stack.pop();
} else if c == '|' && stack.is_empty() {
result = Ok((&s[..i], &s[i+1..]));
break;
}
}
stack.pop();
} else if c == '|' && stack.is_empty() {
result = Ok((&s[..i], &s[i + 1..]));
break;
}
}
result
result
}
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 emptyre = Regex::new(r"\s*_\s*").unwrap();
let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s);
let mut result = Err(ParseTreeError::new(String::from(
"Unable to parse tree, string format unrecognized.",
)));
let emptyre = Regex::new(r"\s*_\s*").unwrap();
let re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s);
if let Some(c) = caps {
let val = 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()))))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?;
let right = from_str_helper(right)?;
if let Some(c) = caps {
let val = 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()
),
),
))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?;
let right = from_str_helper(right)?;
result = Ok(Some(Box::new(Tree::new(val, left, right))));
} else if emptyre.is_match(s) {
result = Ok(None);
}
result = Ok(Some(Box::new(Tree::new(val, left, right))));
} else if emptyre.is_match(s) {
result = Ok(None);
}
result
result
}
impl<T> FromStr for Tree<T> where T: FromStr {
type Err = ParseTreeError;
impl<T> FromStr for Tree<T>
where
T: FromStr,
{
type Err = ParseTreeError;
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 re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s);
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 re = Regex::new(r"\(([0-9a-fA-F-]+)\s*:\s*(.*)\)$").unwrap();
let caps = re.captures(s);
if let Some(c) = caps {
let val = 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()))))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?;
let right = from_str_helper(right)?;
result = Ok(Tree::new(val, left, right));
}
if let Some(c) = caps {
let val = 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()
),
),
))?;
let (left, right) = seperate_nodes(c.get(2).unwrap().as_str())?;
let left = from_str_helper(left)?;
let right = from_str_helper(right)?;
// if let Some(c) = caps {
// 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()))))
// .and_then(|v| {
// seperate_nodes(c.get(2).unwrap().as_str())
// .and_then(|(left, right)| {
// from_str_helper(left)
// .and_then(|l| {
// from_str_helper(right)
// .and_then(|r| {
// Ok(Tree::new(v, l, r))
// })
// })
// })
// })
// }
result = Ok(Tree::new(val, left, right));
}
// if let Some(c) = caps {
// let val = T::from_str(c.get(1).unwrap().as_str());
// if let Ok(v) = val {
// match seperate_nodes(c.get(2).unwrap().as_str()) {
// Ok((l, r)) => {
// match (from_str_helper(l), from_str_helper(r)) {
// (Ok(left), Ok(right)) => {
// result = Ok(Tree::new(v, left, right));
// },
// (Err(e), _) => {
// result = Err(e);
// },
// (_, Err(e)) => {
// result = Err(e);
// }
// }
// },
// Err(e) => {
// result = Err(e);
// }
// }
// } else {
// result = Err(ParseTreeError::new(format!("Unable to parse node value: {}", c.get(1).unwrap().as_str())));
// }
// }
// if let Some(c) = caps {
// 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()))))
// .and_then(|v| {
// seperate_nodes(c.get(2).unwrap().as_str())
// .and_then(|(left, right)| {
// from_str_helper(left)
// .and_then(|l| {
// from_str_helper(right)
// .and_then(|r| {
// Ok(Tree::new(v, l, r))
// })
// })
// })
// })
// }
result
}
// if let Some(c) = caps {
// let val = T::from_str(c.get(1).unwrap().as_str());
// if let Ok(v) = val {
// match seperate_nodes(c.get(2).unwrap().as_str()) {
// Ok((l, r)) => {
// match (from_str_helper(l), from_str_helper(r)) {
// (Ok(left), Ok(right)) => {
// result = Ok(Tree::new(v, left, right));
// },
// (Err(e), _) => {
// result = Err(e);
// },
// (_, Err(e)) => {
// result = Err(e);
// }
// }
// },
// Err(e) => {
// result = Err(e);
// }
// }
// } else {
// result = Err(ParseTreeError::new(
// format!("Unable to parse node value: {}", c.get(1).unwrap().as_str())));
// }
// }
result
}
}
#[derive(Debug)]
pub struct ParseTreeError {
pub msg: String
pub msg: String,
}
impl ParseTreeError {
fn new(msg: String) -> ParseTreeError {
ParseTreeError {
msg
}
}
}
fn new(msg: String) -> ParseTreeError {
ParseTreeError { msg }
}
}