pub struct FileDownload { /* private fields */ }Expand description
A file download in progress with true USB streaming.
This struct wraps the low-level ReceiveStream and provides convenient
methods for tracking progress. Data is streamed directly from USB as
chunks arrive, without buffering the entire file in memory.
§Important
The MTP session is locked while this download is active. You must either
consume the entire download or call cancel() before
dropping it. Dropping mid-download without cancelling corrupts the USB
session.
§Example
use mtp_rs::mtp::MtpDevice;
use mtp_rs::ObjectHandle;
use tokio::io::AsyncWriteExt;
let mut download = storage.download_stream(handle).await?;
println!("Downloading {} bytes...", download.size());
while let Some(chunk) = download.next_chunk().await {
let bytes = chunk?;
file.write_all(&bytes).await?;
println!("Progress: {:.1}%", download.progress() * 100.0);
}Implementations§
Source§impl FileDownload
impl FileDownload
Sourcepub fn bytes_received(&self) -> u64
pub fn bytes_received(&self) -> u64
Bytes received so far.
Sourcepub async fn cancel(&mut self, idle_timeout: Duration) -> Result<(), Error>
pub async fn cancel(&mut self, idle_timeout: Duration) -> Result<(), Error>
Cancel the in-progress download.
Uses the USB Still Image Class cancel mechanism to stop the transfer and drain remaining data, leaving the session clean for the next operation.
The idle_timeout controls how long to wait during pipe drain before
assuming the pipe is clear. 1–2 seconds is typically sufficient.
If the download is already complete, this is a no-op.
Sourcepub async fn next_chunk(&mut self) -> Option<Result<Bytes, Error>>
pub async fn next_chunk(&mut self) -> Option<Result<Bytes, Error>>
Get the next chunk of data from USB.
Returns None when the download is complete.
Sourcepub async fn collect_with_progress<F>(
self,
on_progress: F,
) -> Result<Vec<u8>, Error>
pub async fn collect_with_progress<F>( self, on_progress: F, ) -> Result<Vec<u8>, Error>
Consume the download and iterate with a progress callback.
Calls on_progress after each chunk. Return ControlFlow::Break(())
to cancel the download.
§Example
use mtp_rs::mtp::MtpDevice;
use mtp_rs::ObjectHandle;
use std::ops::ControlFlow;
let download = storage.download_stream(handle).await?;
let data = download.collect_with_progress(|progress| {
println!("{:.1}%", progress.percent());
ControlFlow::Continue(())
}).await?;