io: add storage helper

Use bincode+zstd to serialize data structures for temporary storage.
This commit is contained in:
Matthias Schiffer 2023-02-28 00:44:49 +01:00
parent f47b38b2ca
commit 21fd3a42ca
Signed by: neocturne
GPG key ID: 16EF3F64CB201D9C
4 changed files with 84 additions and 0 deletions

View file

@ -1,2 +1,3 @@
pub mod data;
pub mod region;
pub mod storage;

22
src/io/storage.rs Normal file
View file

@ -0,0 +1,22 @@
use std::{
fs::File,
io::{BufWriter, Write},
path::Path,
};
use anyhow::{Context, Result};
use serde::Serialize;
pub fn write<T: Serialize>(path: &Path, value: &T) -> Result<()> {
(|| -> Result<()> {
let file = File::create(path)?;
let writer = BufWriter::new(file);
let mut compressor = zstd::Encoder::new(writer, 1)?;
bincode::serialize_into(&mut compressor, value)?;
let writer = compressor.finish()?;
let mut file = writer.into_inner()?;
file.flush()?;
Ok(())
})()
.with_context(|| format!("Failed to write file {}", path.display()))
}