Added read errors.

This commit is contained in:
Jeff Baskin 2023-01-13 07:54:27 -05:00
parent b5b0016aba
commit 43036bec84

View File

@ -36,11 +36,18 @@ impl CacheType {
pub fn from_bytes(data: Vec<u8>) -> Result<CacheType, DBError> { pub fn from_bytes(data: Vec<u8>) -> Result<CacheType, DBError> {
let mut data_iter = data.iter(); 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<u8> = Vec::new(); let mut header: Vec<u8> = Vec::new();
while letter != 0 { while letter != 0 {
header.push(letter.clone()); 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(); let header = str::from_utf8(&header).unwrap().to_string();
match header.as_str() { match header.as_str() {
@ -51,7 +58,7 @@ impl CacheType {
} }
Ok(CacheType::Raw(str::from_utf8(&output).unwrap().to_string())) 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] #[test]
fn bad_file() { fn bad_file_header() {
let mut data: Vec<u8> = Vec::new(); let mut data: Vec<u8> = Vec::new();
let mut ctype = "jlksdfg".as_bytes().to_vec(); let mut ctype = "jlksdfg".as_bytes().to_vec();
let mut cdata = "ghjk".as_bytes().to_vec(); let mut cdata = "ghjk".as_bytes().to_vec();
@ -125,7 +132,27 @@ mod enum_ctype {
data.append(&mut cdata); data.append(&mut cdata);
match CacheType::from_bytes(data) { match CacheType::from_bytes(data) {
Ok(_) => assert!(false, "This should fail."), Ok(_) => assert!(false, "This should fail."),
Err(_) => (), Err(err) => assert_eq!(err.to_string(), "data corruption"),
}
}
#[test]
fn incomplete_file() {
let mut data: Vec<u8> = 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<u8> = Vec::new();
match CacheType::from_bytes(data) {
Ok(_) => assert!(false, "This should fail."),
Err(err) => assert_eq!(err.to_string(), "empty file"),
} }
} }
} }