Skip to main content

CancelToken

Struct CancelToken 

Source
pub struct CancelToken { /* private fields */ }
Expand description

Cooperative cancellation handle for long-running MTP operations.

Cheap to clone (Arc-backed). Send + Sync. Once cancelled, the token stays cancelled (no reset). Construct a fresh CancelToken per logical operation.

A cheap-to-clone handle that callers pass into operations like Storage::list_objects so they can be aborted from another task. The operation checks the token between USB roundtrips; when set, it returns Error::Cancelled within one roundtrip’s worth of latency instead of running to completion.

§When to use this

MTP list and recursive delete on large folders consist of many small per-object USB transactions (GetObjectInfo per handle). A 1k-photo /DCIM/Camera listing on Android can take 15+ seconds over USB 2.0. Without cooperative cancel, a user-initiated cancel only stops issuing new transactions after the current bulk call’s entire for-loop completes. By then the device may already be wedged from a follow-up op.

CancelToken gives every per-handle iteration a fast way to bail.

§Mid-data-phase cancel

For streaming downloads, see FileDownload::cancel; that path uses the USB Still Image Class (SIC) class-cancel mechanism to abort a long bulk-IN transfer mid-stream. Per-handle list/delete operations don’t need that: each GetObjectInfo / DeleteObject USB roundtrip completes in milliseconds, so checking the token between roundtrips is sufficient and safe (no half-finished transfer to drain).

§Example

use mtp_rs::{CancelToken, mtp::MtpDevice};

let device = MtpDevice::open_first().await?;
let storages = device.storages().await?;
let storage = &storages[0];

let cancel = CancelToken::new();

// Fire the cancel from another task after 500 ms.
let cancel_for_task = cancel.clone();
tokio::spawn(async move {
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    cancel_for_task.cancel();
});

match storage.list_objects_with_cancel(None, Some(&cancel)).await {
    Ok(objects) => println!("Listed {} objects", objects.len()),
    Err(mtp_rs::Error::Cancelled) => println!("Cancelled mid-listing"),
    Err(e) => return Err(e),
}

Implementations§

Source§

impl CancelToken

Source

pub fn new() -> Self

Creates a fresh, not-yet-cancelled token.

Source

pub fn from_arc(cancelled: Arc<AtomicBool>) -> Self

Wraps an externally-owned Arc<AtomicBool>.

Use this when the caller already has its own cancellation flag (for example, threaded through several layers from a host application) and wants the same atomic to drive an mtp-rs operation, with no second polling task. The token shares ownership of the inner atomic, so flipping the original flag flips the token (and vice versa).

Source

pub fn cancel(&self)

Marks the token as cancelled. Subsequent is_cancelled calls return true. Cooperative consumers (operations holding Option<&CancelToken>) bail at their next check point with Err(Error::Cancelled).

Idempotent: calling on an already-cancelled token is a no-op.

Source

pub fn is_cancelled(&self) -> bool

Returns true once cancel has been called on this token (or any clone of it).

Trait Implementations§

Source§

impl Clone for CancelToken

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CancelToken

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CancelToken

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more