#![doc(hidden)]
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use super::{Storage, StorageError};
#[derive(Debug, Clone)]
pub struct SimpleStorageError {}
impl Display for SimpleStorageError {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "Failed to get data from SimpleStorage")
}
}
impl Error for SimpleStorageError {
fn description(&self) -> &str {
"SimpleStorage::get() error"
}
}
impl StorageError for SimpleStorageError {}
struct Entry {
name: Vec<u8>,
data: Vec<u8>,
}
#[derive(Default)]
pub struct SimpleStorage {
entries: Vec<Entry>,
}
impl SimpleStorage {
pub fn new() -> SimpleStorage {
SimpleStorage { entries: vec![] }
}
pub fn has_chunk(&self, name: &[u8]) -> bool {
self.entries.iter().any(|ref entry| entry.name == name)
}
pub fn num_entries(&self) -> usize {
self.entries.len()
}
}
impl Storage<SimpleStorageError> for SimpleStorage {
fn get(&self, name: &[u8]) -> Result<Vec<u8>, SimpleStorageError> {
match self.entries.iter().find(|ref entry| entry.name == name) {
Some(entry) => Ok(entry.data.clone()),
None => Err(SimpleStorageError {}),
}
}
fn put(&mut self, name: Vec<u8>, data: Vec<u8>) -> Result<(), SimpleStorageError> {
Ok(self.entries.push(Entry {
name: name,
data: data,
}))
}
}