Removing unnecessary debug fmt uses

This commit is contained in:
vandomej 2021-10-02 21:21:01 -07:00
parent edc2f67897
commit daae6c2705
3 changed files with 63 additions and 110 deletions

View file

@ -2,7 +2,6 @@
extern crate serde; extern crate serde;
use std::fmt;
use std::fs; use std::fs;
use std::io; use std::io;
use std::io::prelude::*; use std::io::prelude::*;
@ -24,6 +23,7 @@ pub enum Error {
} }
/// A wrapper around an object `T` that ties the object to a physical file /// A wrapper around an object `T` that ties the object to a physical file
#[derive(Debug, PartialEq)]
pub struct FileLinked<T> pub struct FileLinked<T>
where where
T: Serialize, T: Serialize,
@ -109,13 +109,6 @@ where
/// # } /// # }
/// ``` /// ```
pub fn new(val: T, path: path::PathBuf) -> Result<FileLinked<T>, Error> { pub fn new(val: T, path: path::PathBuf) -> Result<FileLinked<T>, Error> {
if path.is_file() {
return Err(Error::IO(io::Error::new(
io::ErrorKind::Other,
anyhow!("{} is not a valid file path", path.display()),
)));
}
let result = FileLinked { val, path }; let result = FileLinked { val, path };
result.write_data()?; result.write_data()?;
@ -295,13 +288,6 @@ where
/// # } /// # }
/// ``` /// ```
pub fn from_file(path: path::PathBuf) -> Result<FileLinked<T>, Error> { pub fn from_file(path: path::PathBuf) -> Result<FileLinked<T>, Error> {
if !path.is_file() {
return Err(Error::IO(io::Error::new(
io::ErrorKind::Other,
anyhow!("{} is not a valid file path", path.display()),
)));
}
let metadata = path let metadata = path
.metadata() .metadata()
.with_context(|| format!("Error obtaining metadata for {}", path.display()))?; .with_context(|| format!("Error obtaining metadata for {}", path.display()))?;
@ -325,15 +311,6 @@ where
} }
} }
impl<T> fmt::Debug for FileLinked<T>
where
T: fmt::Debug + Serialize,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.val)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View file

@ -9,7 +9,6 @@ use crate::tree;
use file_linked::FileLinked; use file_linked::FileLinked;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt;
use std::path; use std::path;
/// As the bracket tree increases in height, `IterationScaling` can be used to configure the number of iterations that /// As the bracket tree increases in height, `IterationScaling` can be used to configure the number of iterations that
@ -26,7 +25,7 @@ use std::path;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path; /// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone, PartialEq)]
/// # struct TestState { /// # struct TestState {
/// # pub score: f64, /// # pub score: f64,
/// # } /// # }
@ -72,7 +71,7 @@ use std::path;
/// # std::fs::remove_file("./temp").expect("Unable to remove file"); /// # std::fs::remove_file("./temp").expect("Unable to remove file");
/// # } /// # }
/// ``` /// ```
#[derive(Clone, Serialize, Deserialize, Copy)] #[derive(Clone, Serialize, Deserialize, Copy, Debug, PartialEq)]
#[serde(tag = "enumType", content = "enumContent")] #[serde(tag = "enumType", content = "enumContent")]
pub enum IterationScaling { pub enum IterationScaling {
/// Scales the number of simulations linearly with the height of the bracket tree given by `f(x) = mx` where /// Scales the number of simulations linearly with the height of the bracket tree given by `f(x) = mx` where
@ -88,47 +87,24 @@ impl Default for IterationScaling {
} }
} }
impl fmt::Debug for IterationScaling {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
serde_json::to_string(self).expect("Unable to deserialize IterationScaling struct")
)
}
}
/// Creates a tournament style bracket for simulating and evaluating nodes of type `T` implementing [`GeneticNode`]. /// Creates a tournament style bracket for simulating and evaluating nodes of type `T` implementing [`GeneticNode`].
/// These nodes are built upwards as a balanced binary tree starting from the bottom. This results in `Bracket` building /// These nodes are built upwards as a balanced binary tree starting from the bottom. This results in `Bracket` building
/// a separate tree of the same height then merging trees together. Evaluating populations between nodes and taking the strongest /// a separate tree of the same height then merging trees together. Evaluating populations between nodes and taking the strongest
/// individuals. /// individuals.
/// ///
/// [`GeneticNode`]: genetic_node::GeneticNode /// [`GeneticNode`]: genetic_node::GeneticNode
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Bracket<T> pub struct Bracket<T>
where where
T: genetic_node::GeneticNode, T: genetic_node::GeneticNode + Serialize,
{ {
pub tree: tree::Tree<T>, pub tree: tree::Tree<T>,
iteration_scaling: IterationScaling, iteration_scaling: IterationScaling,
} }
impl<T> fmt::Debug for Bracket<T>
where
T: genetic_node::GeneticNode + Serialize,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
serde_json::to_string(self).expect("Unable to deserialize Bracket struct")
)
}
}
impl<T> Bracket<T> impl<T> Bracket<T>
where where
T: genetic_node::GeneticNode + Default + DeserializeOwned + Serialize + Clone, T: genetic_node::GeneticNode + Default + DeserializeOwned + Serialize + Clone + PartialEq,
{ {
/// Initializes a bracket of type `T` storing the contents to `file_path` /// Initializes a bracket of type `T` storing the contents to `file_path`
/// ///
@ -136,6 +112,7 @@ where
/// ``` /// ```
/// # use gemla::bracket::*; /// # use gemla::bracket::*;
/// # use gemla::btree; /// # use gemla::btree;
/// # use gemla::tree;
/// # use gemla::error::Error; /// # use gemla::error::Error;
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # use std::fmt; /// # use std::fmt;
@ -143,7 +120,7 @@ where
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path; /// # use std::path;
/// # /// #
/// #[derive(Default, Deserialize, Serialize, Debug, Clone)] /// #[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq)]
/// struct TestState { /// struct TestState {
/// pub score: f64, /// pub score: f64,
/// } /// }
@ -197,12 +174,6 @@ where
/// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp")) /// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
/// .expect("Bracket failed to initialize"); /// .expect("Bracket failed to initialize");
/// ///
/// assert_eq!(
/// format!("{:?}", bracket),
/// format!("{{\"tree\":{:?},\"iteration_scaling\":{{\"enumType\":\"Constant\",\"enumContent\":1}}}}",
/// btree!(TestState{score: 0.0}))
/// );
///
/// std::fs::remove_file("./temp").expect("Unable to remove file"); /// std::fs::remove_file("./temp").expect("Unable to remove file");
/// # } /// # }
/// ``` /// ```
@ -228,7 +199,7 @@ where
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path; /// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone, PartialEq)]
/// # struct TestState { /// # struct TestState {
/// # pub score: f64, /// # pub score: f64,
/// # } /// # }
@ -331,7 +302,7 @@ where
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path; /// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone, PartialEq)]
/// # struct TestState { /// # struct TestState {
/// # pub score: f64, /// # pub score: f64,
/// # } /// # }
@ -409,12 +380,13 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use crate::bracket::*;
use crate::tree::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
#[derive(Default, Deserialize, Serialize, Clone, Debug)] #[derive(Default, Deserialize, Serialize, Clone, Debug, PartialEq)]
struct TestState { struct TestState {
pub score: f64, pub score: f64,
} }
@ -456,9 +428,19 @@ mod tests {
.expect("Bracket failed to initialize"); .expect("Bracket failed to initialize");
assert_eq!( assert_eq!(
format!("{:?}", bracket), bracket,
format!("{{\"tree\":{:?},\"iteration_scaling\":{{\"enumType\":\"Constant\",\"enumContent\":1}}}}", file_linked::FileLinked::new(
btree!(TestState{score: 0.0})) Bracket {
tree: Tree {
val: TestState { score: 0.0 },
left: None,
right: None
},
iteration_scaling: IterationScaling::Constant(1)
},
path::PathBuf::from("./temp")
)
.unwrap()
); );
std::fs::remove_file("./temp").expect("Unable to remove file"); std::fs::remove_file("./temp").expect("Unable to remove file");
@ -479,29 +461,43 @@ mod tests {
} }
assert_eq!( assert_eq!(
format!("{:?}", bracket), bracket,
format!("{{\"tree\":{:?},\"iteration_scaling\":{{\"enumType\":\"Linear\",\"enumContent\":2}}}}", file_linked::FileLinked::new(
btree!( Bracket {
iteration_scaling: IterationScaling::Linear(2),
tree: btree!(
TestState { score: 12.0 }, TestState { score: 12.0 },
btree!( btree!(
TestState { score: 12.0 }, TestState { score: 12.0 },
btree!(TestState{score: 6.0}, btree!(
TestState { score: 6.0 },
btree!(TestState { score: 2.0 }), btree!(TestState { score: 2.0 }),
btree!(TestState{score: 2.0})), btree!(TestState { score: 2.0 })
btree!(TestState{score: 6.0}, ),
btree!(
TestState { score: 6.0 },
btree!(TestState { score: 2.0 }), btree!(TestState { score: 2.0 }),
btree!(TestState{score: 2.0})) btree!(TestState { score: 2.0 })
)
), ),
btree!( btree!(
TestState { score: 12.0 }, TestState { score: 12.0 },
btree!(TestState{score: 6.0}, btree!(
TestState { score: 6.0 },
btree!(TestState { score: 2.0 }), btree!(TestState { score: 2.0 }),
btree!(TestState{score: 2.0})), btree!(TestState { score: 2.0 })
btree!(TestState{score: 6.0}, ),
btree!(
TestState { score: 6.0 },
btree!(TestState { score: 2.0 }), btree!(TestState { score: 2.0 }),
btree!(TestState{score: 2.0}))) btree!(TestState { score: 2.0 })
) )
) )
)
},
path::PathBuf::from("./temp2")
)
.unwrap()
); );
std::fs::remove_file("./temp2").expect("Unable to remove file"); std::fs::remove_file("./temp2").expect("Unable to remove file");

View file

@ -18,7 +18,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::cmp::max; use std::cmp::max;
use std::fmt;
/// An unbalanced binary tree type where each node has an optional left and right child. /// An unbalanced binary tree type where each node has an optional left and right child.
/// ///
@ -37,7 +36,7 @@ use std::fmt;
/// t.right = Some(Box::new(btree!(3))); /// t.right = Some(Box::new(btree!(3)));
/// assert_eq!(t.right.unwrap().val, 3); /// assert_eq!(t.right.unwrap().val, 3);
/// ``` /// ```
#[derive(Default, Serialize, Deserialize, Clone, PartialEq)] #[derive(Default, Serialize, Deserialize, Clone, PartialEq, Debug)]
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>>>,
@ -142,17 +141,6 @@ impl<T> Tree<T> {
} }
} }
impl<T: fmt::Debug + Serialize> fmt::Debug for Tree<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let result = serde_json::to_string(self);
match result {
Ok(string) => write!(f, "{}", string),
Err(_) => Err(std::fmt::Error),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -173,14 +161,6 @@ mod tests {
); );
} }
#[test]
fn test_fmt() {
assert_eq!(
format!("{:?}", btree!("foo", btree!("bar"),),),
"{\"val\":\"foo\",\"left\":{\"val\":\"bar\",\"left\":null,\"right\":null},\"right\":null}"
);
}
#[test] #[test]
fn test_height() { fn test_height() {
assert_eq!(1, btree!(1).height()); assert_eq!(1, btree!(1).height());