pub struct File<T: Serialize + DeserializeOwned + Default> { /* private fields */ }Expand description
A state file.
This provides strongly typed access to a JSON file wrapped in a RwLock
that writes to disk once write access is dropped.
use statefile::File;
use serde::{Deserialize, Serialize};
// you must specify at least these derivations
#[derive(Serialize, Deserialize, Default)]
struct State {
foo: String,
bar: u32,
}
#[tokio::main]
async fn main() {
// create or open state file at given path
let mut state = File::<State>::new("mystate.json").await.unwrap();
// if the file doesn't exist or is empty, State will contain default values
let mut write_guard = state.write().await; // grab write access
write_guard.foo = "".to_string();
write_guard.bar = 10;
drop(write_guard); // write state by explicitly dropping
}Implementations§
Source§impl<T: Serialize + DeserializeOwned + Default> File<T>
impl<T: Serialize + DeserializeOwned + Default> File<T>
Sourcepub async fn new(path: impl AsRef<Path> + Copy) -> Result<Self, Box<dyn Error>>
pub async fn new(path: impl AsRef<Path> + Copy) -> Result<Self, Box<dyn Error>>
Create a new state file at the given path
Sourcepub async fn read(&self) -> RwLockReadGuard<'_, T>
pub async fn read(&self) -> RwLockReadGuard<'_, T>
Locks this state file with shared read access, causing the current task to yield until the lock has been acquired.
Sourcepub async fn write(&self) -> WriteGuard<'_, T>
pub async fn write(&self) -> WriteGuard<'_, T>
Locks this state file with exclusive write access, causing the current task to yield until the lock has been acquired.
Auto Trait Implementations§
impl<T> !Freeze for File<T>
impl<T> !RefUnwindSafe for File<T>
impl<T> Send for File<T>where
T: Send,
impl<T> Sync for File<T>
impl<T> Unpin for File<T>where
T: Unpin,
impl<T> UnwindSafe for File<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more