Skip to main content

ResumeData

Struct ResumeData 

Source
pub struct ResumeData {
Show 18 fields pub gid: String, pub uris: Vec<UriState>, pub total_length: u64, pub completed_length: u64, pub uploaded_length: u64, pub bitfield: Vec<u8>, pub num_pieces: Option<u32>, pub piece_length: Option<u32>, pub status: String, pub error_message: Option<String>, pub last_download_time: u64, pub created_at: u64, pub output_path: Option<String>, pub checksum: Option<ChecksumInfo>, pub options: HashMap<String, String>, pub resume_offset: Option<u64>, pub bt_info_hash: Option<String>, pub bt_saved_metadata_path: Option<String>,
}
Expand description

Complete download state for persistence across process restarts

This structure captures all necessary information to fully restore a download session, including progress state, URI history, error context, and protocol- specific metadata.

§Examples

use aria2_core::engine::resume_data::{ResumeData, UriState};

let data = ResumeData {
    gid: "abc123".to_string(),
    uris: vec![
        UriState {
            uri: "http://example.com/file.zip".to_string(),
            tried: true,
            used: true,
            last_result: Some("ok".to_string()),
            speed_bytes_per_sec: Some(1024 * 1024),
        },
    ],
    total_length: 1024 * 1024 * 100,
    completed_length: 1024 * 1024 * 50,
    bitfield: vec![],
    status: "active".to_string(),
    error_message: None,
    last_download_time: 1700000000u64,
    created_at: 1699900000u64,
    output_path: Some("/downloads/file.zip".to_string()),
    checksum: None,
    bt_info_hash: None,
    bt_saved_metadata_path: None,
};

let json = data.serialize().expect("Serialization failed");
assert!(json.contains("abc123"));

Fields§

§gid: String

Unique global identifier for this download task

§uris: Vec<UriState>

All source URIs with their individual status tracking

§total_length: u64

Total size of the download in bytes (0 if unknown)

§completed_length: u64

Number of bytes already downloaded and verified

§uploaded_length: u64

Number of bytes uploaded (for BitTorrent seeding)

§bitfield: Vec<u8>

Per-piece completion bitmap (BitTorrent only, empty for HTTP/FTP)

§num_pieces: Option<u32>

Total number of pieces in torrent (BitTorrent only)

§piece_length: Option<u32>

Size of each piece in bytes (BitTorrent only)

§status: String

Current download status: “active”, “paused”, “error”, “complete”, “waiting”

§error_message: Option<String>

Error message if status is “error”

§last_download_time: u64

Unix timestamp (seconds) of last download activity

§created_at: u64

Unix timestamp (seconds) when this download was created

§output_path: Option<String>

Output file path (relative or absolute)

§checksum: Option<ChecksumInfo>

Checksum verification information

§options: HashMap<String, String>

Persisted download options needed for restoration

§resume_offset: Option<u64>

File offset where HTTP/FTP download should resume

§bt_info_hash: Option<String>

Torrent info hash in hex format (40 characters)

§bt_saved_metadata_path: Option<String>

Path to saved .torrent metadata file

Implementations§

Source§

impl ResumeData

Source

pub fn serialize(&self) -> Result<String, String>

Serialize ResumeData to pretty-printed JSON string

Produces human-readable JSON with 2-space indentation for easy debugging and manual inspection of .aria2 files.

§Returns
  • Ok(String) - JSON string representation
  • Err(String) - Serialization error with context
§Examples
let data = ResumeData::default();
let json = data.serialize().unwrap();
assert!(json.contains("waiting")); // default status
Source

pub fn deserialize(json_str: &str) -> Result<Self, String>

Deserialize ResumeData from JSON string

Parses a JSON string produced by serialize() back into a ResumeData instance with full field restoration.

§Arguments
  • json_str - JSON string to deserialize
§Returns
  • Ok(ResumeData) - Deserialized data structure
  • Err(String) - Parse error with context message
§Errors

Returns error if JSON is malformed, missing required fields, or contains invalid data types.

§Examples
let json = r#"{"gid":"test","uris":[],"total_length":0,"completed_length":0,"uploaded_length":0,"bitfield":[],"num_pieces":null,"piece_length":null,"status":"paused","error_message":null,"last_download_time":0,"created_at":0,"output_path":null,"checksum":null,"options":{},"resume_offset":null,"bt_info_hash":null,"bt_saved_metadata_path":null}"#;
let data = ResumeData::deserialize(json).unwrap();
assert_eq!(data.gid, "test");
Source

pub fn save_to_file(&self, path: &Path) -> Result<(), String>

Save ResumeData to a file atomically

Writes JSON to a temporary file first, then renames to target path. This ensures existing files are never corrupted if write fails midway.

§Arguments
  • path - Target file path (typically ending in .aria2)
§Errors

Returns error if serialization fails, file creation fails, or rename fails.

§Examples
let data = ResumeData::default();
data.save_to_file(Path::new("/tmp/download.aria2")).unwrap();
Source

pub fn load_from_file(path: &Path) -> Result<Option<Self>, String>

Load ResumeData from file, returning None if file doesn’t exist

Gracefully handles missing files (returns Ok(None)) and provides detailed error messages for corrupt or unreadable files.

§Arguments
  • path - Path to .aria2 resume file
§Returns
  • Ok(Some(ResumeData)) - Successfully loaded data
  • Ok(None) - File does not exist (not an error)
  • Err(String) - File exists but cannot be read/parsed
§Examples
match ResumeData::load_from_file(Path::new("download.aria2")) {
    Ok(Some(data)) => println!("Loaded: {} bytes done", data.completed_length),
    Ok(None) => println!("No saved state"),
    Err(e) => eprintln!("Error: {}", e),
}
Source

pub fn completion_ratio(&self) -> f64

Calculate download completion ratio (0.0 to 1.0)

Returns 0.0 if total_length is 0 (unknown size).

Source

pub fn is_bit_torrent(&self) -> bool

Check if this download is a BitTorrent transfer

Returns true if any BT-specific fields are populated.

Check if this download uses Metalink mirrors

Returns true if multiple URIs are present (mirror configuration).

Source

pub fn get_filename(&self) -> String

Generate standard .aria2 filename from GID

Format: {gid}.aria2

Source

pub fn validate_for_restore(&self) -> Result<(), String>

Validate resume data integrity before restoration

Checks that critical fields are consistent and valid for restoration. Returns Ok(()) if data is valid, Err with description otherwise.

Source

pub fn detect_protocol(&self) -> &str

Detect download protocol type from URI patterns

Returns “http”, “ftp”, “bt”, “metalink”, or “unknown”.

Trait Implementations§

Source§

impl Clone for ResumeData

Source§

fn clone(&self) -> ResumeData

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 ResumeData

Source§

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

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

impl Default for ResumeData

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for ResumeData

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl ResumeDataExt for ResumeData

Source§

async fn from_request_group(group: &RequestGroup) -> Result<Self, String>

Create ResumeData from a RequestGroup (async, reads state) Read more
Source§

fn to_restore_components( &self, ) -> (String, Vec<String>, HashMap<String, String>, RestoreState)

Convert ResumeData back to restorable state components Read more
Source§

impl Serialize for ResumeData

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. 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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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