io/storage: add read() function

This commit is contained in:
Matthias Schiffer 2023-03-03 19:20:56 +01:00
parent dda81546de
commit 657d8af8a7
Signed by: neocturne
GPG key ID: 16EF3F64CB201D9C

View file

@ -1,11 +1,11 @@
use std::{ use std::{
fs::File, fs::File,
io::{BufWriter, Write}, io::{BufReader, BufWriter, Write},
path::Path, path::Path,
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use serde::Serialize; use serde::{de::DeserializeOwned, Serialize};
pub fn write<T: Serialize>(path: &Path, value: &T) -> Result<()> { pub fn write<T: Serialize>(path: &Path, value: &T) -> Result<()> {
(|| -> Result<()> { (|| -> Result<()> {
@ -20,3 +20,13 @@ pub fn write<T: Serialize>(path: &Path, value: &T) -> Result<()> {
})() })()
.with_context(|| format!("Failed to write file {}", path.display())) .with_context(|| format!("Failed to write file {}", path.display()))
} }
pub fn read<T: DeserializeOwned>(path: &Path) -> Result<T> {
(|| -> Result<T> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let decompressor = zstd::Decoder::new(reader)?;
Ok(bincode::deserialize_from(decompressor)?)
})()
.with_context(|| format!("Failed to read file {}", path.display()))
}