Remove duplicated code and make base64 error handling better

This commit is contained in:
2022-08-14 09:12:36 -04:00
parent fbf26efa44
commit 5158c16d56
8 changed files with 132 additions and 88 deletions

View File

@@ -1,4 +1,8 @@
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{bytes::Bytes, bytes_base64::BytesBase64};
use std::{
io::{BufRead, BufReader},
time::{SystemTime, UNIX_EPOCH},
};
pub fn unix_timestamp() -> u32 {
let start = SystemTime::now();
@@ -7,3 +11,31 @@ pub fn unix_timestamp() -> u32 {
.expect("Time went backwards");
since_the_epoch.as_secs() as u32
}
pub fn read_base64(path: &str) -> Bytes {
let s = std::fs::read_to_string(path).unwrap();
match BytesBase64::from_base64(&s) {
Ok(bytes) => bytes.to_bytes(),
Err(msg) => panic!("Failed to read_base64 {}: {}", path, msg),
}
}
pub fn read_base64_lines(path: &str) -> Vec<Bytes> {
let file = std::fs::File::open(path).unwrap();
let br = BufReader::new(file);
br.lines()
.map(|line| {
BytesBase64::from_base64(&line.expect(&format!("Failed to read line in {}", path)))
.expect(&format!("Invalid base64 in {}", path))
.to_bytes()
})
.collect()
}
pub fn read_hex_lines(path: &str) -> Vec<Bytes> {
let file = std::fs::File::open(path).unwrap();
let br = BufReader::new(file);
br.lines()
.map(|line| Bytes::from_hex(&line.unwrap()))
.collect()
}