Using PathBuf for paths

This commit is contained in:
vandomej 2021-10-01 00:57:33 -07:00
parent de4a44c93e
commit e5090d650c
4 changed files with 98 additions and 104 deletions

View file

@ -5,6 +5,7 @@ extern crate serde;
use std::fmt; use std::fmt;
use std::fs; use std::fs;
use std::io::prelude::*; use std::io::prelude::*;
use std::path;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
@ -15,7 +16,7 @@ where
T: Serialize, T: Serialize,
{ {
val: T, val: T,
path: String, path: path::PathBuf,
} }
impl<T> FileLinked<T> impl<T> FileLinked<T>
@ -30,6 +31,7 @@ where
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # use std::fmt; /// # use std::fmt;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Deserialize, Serialize)] /// # #[derive(Deserialize, Serialize)]
/// # struct Test { /// # struct Test {
@ -45,7 +47,7 @@ where
/// c: 3.0 /// c: 3.0
/// }; /// };
/// ///
/// let linked_test = FileLinked::new(test, String::from("./temp")) /// let linked_test = FileLinked::new(test, path::PathBuf::from("./temp"))
/// .expect("Unable to create file linked object"); /// .expect("Unable to create file linked object");
/// ///
/// assert_eq!(linked_test.readonly().a, 1); /// assert_eq!(linked_test.readonly().a, 1);
@ -60,13 +62,14 @@ where
} }
/// Creates a new [`FileLinked`] object of type `T` stored to the file given by `path`. /// Creates a new [`FileLinked`] object of type `T` stored to the file given by `path`.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use file_linked::*; /// # use file_linked::*;
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # use std::fmt; /// # use std::fmt;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// #[derive(Deserialize, Serialize)] /// #[derive(Deserialize, Serialize)]
/// struct Test { /// struct Test {
@ -82,7 +85,7 @@ where
/// c: 3.0 /// c: 3.0
/// }; /// };
/// ///
/// let linked_test = FileLinked::new(test, String::from("./temp")) /// let linked_test = FileLinked::new(test, path::PathBuf::from("./temp"))
/// .expect("Unable to create file linked object"); /// .expect("Unable to create file linked object");
/// ///
/// assert_eq!(linked_test.readonly().a, 1); /// assert_eq!(linked_test.readonly().a, 1);
@ -92,7 +95,11 @@ where
/// # std::fs::remove_file("./temp").expect("Unable to remove file"); /// # std::fs::remove_file("./temp").expect("Unable to remove file");
/// # } /// # }
/// ``` /// ```
pub fn new(val: T, path: String) -> Result<FileLinked<T>, String> { pub fn new(val: T, path: path::PathBuf) -> Result<FileLinked<T>, String> {
if path.is_file() {
return Err(format!("{} is not a valid file path", path.display()));
}
let result = FileLinked { val, path }; let result = FileLinked { val, path };
result.write_data()?; result.write_data()?;
@ -106,23 +113,28 @@ where
.create(true) .create(true)
.truncate(true) .truncate(true)
.open(&self.path) .open(&self.path)
.map_err(|_| format!("Unable to open path {}", self.path))?; .map_err(|_| format!("Unable to open path {}", self.path.display()))?;
write!(file, "{}", serde_json::to_string(&self.val).map_err(|e| e.to_string())?) write!(
.or_else(|_| Err(String::from("Unable to write to file.")))?; file,
"{}",
serde_json::to_string(&self.val).map_err(|e| e.to_string())?
)
.or_else(|_| Err(String::from("Unable to write to file.")))?;
Ok(()) Ok(())
} }
/// Modifies the data contained in a `FileLinked` object using a callback `op` that has a mutable reference to the /// Modifies the data contained in a `FileLinked` object using a callback `op` that has a mutable reference to the
/// underlying data. After the mutable operation is performed the data is written to a file to synchronize the state. /// underlying data. After the mutable operation is performed the data is written to a file to synchronize the state.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use file_linked::*; /// # use file_linked::*;
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # use std::fmt; /// # use std::fmt;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Deserialize, Serialize)] /// # #[derive(Deserialize, Serialize)]
/// # struct Test { /// # struct Test {
@ -138,13 +150,13 @@ where
/// c: 0.0 /// c: 0.0
/// }; /// };
/// ///
/// let mut linked_test = FileLinked::new(test, String::from("./temp")) /// let mut linked_test = FileLinked::new(test, path::PathBuf::from("./temp"))
/// .expect("Unable to create file linked object"); /// .expect("Unable to create file linked object");
/// ///
/// assert_eq!(linked_test.readonly().a, 1); /// assert_eq!(linked_test.readonly().a, 1);
/// ///
/// linked_test.mutate(|t| t.a = 2)?; /// linked_test.mutate(|t| t.a = 2)?;
/// ///
/// assert_eq!(linked_test.readonly().a, 2); /// assert_eq!(linked_test.readonly().a, 2);
/// # /// #
/// # std::fs::remove_file("./temp").expect("Unable to remove file"); /// # std::fs::remove_file("./temp").expect("Unable to remove file");
@ -161,13 +173,14 @@ where
} }
/// Replaces the value held by the `FileLinked` object with `val`. After replacing the object will be written to a file. /// Replaces the value held by the `FileLinked` object with `val`. After replacing the object will be written to a file.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use file_linked::*; /// # use file_linked::*;
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # use std::fmt; /// # use std::fmt;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Deserialize, Serialize)] /// # #[derive(Deserialize, Serialize)]
/// # struct Test { /// # struct Test {
@ -183,17 +196,17 @@ where
/// c: 0.0 /// c: 0.0
/// }; /// };
/// ///
/// let mut linked_test = FileLinked::new(test, String::from("./temp")) /// let mut linked_test = FileLinked::new(test, path::PathBuf::from("./temp"))
/// .expect("Unable to create file linked object"); /// .expect("Unable to create file linked object");
/// ///
/// assert_eq!(linked_test.readonly().a, 1); /// assert_eq!(linked_test.readonly().a, 1);
/// ///
/// linked_test.replace(Test { /// linked_test.replace(Test {
/// a: 2, /// a: 2,
/// b: String::from(""), /// b: String::from(""),
/// c: 0.0 /// c: 0.0
/// })?; /// })?;
/// ///
/// assert_eq!(linked_test.readonly().a, 2); /// assert_eq!(linked_test.readonly().a, 2);
/// # /// #
/// # std::fs::remove_file("./temp").expect("Unable to remove file"); /// # std::fs::remove_file("./temp").expect("Unable to remove file");
@ -210,10 +223,10 @@ where
impl<T> FileLinked<T> impl<T> FileLinked<T>
where where
T: Serialize + DeserializeOwned + Default, T: Serialize + DeserializeOwned,
{ {
/// Deserializes an object `T` from the file given by `path` /// Deserializes an object `T` from the file given by `path`
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use file_linked::*; /// # use file_linked::*;
@ -223,8 +236,9 @@ where
/// # use std::fs; /// # use std::fs;
/// # use std::fs::OpenOptions; /// # use std::fs::OpenOptions;
/// # use std::io::Write; /// # use std::io::Write;
/// # use std::path;
/// # /// #
/// # #[derive(Deserialize, Serialize, Default)] /// # #[derive(Deserialize, Serialize)]
/// # struct Test { /// # struct Test {
/// # pub a: u32, /// # pub a: u32,
/// # pub b: String, /// # pub b: String,
@ -237,22 +251,22 @@ where
/// b: String::from("2"), /// b: String::from("2"),
/// c: 3.0 /// c: 3.0
/// }; /// };
/// ///
/// let path = String::from("./temp"); /// let path = path::PathBuf::from("./temp");
/// ///
/// let mut file = OpenOptions::new() /// let mut file = OpenOptions::new()
/// .write(true) /// .write(true)
/// .create(true) /// .create(true)
/// .open(path.clone()) /// .open(path.clone())
/// .expect("Unable to create file"); /// .expect("Unable to create file");
/// ///
/// write!(file, "{}", serde_json::to_string(&test) /// write!(file, "{}", serde_json::to_string(&test)
/// .expect("Unable to serialize object")) /// .expect("Unable to serialize object"))
/// .expect("Unable to write file"); /// .expect("Unable to write file");
/// ///
/// drop(file); /// drop(file);
/// ///
/// let mut linked_test = FileLinked::<Test>::from_file(&path) /// let mut linked_test = FileLinked::<Test>::from_file(path)
/// .expect("Unable to create file linked object"); /// .expect("Unable to create file linked object");
/// ///
/// assert_eq!(linked_test.readonly().a, test.a); /// assert_eq!(linked_test.readonly().a, test.a);
@ -264,43 +278,30 @@ where
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn from_file(path: &str) -> Result<FileLinked<T>, String> { pub fn from_file(path: path::PathBuf) -> 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() && path.is_file()=> {
let file = fs::OpenOptions::new() let file = fs::OpenOptions::new()
.read(true) .read(true)
.open(path) .open(&path)
.map_err(|_| format!("Unable to open file {}", path))?; .map_err(|_| format!("Unable to open file {}", path.display()))?;
let val = serde_json::from_reader(file) let val = serde_json::from_reader(file)
.map_err(|_| String::from("Unable to parse value from file."))?; .map_err(|_| String::from("Unable to parse value from file."))?;
Ok(FileLinked { Ok(FileLinked { val, path })
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()?;
Ok(result)
} }
Ok(_) => Err(format!("{} is not a file.", path.display())),
_ => Err(format!("Error parsing file path {}", path.display())),
} }
} }
} }
impl<T> fmt::Debug for FileLinked<T> impl<T> fmt::Debug for FileLinked<T>
where where
T: fmt::Debug T: fmt::Debug + Serialize,
+ Serialize,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.val) write!(f, "{:?}", self.val)
@ -315,12 +316,9 @@ mod tests {
#[test] #[test]
fn test_mutate() -> Result<(), String> { fn test_mutate() -> Result<(), String> {
let list = vec![1, 2, 3, 4]; let list = vec![1, 2, 3, 4];
let mut file_linked_list = FileLinked::new(list, String::from("test.txt"))?; let mut file_linked_list = FileLinked::new(list, path::PathBuf::from("test.txt"))?;
assert_eq!( assert_eq!(format!("{:?}", file_linked_list.readonly()), "[1, 2, 3, 4]");
format!("{:?}", file_linked_list.readonly()),
"[1, 2, 3, 4]"
);
file_linked_list.mutate(|v1| v1.push(5))?; file_linked_list.mutate(|v1| v1.push(5))?;
@ -329,9 +327,7 @@ mod tests {
"[1, 2, 3, 4, 5]" "[1, 2, 3, 4, 5]"
); );
file_linked_list.mutate(|v1| { file_linked_list.mutate(|v1| v1[1] = 1)?;
v1[1] = 1
})?;
assert_eq!( assert_eq!(
format!("{:?}", file_linked_list.readonly()), format!("{:?}", file_linked_list.readonly()),

View file

@ -9,6 +9,7 @@ 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::fmt;
use std::path;
use std::str::FromStr; use std::str::FromStr;
/// 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
@ -22,6 +23,7 @@ use std::str::FromStr;
/// # use std::fmt; /// # use std::fmt;
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone)]
/// # struct TestState { /// # struct TestState {
@ -66,7 +68,7 @@ use std::str::FromStr;
/// # } /// # }
/// # /// #
/// # fn main() { /// # fn main() {
/// let mut bracket = Bracket::<TestState>::initialize("./temp".to_string()) /// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
/// .expect("Bracket failed to initialize"); /// .expect("Bracket failed to initialize");
/// ///
/// // Constant iteration scaling ensures that every node is simulated 5 times. /// // Constant iteration scaling ensures that every node is simulated 5 times.
@ -120,8 +122,7 @@ where
impl<T> fmt::Debug for Bracket<T> impl<T> fmt::Debug for Bracket<T>
where where
T: genetic_node::GeneticNode T: genetic_node::GeneticNode + Serialize,
+ Serialize
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( write!(
@ -134,12 +135,7 @@ where
impl<T> Bracket<T> impl<T> Bracket<T>
where where
T: genetic_node::GeneticNode T: genetic_node::GeneticNode + FromStr + Default + DeserializeOwned + Serialize + Clone,
+ FromStr
+ Default
+ DeserializeOwned
+ Serialize
+ Clone,
{ {
/// Initializes a bracket of type `T` storing the contents to `file_path` /// Initializes a bracket of type `T` storing the contents to `file_path`
/// ///
@ -151,6 +147,7 @@ where
/// # use std::fmt; /// # use std::fmt;
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// #[derive(Default, Deserialize, Serialize, Debug, Clone)] /// #[derive(Default, Deserialize, Serialize, Debug, Clone)]
/// struct TestState { /// struct TestState {
@ -203,7 +200,7 @@ where
/// } /// }
/// ///
/// # fn main() { /// # fn main() {
/// let mut bracket = Bracket::<TestState>::initialize("./temp".to_string()) /// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
/// .expect("Bracket failed to initialize"); /// .expect("Bracket failed to initialize");
/// ///
/// assert_eq!( /// assert_eq!(
@ -215,7 +212,7 @@ where
/// std::fs::remove_file("./temp").expect("Unable to remove file"); /// std::fs::remove_file("./temp").expect("Unable to remove file");
/// # } /// # }
/// ``` /// ```
pub fn initialize(file_path: String) -> Result<FileLinked<Self>, String> { pub fn initialize(file_path: path::PathBuf) -> Result<FileLinked<Self>, String> {
FileLinked::new( FileLinked::new(
Bracket { Bracket {
tree: btree!(*T::initialize()?), tree: btree!(*T::initialize()?),
@ -234,6 +231,7 @@ where
/// # use std::fmt; /// # use std::fmt;
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone)]
/// # struct TestState { /// # struct TestState {
@ -284,7 +282,7 @@ where
/// # } /// # }
/// # /// #
/// # fn main() { /// # fn main() {
/// let mut bracket = Bracket::<TestState>::initialize("./temp".to_string()) /// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
/// .expect("Bracket failed to initialize"); /// .expect("Bracket failed to initialize");
/// ///
/// // Constant iteration scaling ensures that every node is simulated 5 times. /// // Constant iteration scaling ensures that every node is simulated 5 times.
@ -343,6 +341,7 @@ where
/// # use std::fmt; /// # use std::fmt;
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use std::string::ToString; /// # use std::string::ToString;
/// # use std::path;
/// # /// #
/// # #[derive(Default, Deserialize, Serialize, Clone)] /// # #[derive(Default, Deserialize, Serialize, Clone)]
/// # struct TestState { /// # struct TestState {
@ -393,7 +392,7 @@ where
/// # } /// # }
/// # /// #
/// # fn main() { /// # fn main() {
/// let mut bracket = Bracket::<TestState>::initialize("./temp".to_string()) /// let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
/// .expect("Bracket failed to initialize"); /// .expect("Bracket failed to initialize");
/// ///
/// // Running simulations 3 times /// // Running simulations 3 times
@ -434,7 +433,6 @@ mod tests {
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
use std::string::ToString;
#[derive(Default, Deserialize, Serialize, Clone, Debug)] #[derive(Default, Deserialize, Serialize, Clone, Debug)]
struct TestState { struct TestState {
@ -474,7 +472,7 @@ mod tests {
#[test] #[test]
fn test_new() { fn test_new() {
let bracket = Bracket::<TestState>::initialize("./temp".to_string()) let bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp"))
.expect("Bracket failed to initialize"); .expect("Bracket failed to initialize");
assert_eq!( assert_eq!(
@ -488,7 +486,7 @@ mod tests {
#[test] #[test]
fn test_run() { fn test_run() {
let mut bracket = Bracket::<TestState>::initialize("./temp2".to_string()) let mut bracket = Bracket::<TestState>::initialize(path::PathBuf::from("./temp2"))
.expect("Bracket failed to initialize"); .expect("Bracket failed to initialize");
bracket bracket

View file

@ -1,5 +1,5 @@
extern crate regex;
extern crate file_linked; extern crate file_linked;
extern crate regex;
#[macro_use] #[macro_use]
pub mod tree; pub mod tree;

View file

@ -4,14 +4,14 @@
//! //!
//! ``` //! ```
//! use gemla::btree; //! use gemla::btree;
//! //!
//! // Tree with 2 nodes, one root node and one on the left side //! // Tree with 2 nodes, one root node and one on the left side
//! let mut t = btree!(1, btree!(2),); //! let mut t = btree!(1, btree!(2),);
//! //!
//! assert_eq!(t.height(), 2); //! assert_eq!(t.height(), 2);
//! assert_eq!(t.left.unwrap().val, 2); //! assert_eq!(t.left.unwrap().val, 2);
//! assert_eq!(t.right, None); //! assert_eq!(t.right, None);
//! //!
//! 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);
//! ``` //! ```
@ -28,14 +28,14 @@ use std::str::FromStr;
/// ///
/// ``` /// ```
/// use gemla::btree; /// use gemla::btree;
/// ///
/// // Tree with 2 nodes, one root node and one on the left side /// // Tree with 2 nodes, one root node and one on the left side
/// let mut t = btree!(1, btree!(2),); /// let mut t = btree!(1, btree!(2),);
/// ///
/// assert_eq!(t.height(), 2); /// assert_eq!(t.height(), 2);
/// assert_eq!(t.left.unwrap().val, 2); /// assert_eq!(t.left.unwrap().val, 2);
/// assert_eq!(t.right, None); /// assert_eq!(t.right, None);
/// ///
/// 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);
/// ``` /// ```
@ -53,34 +53,34 @@ pub struct Tree<T> {
/// ``` /// ```
/// use gemla::tree::*; /// use gemla::tree::*;
/// use gemla::btree; /// use gemla::btree;
/// ///
/// # fn main() { /// # fn main() {
/// // A tree with two child nodes. /// // A tree with two child nodes.
/// let t = btree!(1, btree!(2), btree!(3)); /// let t = btree!(1, btree!(2), btree!(3));
/// assert_eq!(t, /// assert_eq!(t,
/// Tree::new(1, /// Tree::new(1,
/// Some(Box::new(Tree::new(2, None, None))), /// Some(Box::new(Tree::new(2, None, None))),
/// Some(Box::new(Tree::new(3, None, None))))); /// Some(Box::new(Tree::new(3, None, None)))));
/// ///
/// // A tree with only a left node. /// // A tree with only a left node.
/// let t_left = btree!(1, btree!(2),); /// let t_left = btree!(1, btree!(2),);
/// assert_eq!(t_left, /// assert_eq!(t_left,
/// Tree::new(1, /// Tree::new(1,
/// Some(Box::new(Tree::new(2, None, None))), /// Some(Box::new(Tree::new(2, None, None))),
/// None)); /// None));
/// ///
/// // A tree with only a right node. /// // A tree with only a right node.
/// let t_right = btree!(1, , btree!(3)); /// let t_right = btree!(1, , btree!(3));
/// assert_eq!(t_right, /// assert_eq!(t_right,
/// Tree::new(1, /// Tree::new(1,
/// None, /// None,
/// Some(Box::new(Tree::new(3, None, None))))); /// Some(Box::new(Tree::new(3, None, None)))));
/// ///
/// // A tree with no child nodes. /// // A tree with no child nodes.
/// let t_single = btree!(1); /// let t_single = btree!(1);
/// assert_eq!(t_single, /// assert_eq!(t_single,
/// Tree::new(1, /// Tree::new(1,
/// None, /// None,
/// None)); /// None));
/// # } /// # }
/// ``` /// ```
@ -102,12 +102,12 @@ macro_rules! btree {
impl<T> Tree<T> { impl<T> Tree<T> {
/// Constructs a new [`Tree`] object /// Constructs a new [`Tree`] object
/// ///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use gemla::tree::*; /// use gemla::tree::*;
/// ///
/// let t = Tree::new(1, None, None); /// let t = Tree::new(1, None, None);
/// assert_eq!(t, Tree { /// assert_eq!(t, Tree {
/// val: 1, /// val: 1,
@ -120,16 +120,16 @@ impl<T> Tree<T> {
} }
/// Obtains the height of the longest branch in a [`Tree`] /// Obtains the height of the longest branch in a [`Tree`]
/// ///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use gemla::tree::*; /// use gemla::tree::*;
/// use gemla::btree; /// use gemla::btree;
/// ///
/// let t = /// let t =
/// btree!("a", /// btree!("a",
/// btree!("aa", /// btree!("aa",
/// btree!("aaa"),), /// btree!("aaa"),),
/// btree!("ab")); /// btree!("ab"));
/// assert_eq!(t.height(), 3); /// assert_eq!(t.height(), 3);