File

Struct File 

Source
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>

Source

pub async fn new(path: impl AsRef<Path> + Copy) -> Result<Self, Box<dyn Error>>

Create a new state file at the given path

Source

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.

Source

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>
where T: Send + Sync,

§

impl<T> Unpin for File<T>
where T: Unpin,

§

impl<T> UnwindSafe for File<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.