81 lines
2.0 KiB
Rust
81 lines
2.0 KiB
Rust
use super::DBError;
|
|
use std::{collections::HashMap, fmt, str};
|
|
|
|
#[derive(Clone)]
|
|
pub enum CacheType {
|
|
Raw(String),
|
|
}
|
|
|
|
impl CacheType {
|
|
fn entry_type(&self) -> String {
|
|
match self {
|
|
CacheType::Raw(_) => "Raw".to_string(),
|
|
}
|
|
}
|
|
|
|
pub fn to_bytes(&self) -> Vec<u8> {
|
|
let mut output = self.entry_type().into_bytes();
|
|
output.push(0);
|
|
match self {
|
|
CacheType::Raw(s) => output.append(&mut s.as_bytes().to_vec()),
|
|
}
|
|
return output;
|
|
}
|
|
|
|
pub fn from_bytes(data: Vec<u8>) -> CacheType {
|
|
let mut data_iter = data.iter();
|
|
let mut holder: u8 = *data_iter.next().unwrap();
|
|
while holder != 0 {
|
|
holder = *data_iter.next().unwrap();
|
|
}
|
|
let mut output: Vec<u8> = Vec::new();
|
|
for letter in data_iter {
|
|
output.push(letter.clone());
|
|
}
|
|
CacheType::Raw(str::from_utf8(&output).unwrap().to_string())
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for CacheType {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
CacheType::Raw(s) => write!(f, "{}", s),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod raw {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn get_bytes() {
|
|
let data = "addams";
|
|
let holder = CacheType::Raw(data.to_string());
|
|
let mut expected = holder.entry_type().into_bytes();
|
|
expected.push(0);
|
|
expected.append(&mut data.as_bytes().to_vec());
|
|
let output = holder.to_bytes();
|
|
assert_eq!(output, expected);
|
|
}
|
|
|
|
#[test]
|
|
fn from_bytes() {
|
|
let holder = CacheType::Raw("stored item".to_string());
|
|
let data = holder.to_bytes();
|
|
let output = CacheType::from_bytes(data);
|
|
assert_eq!(output.to_string(), holder.to_string());
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod enum_ctype {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn get_raw_type() {
|
|
let holder = CacheType::Raw("nothing important".to_string());
|
|
assert_eq!(holder.entry_type(), "Raw");
|
|
}
|
|
}
|