Skip to main content

zsync_rs/
assembly.rs

1//! Assembling a target file from local sources and HTTP ranges.
2//!
3//! A transfer runs in three steps on one [`ZsyncAssembly`]. Local files are
4//! scanned first, and every block they contain is copied into a temporary
5//! file beside the output. The blocks still missing are then downloaded and
6//! verified one at a time. Last, [`ZsyncAssembly::complete`] checks the whole
7//! file against the control file's SHA-1 and renames it into place.
8//!
9//! The temporary file is the output path with its extension replaced by
10//! `zsync-tmp`. Dropping the assembly before it completes removes it, so a
11//! failed or abandoned transfer leaves nothing behind.
12
13use std::fs::{File, OpenOptions};
14use std::io::{Read, Seek, SeekFrom, Write};
15use std::path::Path;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicBool, Ordering};
18
19use crate::checksum::calc_sha1_stream;
20use crate::control::ControlFile;
21use crate::http::{
22    DEFAULT_RANGE_GAP_THRESHOLD, HttpClient, byte_ranges_from_block_ranges, merge_byte_ranges,
23};
24use crate::matcher::BlockMatcher;
25use crate::matcher::MatchError;
26
27const STREAM_CHUNK_SIZE: usize = 1024 * 1024;
28
29/// Why a step of an assembly failed.
30#[derive(Debug, thiserror::Error)]
31pub enum AssemblyError {
32    /// Reading a source file, or writing, truncating or renaming the
33    /// temporary file, failed.
34    #[error("IO error: {0}")]
35    Io(#[from] std::io::Error),
36    /// Fetching the control file or a block range failed.
37    #[error("HTTP error: {0}")]
38    Http(#[from] crate::http::HttpError),
39    /// The block matcher failed.
40    #[error("Matcher error: {0}")]
41    Matcher(#[from] MatchError),
42    /// The assembly cannot do what was asked of it, such as completing while
43    /// blocks are still missing.
44    #[error("Control file error: {0}")]
45    Control(String),
46    /// The assembled file's SHA-1 differs from the control file's.
47    #[error("Checksum mismatch: expected {expected}, got {actual}")]
48    ChecksumMismatch {
49        /// The digest from the control file, as written there.
50        expected: String,
51        /// The digest of the assembled file, in lowercase hex.
52        actual: String,
53    },
54    /// The control file lists no URL to download blocks from.
55    #[error("No URLs available")]
56    NoUrls,
57    /// The abort flag was raised during a scan or a download.
58    #[error("Aborted")]
59    Aborted,
60}
61
62/// Reports whether the caller has raised the abort flag.
63///
64/// Free function rather than a method so the scan and download loops can poll
65/// it while still holding a mutable borrow of the assembly.
66fn aborted(flag: &Option<Arc<AtomicBool>>) -> bool {
67    flag.as_ref().is_some_and(|f| f.load(Ordering::Relaxed))
68}
69
70/// A callback receiving `(done_bytes, total_bytes)`, as
71/// [`ZsyncAssembly::progress`] reports them.
72pub type ProgressCallback = Box<dyn Fn(u64, u64) + Send + Sync>;
73
74/// One transfer of a target file, from a control file to the finished output.
75pub struct ZsyncAssembly {
76    control: ControlFile,
77    base_url: Option<String>,
78    matcher: BlockMatcher,
79    http: HttpClient,
80    output_path: std::path::PathBuf,
81    temp_path: std::path::PathBuf,
82    file: Option<File>,
83    range_gap_threshold: u64,
84    progress_callback: Option<ProgressCallback>,
85    abort_flag: Option<Arc<AtomicBool>>,
86}
87
88impl ZsyncAssembly {
89    /// Assemble the target `control` describes into `output_path`.
90    ///
91    /// There is no base URL, so the control file's URLs must be absolute.
92    /// Nothing is written until a block is found or downloaded.
93    pub fn new(control: ControlFile, output_path: &Path) -> Result<Self, AssemblyError> {
94        Self::with_base_url(control, output_path, None)
95    }
96
97    /// Assemble with relative control file URLs resolved against `base_url`.
98    ///
99    /// The base is joined as given, so for a directory it should end in `/`.
100    pub fn with_base_url(
101        control: ControlFile,
102        output_path: &Path,
103        base_url: Option<&str>,
104    ) -> Result<Self, AssemblyError> {
105        Self::with_client(control, output_path, base_url, HttpClient::new())
106    }
107
108    /// Assemble using a caller-supplied HTTP client.
109    ///
110    /// The client carries the transport policy for every range request the
111    /// assembly makes, so an embedder that needs its own TLS roots or that
112    /// must refuse a redirect to plain HTTP can set it once here.
113    pub fn with_client(
114        control: ControlFile,
115        output_path: &Path,
116        base_url: Option<&str>,
117        http: HttpClient,
118    ) -> Result<Self, AssemblyError> {
119        let matcher = BlockMatcher::new(&control);
120        let temp_path = output_path.with_extension("zsync-tmp");
121
122        Ok(Self {
123            control,
124            base_url: base_url.map(|s| s.to_string()),
125            matcher,
126            http,
127            output_path: output_path.to_path_buf(),
128            temp_path,
129            file: None,
130            range_gap_threshold: DEFAULT_RANGE_GAP_THRESHOLD,
131            progress_callback: None,
132            abort_flag: None,
133        })
134    }
135
136    /// Fetch the control file at `control_url` and assemble into
137    /// `output_path`.
138    ///
139    /// Relative URLs in the control file resolve against `control_url`'s
140    /// directory.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`AssemblyError::Http`] when the control file cannot be
145    /// fetched or does not parse.
146    pub fn from_url(control_url: &str, output_path: &Path) -> Result<Self, AssemblyError> {
147        Self::from_url_with_client(control_url, output_path, HttpClient::new())
148    }
149
150    /// Fetch the control file and assemble, both using `http`.
151    ///
152    /// The same client serves the control-file fetch and every subsequent
153    /// range request, so one policy covers the whole transfer.
154    pub fn from_url_with_client(
155        control_url: &str,
156        output_path: &Path,
157        http: HttpClient,
158    ) -> Result<Self, AssemblyError> {
159        let control = http.fetch_control_file(control_url)?;
160        let base_url = extract_base_url(control_url);
161        Self::with_client(control, output_path, Some(&base_url), http)
162    }
163
164    /// Sets how many known bytes may separate two needed ranges before they
165    /// are fetched with separate requests.
166    ///
167    /// Ranges closer than this are fetched as one, downloading the gap again
168    /// to save a round trip. The default is
169    /// [`DEFAULT_RANGE_GAP_THRESHOLD`].
170    pub fn set_range_gap_threshold(&mut self, threshold: u64) {
171        self.range_gap_threshold = threshold;
172    }
173
174    /// Sets a flag polled during the scan and download loops.
175    ///
176    /// Once the caller raises it, the running operation stops at the next
177    /// chunk boundary and returns [`AssemblyError::Aborted`], so a long
178    /// transfer can be cancelled without waiting for it to finish.
179    pub fn set_abort_flag(&mut self, flag: Arc<AtomicBool>) {
180        self.abort_flag = Some(flag);
181    }
182
183    /// Sets a callback to run after each block is downloaded and verified.
184    ///
185    /// It receives the values [`Self::progress`] returns at that point, and
186    /// runs on the thread calling [`Self::download_missing_blocks`], so a slow
187    /// callback slows the download. Blocks found in local files do not
188    /// trigger it.
189    pub fn set_progress_callback<F>(&mut self, callback: F)
190    where
191        F: Fn(u64, u64) + Send + Sync + 'static,
192    {
193        self.progress_callback = Some(Box::new(callback));
194    }
195
196    fn report_progress(&self) {
197        if let Some(ref cb) = self.progress_callback {
198            let (done, total) = self.progress();
199            cb(done, total);
200        }
201    }
202
203    /// Bytes of the target known so far, and the target's length.
204    ///
205    /// The count is known blocks times the block size, capped at the length.
206    pub fn progress(&self) -> (u64, u64) {
207        let total = self.control.length;
208        let got = self.matcher.blocks_todo();
209        let blocks_done = self.matcher.total_blocks() - got;
210        let done_bytes = (blocks_done * self.control.blocksize) as u64;
211        (done_bytes.min(total), total)
212    }
213
214    /// Whether every block of the target is known.
215    pub fn is_complete(&self) -> bool {
216        self.matcher.is_complete()
217    }
218
219    /// The block size the control file declares.
220    ///
221    /// Progress consumers need it to convert between the block counts that
222    /// [`Self::block_stats`] reports and the byte counts in [`Self::progress`].
223    pub fn blocksize(&self) -> usize {
224        self.control.blocksize
225    }
226
227    /// Blocks known so far, and the target's total block count.
228    pub fn block_stats(&self) -> (usize, usize) {
229        let total = self.matcher.total_blocks();
230        let todo = self.matcher.blocks_todo();
231        (total - todo, total)
232    }
233
234    /// Scans the file at `path` for blocks of the target, at any offset, and
235    /// copies each one found into the temporary file.
236    ///
237    /// Returns the number of blocks found. A file shorter than one block, or
238    /// two when [`HashLengths::seq_matches`](crate::control::HashLengths::seq_matches)
239    /// is 2, cannot contain a match and returns 0.
240    ///
241    /// # Errors
242    ///
243    /// Returns [`AssemblyError::Io`] when reading the source or writing the
244    /// temporary file fails, and [`AssemblyError::Aborted`] when the abort
245    /// flag is raised.
246    pub fn submit_source_file(&mut self, path: &Path) -> Result<usize, AssemblyError> {
247        let mut file = File::open(path)?;
248        let file_size = file.metadata()?.len() as usize;
249
250        let blocksize = self.control.blocksize;
251        let context = blocksize * self.control.hash_lengths.seq_matches as usize;
252
253        if file_size < context {
254            return Ok(0);
255        }
256
257        let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
258        let mut total_matched = 0;
259        let mut buf = vec![0u8; chunk_size + 2 * context];
260        let mut file_offset = 0usize;
261
262        let abort_flag = self.abort_flag.clone();
263
264        loop {
265            if aborted(&abort_flag) {
266                return Err(AssemblyError::Aborted);
267            }
268
269            let overlap_start = file_offset.saturating_sub(context);
270            let overlap_len = file_offset - overlap_start;
271
272            if overlap_len > 0 {
273                Self::read_at_offset(&mut file, &mut buf[..overlap_len], overlap_start as u64)?;
274            }
275
276            let read_start = overlap_len;
277            let read_len = chunk_size;
278
279            let bytes_read = Self::read_at_offset(
280                &mut file,
281                &mut buf[read_start..read_start + read_len],
282                file_offset as u64,
283            )?;
284            if bytes_read == 0 {
285                break;
286            }
287
288            let data_len = read_start + bytes_read;
289            let chunk_context = if file_offset + bytes_read < file_size {
290                let context_start = file_offset + bytes_read;
291                let context_available = file_size.saturating_sub(context_start).min(context);
292                Self::read_at_offset(
293                    &mut file,
294                    &mut buf[data_len..data_len + context_available],
295                    context_start as u64,
296                )?;
297                if context_available < context {
298                    buf[data_len + context_available..data_len + context].fill(0);
299                }
300                data_len + context
301            } else {
302                buf[data_len..data_len + context].fill(0);
303                data_len + context
304            };
305
306            let matched_blocks = self
307                .matcher
308                .submit_source_data(&buf[..chunk_context], overlap_start as u64);
309
310            for (block_id, source_offset) in &matched_blocks {
311                let file_handle = self.ensure_file()?;
312                let offset = (block_id * blocksize) as u64;
313                let buf_offset = source_offset.saturating_sub(overlap_start);
314                debug_assert!(
315                    buf_offset + blocksize <= chunk_context,
316                    "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
317                    buf_offset,
318                    blocksize,
319                    chunk_context,
320                    source_offset,
321                    overlap_start
322                );
323                let block_data = &buf[buf_offset..buf_offset + blocksize];
324                Self::write_at_offset(file_handle, block_data, offset)?;
325            }
326
327            total_matched += matched_blocks.len();
328            file_offset += bytes_read;
329
330            if bytes_read < read_len {
331                break;
332            }
333        }
334
335        Ok(total_matched)
336    }
337
338    /// Scans the temporary file itself for further blocks of the target.
339    ///
340    /// A target that repeats a block, such as a run of zeros, needs it only
341    /// once to fill every copy. Run this after the source files, when the
342    /// temporary file holds what they supplied. Returns the number of blocks
343    /// found, which is 0 when nothing has been written yet.
344    ///
345    /// # Errors
346    ///
347    /// Returns [`AssemblyError::Io`] when reading or writing the temporary
348    /// file fails, and [`AssemblyError::Aborted`] when the abort flag is
349    /// raised.
350    pub fn submit_self_referential(&mut self) -> Result<usize, AssemblyError> {
351        if self.file.is_none() {
352            return Ok(0);
353        }
354
355        let file = self.file.as_mut().unwrap();
356        file.sync_all()?;
357
358        let file_size = file.metadata()?.len() as usize;
359
360        let blocksize = self.control.blocksize;
361        let context = blocksize * self.control.hash_lengths.seq_matches as usize;
362
363        if file_size < context {
364            return Ok(0);
365        }
366
367        let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
368        let mut total_matched = 0;
369        let mut buf = vec![0u8; chunk_size + 2 * context];
370        let mut file_offset = 0usize;
371
372        let abort_flag = self.abort_flag.clone();
373
374        loop {
375            if aborted(&abort_flag) {
376                return Err(AssemblyError::Aborted);
377            }
378
379            let overlap_start = file_offset.saturating_sub(context);
380            let overlap_len = file_offset - overlap_start;
381
382            if overlap_len > 0 {
383                Self::read_at_offset(file, &mut buf[..overlap_len], overlap_start as u64)?;
384            }
385
386            let read_start = overlap_len;
387            let read_len = chunk_size;
388
389            let bytes_read = Self::read_at_offset(
390                file,
391                &mut buf[read_start..read_start + read_len],
392                file_offset as u64,
393            )?;
394            if bytes_read == 0 {
395                break;
396            }
397
398            let data_len = read_start + bytes_read;
399            let chunk_context = if file_offset + bytes_read < file_size {
400                let context_start = file_offset + bytes_read;
401                let context_available = file_size.saturating_sub(context_start).min(context);
402                Self::read_at_offset(
403                    file,
404                    &mut buf[data_len..data_len + context_available],
405                    context_start as u64,
406                )?;
407                if context_available < context {
408                    buf[data_len + context_available..data_len + context].fill(0);
409                }
410                data_len + context
411            } else {
412                buf[data_len..data_len + context].fill(0);
413                data_len + context
414            };
415
416            let matched_blocks = self
417                .matcher
418                .submit_source_data(&buf[..chunk_context], overlap_start as u64);
419
420            for (block_id, source_offset) in &matched_blocks {
421                let offset = (block_id * blocksize) as u64;
422                let buf_offset = source_offset.saturating_sub(overlap_start);
423                debug_assert!(
424                    buf_offset + blocksize <= chunk_context,
425                    "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
426                    buf_offset,
427                    blocksize,
428                    chunk_context,
429                    source_offset,
430                    overlap_start
431                );
432                let block_data = &buf[buf_offset..buf_offset + blocksize];
433                Self::write_at_offset(file, block_data, offset)?;
434            }
435
436            total_matched += matched_blocks.len();
437            file_offset += bytes_read;
438
439            if bytes_read < read_len {
440                break;
441            }
442        }
443
444        Ok(total_matched)
445    }
446
447    fn read_at_offset(
448        file: &mut File,
449        data: &mut [u8],
450        offset: u64,
451    ) -> Result<usize, AssemblyError> {
452        file.seek(SeekFrom::Start(offset))?;
453        Ok(file.read(data)?)
454    }
455
456    fn write_at_offset(file: &mut File, data: &[u8], offset: u64) -> Result<(), AssemblyError> {
457        file.seek(SeekFrom::Start(offset))?;
458        file.write_all(data)?;
459        Ok(())
460    }
461
462    fn ensure_file(&mut self) -> Result<&mut File, AssemblyError> {
463        if self.file.is_none() {
464            let file = OpenOptions::new()
465                .read(true)
466                .write(true)
467                .create(true)
468                .truncate(false)
469                .open(&self.temp_path)?;
470            self.file = Some(file);
471        }
472        Ok(self.file.as_mut().unwrap())
473    }
474
475    /// Downloads the blocks still missing and writes those that verify.
476    ///
477    /// Blocks are fetched from the control file's first URL, with nearby
478    /// ranges merged as [`Self::set_range_gap_threshold`] allows. Each block
479    /// is checked against its checksum before it is written. One that fails
480    /// stays missing, so a server sending wrong data cannot corrupt the
481    /// output.
482    ///
483    /// Returns the number of blocks written. Call it until it returns 0, then
484    /// check [`Self::is_complete`]: 0 means nothing was missing or nothing
485    /// that arrived verified, and looping on [`Self::is_complete`] alone
486    /// never ends against a server that sends the wrong bytes.
487    ///
488    /// # Errors
489    ///
490    /// Returns [`AssemblyError::NoUrls`] when the control file lists no URL,
491    /// [`AssemblyError::Http`] or [`AssemblyError::Io`] when a request or a
492    /// write fails, and [`AssemblyError::Aborted`] when the abort flag is
493    /// raised.
494    pub fn download_missing_blocks(&mut self) -> Result<usize, AssemblyError> {
495        let relative_url = self
496            .control
497            .urls
498            .first()
499            .ok_or(AssemblyError::NoUrls)?
500            .clone();
501
502        let url = self
503            .base_url
504            .as_ref()
505            .map(|base| resolve_url(base, &relative_url))
506            .unwrap_or(relative_url);
507
508        let block_ranges = self.matcher.needed_block_ranges();
509        if block_ranges.is_empty() {
510            return Ok(0);
511        }
512
513        let byte_ranges = byte_ranges_from_block_ranges(
514            &block_ranges,
515            self.control.blocksize,
516            self.control.length,
517        );
518        let merged_ranges = merge_byte_ranges(&byte_ranges, self.range_gap_threshold);
519        let mut downloaded_blocks = 0;
520        let blocksize = self.control.blocksize;
521        let total_blocks = self.matcher.total_blocks();
522        let mut padded_buf = vec![0u8; blocksize];
523
524        let abort_flag = self.abort_flag.clone();
525
526        for (range_start, range_end) in merged_ranges {
527            if aborted(&abort_flag) {
528                return Err(AssemblyError::Aborted);
529            }
530
531            let mut reader = self.http.fetch_range_reader(&url, range_start, range_end)?;
532            let block_start = (range_start / blocksize as u64) as usize;
533            let initial_offset = (range_start % blocksize as u64) as usize;
534
535            let mut buf = vec![0u8; blocksize + 64 * 1024];
536            buf[..initial_offset].fill(0);
537            let mut buf_len = initial_offset;
538            let mut current_block_id = block_start;
539
540            let mut read_buf = [0u8; 64 * 1024];
541            loop {
542                if aborted(&abort_flag) {
543                    return Err(AssemblyError::Aborted);
544                }
545
546                let n = reader.read(&mut read_buf)?;
547                if n == 0 {
548                    break;
549                }
550
551                if buf_len + n > buf.len() {
552                    buf.resize(buf_len + n, 0);
553                }
554                buf[buf_len..buf_len + n].copy_from_slice(&read_buf[..n]);
555                buf_len += n;
556
557                while buf_len >= blocksize {
558                    if current_block_id >= total_blocks {
559                        break;
560                    }
561
562                    if !self.matcher.is_block_known(current_block_id) {
563                        let block_data_end = if current_block_id == total_blocks - 1 {
564                            let last_block_size = (self.control.length as usize) % blocksize;
565                            if last_block_size == 0 {
566                                blocksize
567                            } else {
568                                last_block_size
569                            }
570                        } else {
571                            blocksize
572                        };
573
574                        let block_data = &buf[..block_data_end];
575                        padded_buf[..block_data_end].copy_from_slice(block_data);
576                        if block_data_end < blocksize {
577                            padded_buf[block_data_end..].fill(0);
578                        }
579
580                        if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
581                            let file = self.ensure_file()?;
582                            let file_offset = (current_block_id * blocksize) as u64;
583                            Self::write_at_offset(file, block_data, file_offset)?;
584                            downloaded_blocks += 1;
585                            self.report_progress();
586                        }
587                    }
588
589                    current_block_id += 1;
590                    buf.copy_within(blocksize..buf_len, 0);
591                    buf_len -= blocksize;
592                }
593            }
594
595            if buf_len > 0
596                && current_block_id < total_blocks
597                && !self.matcher.is_block_known(current_block_id)
598            {
599                let block_data = &buf[..buf_len];
600                padded_buf[..buf_len].copy_from_slice(block_data);
601                padded_buf[buf_len..].fill(0);
602
603                if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
604                    let file = self.ensure_file()?;
605                    let file_offset = (current_block_id * blocksize) as u64;
606                    Self::write_at_offset(file, block_data, file_offset)?;
607                    downloaded_blocks += 1;
608                    self.report_progress();
609                }
610            }
611        }
612
613        Ok(downloaded_blocks)
614    }
615
616    /// Verifies the assembled file and moves it to the output path.
617    ///
618    /// The temporary file is cut to the target's length, its SHA-1 is
619    /// compared with the control file's when the control file has one, and
620    /// it is renamed to the output path. On any error the assembly is
621    /// dropped, which removes the temporary file.
622    ///
623    /// # Errors
624    ///
625    /// Returns [`AssemblyError::Control`] when blocks are still missing,
626    /// [`AssemblyError::ChecksumMismatch`] when the digests differ, and
627    /// [`AssemblyError::Io`] when reading, truncating or renaming fails.
628    pub fn complete(mut self) -> Result<(), AssemblyError> {
629        if !self.matcher.is_complete() {
630            return Err(AssemblyError::Control(
631                "Not all blocks downloaded".to_string(),
632            ));
633        }
634
635        let file_length = self.control.length;
636        let expected_sha1 = self.control.sha1.clone();
637
638        let file = self.ensure_file()?;
639        file.set_len(file_length)?;
640
641        if let Some(ref expected) = expected_sha1 {
642            file.seek(SeekFrom::Start(0))?;
643            let actual_checksum = calc_sha1_stream(file)?;
644            let actual_hex = hex_encode(&actual_checksum);
645
646            if !actual_hex.eq_ignore_ascii_case(expected) {
647                return Err(AssemblyError::ChecksumMismatch {
648                    expected: expected.clone(),
649                    actual: actual_hex,
650                });
651            }
652        }
653
654        self.file.take();
655        std::fs::rename(&self.temp_path, &self.output_path)?;
656
657        Ok(())
658    }
659
660    /// Discards the assembly and its partial output.
661    ///
662    /// Equivalent to dropping it; both remove the temp file.
663    pub fn abort(self) {}
664}
665
666impl Drop for ZsyncAssembly {
667    /// Removes the temp file unless [`ZsyncAssembly::complete`] already renamed
668    /// it into place.
669    ///
670    /// Every failure path would otherwise leave a partial `.zsync-tmp` beside
671    /// the output. Nothing resumes from it: a later run builds a fresh matcher
672    /// that cannot tell which of its blocks are already written.
673    fn drop(&mut self) {
674        let _ = std::fs::remove_file(&self.temp_path);
675    }
676}
677
678fn hex_encode(bytes: &[u8]) -> String {
679    bytes.iter().map(|b| format!("{:02x}", b)).collect()
680}
681
682fn extract_base_url(url: &str) -> String {
683    url.rfind('/')
684        .map(|i| url[..=i].to_string())
685        .unwrap_or_default()
686}
687
688fn resolve_url(base: &str, relative: &str) -> String {
689    if relative.contains("://") {
690        return relative.to_string();
691    }
692    if relative.starts_with('/') {
693        let scheme_end = base.find("://").map(|i| i + 3).unwrap_or(0);
694        let host_end = base[scheme_end..]
695            .find('/')
696            .map(|i| scheme_end + i)
697            .unwrap_or(base.len());
698        format!("{}{}", &base[..host_end], relative)
699    } else {
700        format!("{}{}", base, relative)
701    }
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    #[test]
709    fn test_hex_encode() {
710        assert_eq!(hex_encode(&[0x00, 0xff, 0x10]), "00ff10");
711    }
712
713    #[test]
714    fn test_extract_base_url() {
715        assert_eq!(
716            extract_base_url("https://example.com/path/file.zsync"),
717            "https://example.com/path/"
718        );
719        assert_eq!(
720            extract_base_url("https://example.com/file.zsync"),
721            "https://example.com/"
722        );
723    }
724
725    #[test]
726    fn test_resolve_url() {
727        assert_eq!(
728            resolve_url("https://example.com/path/", "file.bin"),
729            "https://example.com/path/file.bin"
730        );
731        assert_eq!(
732            resolve_url("https://example.com/path/", "/file.bin"),
733            "https://example.com/file.bin"
734        );
735        assert_eq!(
736            resolve_url("https://example.com/path/", "https://other.com/file.bin"),
737            "https://other.com/file.bin"
738        );
739    }
740}