use crate::mtp::backend::{DownloadBody, MtpBackend};
use crate::mtp::{Error, ObjectHandle};
use bytes::Bytes;
use std::ops::ControlFlow;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Progress {
pub bytes_transferred: u64,
pub total_bytes: Option<u64>,
}
impl Progress {
#[must_use]
pub fn percent(&self) -> f64 {
self.fraction() * 100.0
}
#[must_use]
pub fn fraction(&self) -> f64 {
self.total_bytes.map_or(1.0, |total| {
if total == 0 {
1.0
} else {
self.bytes_transferred as f64 / total as f64
}
})
}
}
pub const DEFAULT_CANCEL_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);
#[must_use = "dropping a FileDownload mid-transfer may corrupt the USB session; \
consume it fully or call cancel()"]
pub struct FileDownload {
size: u64,
bytes_received: u64,
body: Box<dyn DownloadBody>,
}
impl FileDownload {
pub(crate) fn new(size: u64, body: Box<dyn DownloadBody>) -> Self {
Self {
size,
bytes_received: 0,
body,
}
}
#[must_use]
pub fn size(&self) -> u64 {
self.size
}
#[must_use]
pub fn bytes_received(&self) -> u64 {
self.bytes_received
}
#[must_use]
pub fn progress(&self) -> f64 {
if self.size == 0 {
1.0
} else {
self.bytes_received as f64 / self.size as f64
}
}
pub async fn cancel(&mut self, idle_timeout: std::time::Duration) -> Result<(), Error> {
self.body.cancel(idle_timeout).await
}
pub async fn next_chunk(&mut self) -> Option<Result<Bytes, Error>> {
match self.body.next_chunk().await {
Some(Ok(bytes)) => {
self.bytes_received += bytes.len() as u64;
Some(Ok(bytes))
}
other => other,
}
}
pub async fn collect_with_progress<F>(mut self, mut on_progress: F) -> Result<Vec<u8>, Error>
where
F: FnMut(Progress) -> ControlFlow<()>,
{
let mut data = Vec::with_capacity(self.size as usize);
while let Some(result) = self.next_chunk().await {
let chunk = result?;
data.extend_from_slice(&chunk);
let progress = Progress {
bytes_transferred: self.bytes_received,
total_bytes: Some(self.size),
};
if let ControlFlow::Break(()) = on_progress(progress) {
self.body.cancel(DEFAULT_CANCEL_TIMEOUT).await?;
return Err(Error::Cancelled);
}
}
Ok(data)
}
pub async fn collect(mut self) -> Result<Vec<u8>, Error> {
let mut data = Vec::with_capacity(self.size as usize);
while let Some(result) = self.next_chunk().await {
data.extend_from_slice(&result?);
}
Ok(data)
}
}
pub const DEFAULT_DOWNLOAD_WINDOW: u32 = 8 * 1024 * 1024;
pub struct WindowedDownload {
backend: Arc<dyn MtpBackend>,
handle: ObjectHandle,
total_size: u64,
offset: u64,
window_size: u32,
}
impl WindowedDownload {
pub(crate) fn new(
backend: Arc<dyn MtpBackend>,
handle: ObjectHandle,
total_size: u64,
start_offset: u64,
window_size: u32,
) -> Self {
Self {
backend,
handle,
total_size,
offset: start_offset,
window_size: window_size.max(1),
}
}
#[must_use]
pub fn size(&self) -> u64 {
self.total_size
}
#[must_use]
pub fn offset(&self) -> u64 {
self.offset
}
pub async fn next_window(&mut self) -> Option<Result<Vec<u8>, Error>> {
if self.offset >= self.total_size {
return None;
}
let remaining = self.total_size - self.offset;
let want = u32::try_from(remaining.min(u64::from(self.window_size))).unwrap_or(u32::MAX);
match self
.backend
.read_range(self.handle, self.offset, Some(want))
.await
{
Ok(bytes) => {
if bytes.is_empty() {
return Some(Err(Error::invalid_data(format!(
"device returned 0 bytes at offset {} of {} (expected up to {want}); \
treating as a stall rather than end-of-file",
self.offset, self.total_size
))));
}
self.offset += bytes.len() as u64;
Some(Ok(bytes))
}
Err(e) => Some(Err(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_calculations() {
let cases = [
(50, Some(100), 50.0, 0.5),
(100, Some(100), 100.0, 1.0),
(25, Some(100), 25.0, 0.25),
(0, Some(0), 100.0, 1.0), (50, None, 100.0, 1.0), ];
for (transferred, total, expected_pct, expected_frac) in cases {
let p = Progress {
bytes_transferred: transferred,
total_bytes: total,
};
assert_eq!(
p.percent(),
expected_pct,
"percent failed for {transferred}/{total:?}"
);
assert_eq!(
p.fraction(),
expected_frac,
"fraction failed for {transferred}/{total:?}"
);
}
let large = Progress {
bytes_transferred: u64::MAX / 2,
total_bytes: Some(u64::MAX),
};
let frac = large.fraction();
assert!(frac > 0.49 && frac < 0.51);
}
}