xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / vm / download.rs 28 lines891 bytes Raw
1use std::io::{self, Read, Write};
2use std::path::Path;
3
4pub fn fetch(url: &str, dest: &Path, mut on_pct: impl FnMut(u8)) -> io::Result<()> {
5    let resp = ureq::get(url).call().map_err(io::Error::other)?;
6    let total: u64 = resp
7        .header("Content-Length")
8        .and_then(|v| v.parse().ok())
9        .unwrap_or(0);
10    let part = dest.with_extension("part");
11    let mut out = std::fs::File::create(&part)?;
12    let mut reader = resp.into_reader();
13    let (mut buf, mut done, mut last) = (vec![0u8; 1 << 16], 0u64, 255u8);
14    loop {
15        let n = reader.read(&mut buf)?;
16        if n == 0 {
17            break;
18        }
19        out.write_all(&buf[..n])?;
20        done += n as u64;
21        let pct = (done * 100).checked_div(total).unwrap_or(0) as u8;
22        if pct != last {
23            last = pct;
24            on_pct(pct);
25        }
26    }
27    std::fs::rename(part, dest)
28}