From 43036bec84453a2838f53967e72637059d733a36 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Fri, 13 Jan 2023 07:54:27 -0500 Subject: [PATCH] Added read errors. --- src/morethantext/cachetype.rs | 37 ++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/morethantext/cachetype.rs b/src/morethantext/cachetype.rs index 0c9f19d..1229571 100644 --- a/src/morethantext/cachetype.rs +++ b/src/morethantext/cachetype.rs @@ -36,11 +36,18 @@ impl CacheType { pub fn from_bytes(data: Vec) -> Result { let mut data_iter = data.iter(); - let mut letter: u8 = *data_iter.next().unwrap(); + let mut letter: u8; + match data_iter.next() { + Some(item) => letter = *item, + None => return Err(DBError::new("empty file")), + } let mut header: Vec = Vec::new(); while letter != 0 { header.push(letter.clone()); - letter = *data_iter.next().unwrap(); + match data_iter.next() { + Some(item) => letter = *item, + None => return Err(DBError::new("incomplete file")), + } } let header = str::from_utf8(&header).unwrap().to_string(); match header.as_str() { @@ -51,7 +58,7 @@ impl CacheType { } Ok(CacheType::Raw(str::from_utf8(&output).unwrap().to_string())) } - _ => Err(DBError::new("fred")), + _ => Err(DBError::new("data corruption")), } } } @@ -116,7 +123,7 @@ mod enum_ctype { } #[test] - fn bad_file() { + fn bad_file_header() { let mut data: Vec = Vec::new(); let mut ctype = "jlksdfg".as_bytes().to_vec(); let mut cdata = "ghjk".as_bytes().to_vec(); @@ -125,7 +132,27 @@ mod enum_ctype { data.append(&mut cdata); match CacheType::from_bytes(data) { Ok(_) => assert!(false, "This should fail."), - Err(_) => (), + Err(err) => assert_eq!(err.to_string(), "data corruption"), + } + } + + #[test] + fn incomplete_file() { + let mut data: Vec = Vec::new(); + let mut ctype = "uoisfde".as_bytes().to_vec(); + data.append(&mut ctype); + match CacheType::from_bytes(data) { + Ok(_) => assert!(false, "This should fail."), + Err(err) => assert_eq!(err.to_string(), "incomplete file"), + } + } + + #[test] + fn empty_file() { + let data: Vec = Vec::new(); + match CacheType::from_bytes(data) { + Ok(_) => assert!(false, "This should fail."), + Err(err) => assert_eq!(err.to_string(), "empty file"), } } }