| Crates.io | save-load-traits |
| lib.rs | save-load-traits |
| version | 0.2.2 |
| created_at | 2025-02-27 02:31:45.033+00 |
| updated_at | 2025-07-13 10:17:11.451072+00 |
| description | Provides traits for saving and loading objects asynchronously to and from files and directories. |
| homepage | |
| repository | https://github.com/klebs6/klebs-general |
| max_upload_size | |
| id | 1571168 |
| size | 70,518 |
The save-load-traits crate provides traits for saving and loading objects asynchronously to and from files and directories. It also includes a blanket implementation for loading objects from a directory using the LoadFromFile trait.
LoadFromFile trait.The SaveToFile trait allows objects to be saved asynchronously to a file.
#[async_trait]
pub trait SaveToFile {
type Error;
async fn save_to_file(&self, filename: impl AsRef<Path> + Send) -> Result<(), Self::Error>;
}
The LoadFromFile trait allows objects to be loaded asynchronously from a file.
#[async_trait]
pub trait LoadFromFile: Sized {
type Error;
async fn load_from_file(filename: impl AsRef<Path> + Send) -> Result<Self, Self::Error>;
}
The LoadFromDirectory trait is designed for asynchronously loading objects from a directory. It provides a blanket implementation for any type that implements LoadFromFile.
#[async_trait]
pub trait LoadFromDirectory: Sized {
type Error;
async fn load_from_directory(
dir: impl AsRef<Path> + Send,
) -> Result<Vec<Self>, Self::Error>;
}
This crate uses custom error types to handle I/O and JSON parsing errors:
error_tree! {
pub enum SaveLoadError {
IoError(std::io::Error),
JsonParseError(JsonParseError),
InvalidDirectory { dir: PathBuf },
}
}
To save an object to a file asynchronously, implement the SaveToFile trait for the type:
let obj = YourStruct {};
obj.save_to_file("file.json").await?;
To load an object from a file asynchronously, implement the LoadFromFile trait for the type:
let obj = YourStruct::load_from_file("file.json").await?;
To load multiple objects from a directory, use the LoadFromDirectory trait:
let objects = YourStruct::load_from_directory("directory_path").await?;
This crate is licensed under the MIT License. See LICENSE for details.