1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#[macro_use]
extern crate failure;

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::hash::Hash;

use kv_crud_core::*;

#[derive(Debug, Fail)]
pub enum InMemoryStorageError {
    #[fail(display = "Entity with id {} was not found", entity_id)]
    EntityNotFound { entity_id: String },
}

/// In-memory storage manages it's data in simple hash map
#[derive(Default)]
pub struct InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    db: HashMap<K, V>,
}

impl<K, V> InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    /// Creates new empty in-memory storage
    pub fn new() -> Self {
        Self { db: HashMap::new() }
    }
}

impl<K, V> Create<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    type Error = InMemoryStorageError;
    fn save(&mut self, entity: &V) -> Result<(), InMemoryStorageError> {
        self.db.insert(entity.get_id(), entity.clone());
        Ok(())
    }
}

impl<K, V> Read<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq + ToString,
    V: Entity<K>,
{
    type Error = InMemoryStorageError;

    fn find_by_id(&self, id: &K) -> Result<V, InMemoryStorageError> {
        match self.db.get(id) {
            Some(value) => Ok(value.clone()),
            None => {
                let id: String = id.to_string();
                Err(InMemoryStorageError::EntityNotFound { entity_id: id })
            }
        }
    }
}

impl<K, V> ReadWithPaginationAndSort<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq + ToString,
    V: Entity<K> + Ord,
{
    type Error = InMemoryStorageError;

    fn find_all_with_page(&self, page: &Page) -> Result<Vec<V>, InMemoryStorageError> {
        self.find_all_with_page_and_sort(page, &Sort::ASCENDING)
    }

    fn find_all_with_page_and_sort(
        &self,
        page: &Page,
        sort: &Sort,
    ) -> Result<Vec<V>, InMemoryStorageError> {
        let mut values: Vec<V> = self.db.iter().map(|(_, v)| v).cloned().collect();

        values.sort();
        if *sort == Sort::DESCENDING {
            values.reverse();
        }

        Ok(values
            .into_iter()
            .skip(page.offset() as usize)
            .take(page.size as usize)
            .collect())
    }
}

impl<K, V> Update<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    type Error = InMemoryStorageError;

    fn update(&mut self, entity: &V) -> Result<(), Self::Error> {
        self.save(entity)
    }
}

impl<K, V> Delete<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    type Error = InMemoryStorageError;

    fn remove_by_id(&mut self, id: &K) -> Result<(), Self::Error> {
        self.db.remove(id);
        Ok(())
    }

    fn remove(&mut self, entity: &V) -> Result<(), Self::Error> {
        self.remove_by_id(&entity.get_id())
    }
}

impl<K, V> Crud<K, V> for InMemoryStorage<K, V>
where
    K: Hash + Eq + ToString,
    V: Entity<K> + Ord,
{
}

impl<K, V> From<&V> for InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    fn from(v: &V) -> Self {
        let mut result = Self::new();
        result.save(v).unwrap();
        result
    }
}

impl<K, V> From<&Vec<V>> for InMemoryStorage<K, V>
where
    K: Hash + Eq,
    V: Entity<K>,
{
    fn from(values: &Vec<V>) -> Self {
        let mut result = Self::new();
        for v in values {
            result.save(v).unwrap();
        }
        result
    }
}