omaha_client/storage/
memory.rs

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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2019 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.

use super::*;
use futures::future::BoxFuture;
use futures::prelude::*;
use std::collections::HashMap;
use thiserror::Error;

/// The MemStorage struct is an in-memory-only implementation of the Storage trait, to be used in
/// testing scenarios.
#[derive(Debug)]
pub struct MemStorage {
    /// The values current stored.
    data: HashMap<String, Value>,

    /// Whether commit() has been called after set_*() or remove().
    committed: bool,
}

/// Value is an enumeration for holding the values in MemStorage.
#[derive(Debug)]
enum Value {
    String(String),
    Int(i64),
    Bool(bool),
}

/// The stub implementation doesn't return errors, so this is just a placeholder.
#[derive(Debug, Error)]
pub enum StorageErrors {
    #[error("Unknown error occurred")]
    Unknown,
}

impl MemStorage {
    pub fn new() -> Self {
        MemStorage {
            data: HashMap::new(),
            committed: true,
        }
    }

    pub fn committed(&self) -> bool {
        self.committed
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }

    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl Default for MemStorage {
    fn default() -> Self {
        Self::new()
    }
}

impl Storage for MemStorage {
    type Error = StorageErrors;

    /// Get a string from the backing store.  Returns None if there is no value for the given key.
    fn get_string<'a>(&'a self, key: &'a str) -> BoxFuture<'_, Option<String>> {
        future::ready(match self.data.get(key) {
            Some(Value::String(s)) => Some(s.clone()),
            _ => None,
        })
        .boxed()
    }

    /// Get an int from the backing store.  Returns None if there is no value for the given key.
    fn get_int<'a>(&'a self, key: &'a str) -> BoxFuture<'_, Option<i64>> {
        future::ready(match self.data.get(key) {
            Some(Value::Int(i)) => Some(*i),
            _ => None,
        })
        .boxed()
    }

    /// Get a boolean from the backing store.  Returns None if there is no value for the given key.
    fn get_bool<'a>(&'a self, key: &'a str) -> BoxFuture<'_, Option<bool>> {
        future::ready(match self.data.get(key) {
            Some(Value::Bool(b)) => Some(*b),
            _ => None,
        })
        .boxed()
    }

    /// Set a value to be stored in the backing store.  The implementation should cache the value
    /// until the |commit()| fn is called, and then persist all cached values at that time.
    fn set_string<'a>(
        &'a mut self,
        key: &'a str,
        value: &'a str,
    ) -> BoxFuture<'_, Result<(), Self::Error>> {
        self.data
            .insert(key.to_string(), Value::String(value.to_string()));
        self.committed = false;
        future::ready(Ok(())).boxed()
    }

    /// Set a value to be stored in the backing store.  The implementation should cache the value
    /// until the |commit()| fn is called, and then persist all cached values at that time.
    fn set_int<'a>(
        &'a mut self,
        key: &'a str,
        value: i64,
    ) -> BoxFuture<'_, Result<(), Self::Error>> {
        self.data.insert(key.to_string(), Value::Int(value));
        self.committed = false;
        future::ready(Ok(())).boxed()
    }

    /// Set a value to be stored in the backing store.  The implementation should cache the value
    /// until the |commit()| fn is called, and then persist all cached values at that time.
    fn set_bool<'a>(
        &'a mut self,
        key: &'a str,
        value: bool,
    ) -> BoxFuture<'_, Result<(), Self::Error>> {
        self.data.insert(key.to_string(), Value::Bool(value));
        self.committed = false;
        future::ready(Ok(())).boxed()
    }

    fn remove<'a>(&'a mut self, key: &'a str) -> BoxFuture<'_, Result<(), Self::Error>> {
        self.data.remove(key);
        self.committed = false;
        future::ready(Ok(())).boxed()
    }

    /// Persist all cached values to storage.
    fn commit(&mut self) -> BoxFuture<'_, Result<(), Self::Error>> {
        self.committed = true;
        future::ready(Ok(())).boxed()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::tests::*;
    use futures::executor::block_on;

    #[test]
    fn test_set_get_remove_string() {
        block_on(do_test_set_get_remove_string(&mut MemStorage::new()));
    }

    #[test]
    fn test_set_get_remove_int() {
        block_on(do_test_set_get_remove_int(&mut MemStorage::new()));
    }

    #[test]
    fn test_set_option_int() {
        block_on(do_test_set_option_int(&mut MemStorage::new()));
    }

    #[test]
    fn test_set_get_remove_bool() {
        block_on(do_test_set_get_remove_bool(&mut MemStorage::new()));
    }

    #[test]
    fn test_set_get_remove_time() {
        block_on(do_test_set_get_remove_time(&mut MemStorage::new()));
    }

    #[test]
    fn test_return_none_for_wrong_value_type() {
        block_on(do_return_none_for_wrong_value_type(&mut MemStorage::new()));
    }

    #[test]
    fn test_ensure_no_error_remove_nonexistent_key() {
        block_on(do_ensure_no_error_remove_nonexistent_key(
            &mut MemStorage::new(),
        ));
    }

    #[test]
    fn test_committed() {
        block_on(async {
            let mut storage = MemStorage::new();
            assert!(storage.committed());
            storage.set_bool("some bool key", false).await.unwrap();
            assert!(!storage.committed());
            storage.commit().await.unwrap();
            assert!(storage.committed());
            storage
                .set_string("some string key", "some string")
                .await
                .unwrap();
            assert!(!storage.committed());
            storage.set_int("some int key", 42).await.unwrap();
            assert!(!storage.committed());
            storage.commit().await.unwrap();
            assert!(storage.committed());
        });
    }
}