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);
@ -67,6 +69,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 {
@ -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,9 +113,13 @@ 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!(
file,
"{}",
serde_json::to_string(&self.val).map_err(|e| e.to_string())?
)
.or_else(|_| Err(String::from("Unable to write to file.")))?; .or_else(|_| Err(String::from("Unable to write to file.")))?;
Ok(()) Ok(())
@ -123,6 +134,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 {
@ -138,7 +150,7 @@ 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);
@ -168,6 +180,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 {
@ -183,7 +196,7 @@ 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);
@ -210,7 +223,7 @@ 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`
/// ///
@ -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,
@ -238,7 +252,7 @@ where
/// 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)
@ -252,7 +266,7 @@ where
/// ///
/// 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;