rqbit/crates/librqbit/src/storage/timing.rs

87 lines
2.3 KiB
Rust
Raw Normal View History

2024-05-01 21:09:26 +01:00
use super::{StorageFactory, TorrentStorage};
2024-05-01 22:00:00 +01:00
pub struct TimingStorageFactory<U> {
2024-05-01 21:09:26 +01:00
name: String,
2024-05-01 22:00:00 +01:00
underlying_factory: U,
2024-05-01 21:09:26 +01:00
}
2024-05-01 22:00:00 +01:00
impl<U> TimingStorageFactory<U> {
pub fn new(name: String, underlying: U) -> Self {
2024-05-01 21:09:26 +01:00
Self {
name,
underlying_factory: underlying,
}
}
}
2024-05-01 22:00:00 +01:00
impl<U: StorageFactory> StorageFactory for TimingStorageFactory<U> {
2024-05-01 22:14:34 +01:00
type Storage = TimingStorage<U::Storage>;
fn init_storage(&self, info: &crate::ManagedTorrentInfo) -> anyhow::Result<Self::Storage> {
Ok(TimingStorage {
2024-05-01 21:09:26 +01:00
name: self.name.clone(),
underlying: self.underlying_factory.init_storage(info)?,
2024-05-01 22:14:34 +01:00
})
2024-05-01 21:09:26 +01:00
}
}
2024-05-01 22:14:34 +01:00
pub struct TimingStorage<U> {
2024-05-01 21:09:26 +01:00
name: String,
2024-05-01 22:00:00 +01:00
underlying: U,
2024-05-01 21:09:26 +01:00
}
macro_rules! timeit {
($name:expr, $op:expr, $($rest:tt),*) => {
{
let start = std::time::Instant::now();
let r = $op;
let elapsed = start.elapsed();
2024-05-01 21:13:11 +01:00
tracing::debug!(name = $name, $($rest),*, elapsed_micros=elapsed.as_micros(), "timeit");
2024-05-01 21:09:26 +01:00
r
}
};
}
2024-05-01 22:00:00 +01:00
impl<U: TorrentStorage> TorrentStorage for TimingStorage<U> {
2024-05-01 21:09:26 +01:00
fn pread_exact(&self, file_id: usize, offset: u64, buf: &mut [u8]) -> anyhow::Result<()> {
let storage = &self.name;
2024-05-01 21:17:05 +01:00
let len = buf.len();
2024-05-01 21:09:26 +01:00
timeit!(
"pread_exact",
self.underlying.pread_exact(file_id, offset, buf),
file_id,
offset,
2024-05-01 21:17:05 +01:00
storage,
len
2024-05-01 21:09:26 +01:00
)
}
fn pwrite_all(&self, file_id: usize, offset: u64, buf: &[u8]) -> anyhow::Result<()> {
let storage = &self.name;
2024-05-01 21:17:05 +01:00
let len = buf.len();
2024-05-01 21:09:26 +01:00
timeit!(
"pwrite_all",
self.underlying.pwrite_all(file_id, offset, buf),
file_id,
offset,
2024-05-01 21:17:05 +01:00
storage,
len
2024-05-01 21:09:26 +01:00
)
}
fn remove_file(&self, file_id: usize, filename: &std::path::Path) -> anyhow::Result<()> {
self.underlying.remove_file(file_id, filename)
}
fn ensure_file_length(&self, file_id: usize, length: u64) -> anyhow::Result<()> {
self.underlying.ensure_file_length(file_id, length)
}
fn take(&self) -> anyhow::Result<Box<dyn TorrentStorage>> {
2024-05-01 22:00:00 +01:00
Ok(Box::new(TimingStorage {
2024-05-01 21:09:26 +01:00
underlying: self.underlying.take()?,
name: self.name.clone(),
}))
}
}