refactor: split read_cache

This commit is contained in:
mokurin000
2025-08-02 19:41:49 +08:00
parent 9b53cb633c
commit 929e4641ea

View File

@@ -24,6 +24,27 @@ use bincode::{BorrowDecode, Encode, borrow_decode_from_slice};
use crate::{EARLY_QUIT, cache}; use crate::{EARLY_QUIT, cache};
pub fn read_cache<D>(
definition: TableDefinition<'_, u32, Vec<u8>>,
) -> Result<Vec<D>, Box<dyn snafu::Error>>
where
D: for<'d> BorrowDecode<'d, ()>,
{
let txn = cache::read_txn()?;
let table = cache::open_table_ro(&txn, definition)?;
let config =
bincode::config::Configuration::<bincode::config::LittleEndian>::default().with_no_limit();
Ok(table
.iter()?
.flatten()
.map(|d| borrow_decode_from_slice(&d.1.value(), config))
.flatten()
.map(|(value, _)| value)
.collect::<Vec<D>>())
}
pub fn dump_cache<D>( pub fn dump_cache<D>(
output_path: impl AsRef<Path>, output_path: impl AsRef<Path>,
definition: TableDefinition<'_, u32, Vec<u8>>, definition: TableDefinition<'_, u32, Vec<u8>>,
@@ -40,23 +61,10 @@ where
#[cfg(file_lock_ready)] #[cfg(file_lock_ready)]
file.try_lock()?; file.try_lock()?;
let txn = cache::read_txn()?; let data = read_cache::<D>(definition)?;
let table = cache::open_table_ro(&txn, definition)?;
let config =
bincode::config::Configuration::<bincode::config::LittleEndian>::default().with_no_limit();
let user_ids = table
.iter()?
.flatten()
.map(|d| borrow_decode_from_slice(&d.1.value(), config))
.flatten()
.map(|(value, _)| value)
.collect::<Vec<D>>();
let writer = BufWriter::new(file); let writer = BufWriter::new(file);
serde_json::to_writer(writer, &user_ids)?; serde_json::to_writer(writer, &data)?;
info!("dumped {} user id", user_ids.len()); info!("dumped {} user id", data.len());
Ok(()) Ok(())
} }