Skip to content

Commit 02082f1

Browse files
committed
rustup_utils: Add a FileReaderWithProgress struct
In order to be able to report unpack progress, add support for a file reader which emits notifications akin to the downloading of a file. This allows the generic progress bar supporting downloads to also handle the installation of components. Signed-off-by: Daniel Silverstone <[email protected]>
1 parent f767b8f commit 02082f1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/rustup-utils/src/utils.rs

+51
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,57 @@ fn rename(name: &'static str, src: &Path, dest: &Path) -> Result<()> {
854854
})
855855
}
856856

857+
pub struct FileReaderWithProgress<'a> {
858+
fh: std::fs::File,
859+
notify_handler: &'a Fn(Notification),
860+
sent_start: bool,
861+
nbytes: u64,
862+
flen: u64,
863+
}
864+
865+
impl<'a> FileReaderWithProgress<'a> {
866+
pub fn new_file(path: &Path, notify_handler: &'a Fn(Notification)) -> Result<Self> {
867+
let fh = match std::fs::File::open(path) {
868+
Ok(fh) => fh,
869+
Err(_) => Err(ErrorKind::ReadingFile {
870+
name: "downloaded",
871+
path: path.to_path_buf(),
872+
})?,
873+
};
874+
875+
Ok(FileReaderWithProgress {
876+
fh,
877+
notify_handler,
878+
sent_start: false,
879+
nbytes: 0,
880+
flen: 0,
881+
})
882+
}
883+
}
884+
885+
impl<'a> std::io::Read for FileReaderWithProgress<'a> {
886+
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
887+
if !self.sent_start {
888+
// Send the start notifications
889+
let flen = self.fh.metadata()?.len();
890+
self.flen = flen;
891+
(self.notify_handler)(Notification::DownloadContentLengthReceived(flen));
892+
}
893+
match self.fh.read(buf) {
894+
Ok(nbytes) => {
895+
self.nbytes += nbytes as u64;
896+
if (nbytes == 0) || (self.flen == self.nbytes) {
897+
(self.notify_handler)(Notification::DownloadFinished);
898+
} else {
899+
(self.notify_handler)(Notification::DownloadDataReceived(&buf[0..nbytes]));
900+
}
901+
Ok(nbytes)
902+
}
903+
Err(e) => Err(e),
904+
}
905+
}
906+
}
907+
857908
#[cfg(test)]
858909
mod tests {
859910
use super::*;

0 commit comments

Comments
 (0)