diff options
| author | Jokler <jokler.contact@gmail.com> | 2018-03-01 17:27:49 +0100 |
|---|---|---|
| committer | Jokler <jokler.contact@gmail.com> | 2018-03-01 17:27:49 +0100 |
| commit | 7cdca0b7d75172d8f900e8e755ff07ed8a72966a (patch) | |
| tree | afae84087d58240e7934e8c82024681134d32690 | |
| parent | 090dea2091eb12559004b27a38a9c5f1afc32626 (diff) | |
| download | frippy-7cdca0b7d75172d8f900e8e755ff07ed8a72966a.tar.gz frippy-7cdca0b7d75172d8f900e8e755ff07ed8a72966a.zip | |
Simplify the download function
| -rw-r--r-- | src/error.rs | 8 | ||||
| -rw-r--r-- | src/utils.rs | 29 |
2 files changed, 8 insertions, 29 deletions
diff --git a/src/error.rs b/src/error.rs index 2ceb4cc..674faaa 100644 --- a/src/error.rs +++ b/src/error.rs @@ -30,9 +30,9 @@ pub enum FrippyError { #[fail(display = "An I/O error occured")] Io(#[cause] IoError), - /// A UTF8 error - #[fail(display = "A UTF8 error occured")] - Utf8(#[cause] Utf8Error), + /// A decoding error + #[fail(display = "Failed to decode bytes")] + Decoding(#[cause] Utf8Error), /// An r2d2 error #[cfg(feature = "mysql")] @@ -100,7 +100,7 @@ impl From<IoError> for FrippyError { impl From<Utf8Error> for FrippyError { fn from(e: Utf8Error) -> FrippyError { - FrippyError::Utf8(e) + FrippyError::Decoding(e) } } diff --git a/src/utils.rs b/src/utils.rs index 68ad4d8..1f3a117 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -9,43 +9,21 @@ use error::FrippyError; pub fn download(max_kib: usize, url: &str) -> Result<String, FrippyError> { let mut response = Client::new().get(url).header(Connection::close()).send()?; - let mut body = String::new(); - // 100 kibibyte buffer let mut buf = [0; 100 * 1024]; let mut written = 0; - let mut vec = Vec::new(); - let mut end_of_valid = None; + let mut bytes = Vec::new(); // Read until we reach EOF or max_kib KiB loop { - if let Some(eov) = end_of_valid { - vec = vec[..eov].to_vec(); - } - let len = match response.read(&mut buf) { Ok(0) => break, Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => Err(e)?, }; - vec.extend_from_slice(&buf); - - end_of_valid = None; - let body_slice = match str::from_utf8(&vec[..len]) { - Ok(slice) => slice, - Err(e) => { - let valid = e.valid_up_to(); - if valid == 0 { - Err(e)?; - } - end_of_valid = Some(valid); - - str::from_utf8(&buf[..valid])? - } - }; - body.push_str(body_slice); + bytes.extend_from_slice(&buf); written += len; // Check if the file is too large to download @@ -53,6 +31,7 @@ pub fn download(max_kib: usize, url: &str) -> Result<String, FrippyError> { Err(FrippyError::DownloadLimit { limit: max_kib })?; } } + let body = str::from_utf8(&bytes)?; - Ok(body) + Ok(body.to_string()) } |
