提交 08fb1e81 authored 作者: Serhij S's avatar Serhij S

state helpers

上级 1ccf3f34
...@@ -54,6 +54,8 @@ once_cell = { version = "1.19.0", optional = true } ...@@ -54,6 +54,8 @@ once_cell = { version = "1.19.0", optional = true }
parking_lot = { version = "0.12.3", optional = true } parking_lot = { version = "0.12.3", optional = true }
parking_lot_rt = { version = "0.12.1", optional = true } parking_lot_rt = { version = "0.12.1", optional = true }
quanta = { version = "=0.12.3", optional = true } quanta = { version = "=0.12.3", optional = true }
serde_json = "1.0.134"
rmp-serde = "1.3.0"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
parking_lot_rt = { version = "0.12.1" } parking_lot_rt = { version = "0.12.1" }
......
...@@ -107,6 +107,9 @@ pub mod supervisor; ...@@ -107,6 +107,9 @@ pub mod supervisor;
/// Real-time thread functions to work with [`supervisor::Supervisor`] and standalone, Linux only /// Real-time thread functions to work with [`supervisor::Supervisor`] and standalone, Linux only
pub mod thread_rt; pub mod thread_rt;
/// State helper functions
pub mod state;
/// The crate result type /// The crate result type
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
......
use std::{fs::File, io::Write, path::Path};
use serde::{de::DeserializeOwned, Serialize};
use crate::{Error, Result};
enum Format {
Json,
Msgpack,
}
impl Format {
fn from_path<P: AsRef<Path>>(path: P) -> Self {
match path
.as_ref()
.extension()
.map_or("", |ext| ext.to_str().unwrap())
{
"json" => Self::Json,
_ => Self::Msgpack,
}
}
}
/// Load the state from a file. If "json" extension is specified, the state is loaded in JSON
/// format. All errors, including missing state file, must be handled by the caller.
pub fn load<S: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<S> {
let format = Format::from_path(&path);
let file = File::open(&path)?;
let data = match format {
Format::Json => serde_json::from_reader(file).map_err(Error::failed)?,
Format::Msgpack => rmp_serde::from_read(file).map_err(Error::failed)?,
};
Ok(data)
}
/// Save the state to a file. If "json" extension is specified, the state is saved in JSON
/// format. Otherwise it is saved in MessagePack format.
pub fn save<S: Serialize, P: AsRef<Path>>(state: &S, path: P) -> Result<()> {
let format = Format::from_path(&path);
let mut file = File::create(&path)?;
let data = match format {
Format::Json => serde_json::to_vec(state).map_err(Error::failed)?,
Format::Msgpack => rmp_serde::to_vec_named(state).map_err(Error::failed)?,
};
file.write_all(&data)?;
Ok(())
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论