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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Provides an in-memory implementation of [`NvramStorage`] that doesn't
//! automatically persist to disk.

use crate::NextVariable;
use crate::NvramStorage;
use crate::NvramStorageError;
use crate::EFI_TIME;
use guid::Guid;
use std::collections::BTreeMap;
use std::fmt::Display;
use ucs2::Ucs2LeSlice;
use ucs2::Ucs2LeVec;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct VariableKey {
    vendor: Guid,
    name: Ucs2LeVec,
}

impl Display for VariableKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}-{}", self.vendor, self.name)
    }
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
struct Variable {
    data: Vec<u8>,
    timestamp: EFI_TIME,
    #[cfg_attr(feature = "inspect", inspect(hex))]
    attr: u32,
}

/// An in-memory implementation of [`NvramStorage`].
#[derive(Debug)]
#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
pub struct InMemoryNvram {
    #[cfg_attr(feature = "inspect", inspect(iter_by_key))]
    nvram: BTreeMap<VariableKey, Variable>,
}

pub struct VariableEntry<'a> {
    pub vendor: Guid,
    pub name: &'a Ucs2LeSlice,
    pub data: &'a [u8],
    pub timestamp: EFI_TIME,
    pub attr: u32,
}

impl InMemoryNvram {
    pub fn new() -> Self {
        Self {
            nvram: Default::default(),
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = VariableEntry<'_>> {
        self.nvram.iter().map(|(k, v)| VariableEntry {
            vendor: k.vendor,
            name: k.name.as_ref(),
            data: v.data.as_slice(),
            timestamp: v.timestamp,
            attr: v.attr,
        })
    }

    pub fn clear(&mut self) {
        self.nvram.clear()
    }
}

#[async_trait::async_trait]
impl NvramStorage for InMemoryNvram {
    async fn get_variable(
        &mut self,
        name: &Ucs2LeSlice,
        vendor: Guid,
    ) -> Result<Option<(u32, Vec<u8>, EFI_TIME)>, NvramStorageError> {
        Ok(self
            .nvram
            .get(&VariableKey {
                vendor,
                name: name.to_ucs2_le_vec(),
            })
            .map(|v| (v.attr, v.data.clone(), v.timestamp)))
    }

    async fn set_variable(
        &mut self,
        name: &Ucs2LeSlice,
        vendor: Guid,
        attr: u32,
        data: Vec<u8>,
        timestamp: EFI_TIME,
    ) -> Result<(), NvramStorageError> {
        self.nvram.insert(
            VariableKey {
                vendor,
                name: name.to_ucs2_le_vec(),
            },
            Variable {
                data,
                timestamp,
                attr,
            },
        );
        Ok(())
    }

    async fn append_variable(
        &mut self,
        name: &Ucs2LeSlice,
        vendor: Guid,
        data: Vec<u8>,
        timestamp: EFI_TIME,
    ) -> Result<bool, NvramStorageError> {
        match self.nvram.get_mut(&VariableKey {
            vendor,
            name: name.to_ucs2_le_vec(),
        }) {
            Some(val) => {
                val.data.extend_from_slice(&data);
                val.timestamp = timestamp;
                Ok(true)
            }
            None => Ok(false),
        }
    }

    async fn remove_variable(
        &mut self,
        name: &Ucs2LeSlice,
        vendor: Guid,
    ) -> Result<bool, NvramStorageError> {
        Ok(self
            .nvram
            .remove(&VariableKey {
                vendor,
                name: name.to_ucs2_le_vec(),
            })
            .is_some())
    }

    async fn next_variable(
        &mut self,
        name_vendor: Option<(&Ucs2LeSlice, Guid)>,
    ) -> Result<NextVariable, NvramStorageError> {
        let key = &name_vendor.map(|(name, vendor)| VariableKey {
            vendor,
            name: name.to_ucs2_le_vec(),
        });

        if let Some(key) = key {
            let mut range = self.nvram.range(key..);
            if let Some((found_key, _)) = range.next() {
                if found_key == key {
                    Ok(match range.next() {
                        Some(v) => NextVariable::Exists {
                            name: v.0.name.clone(),
                            vendor: v.0.vendor,
                            attr: v.1.attr,
                        },
                        None => NextVariable::EndOfList,
                    })
                } else {
                    Ok(NextVariable::InvalidKey)
                }
            } else {
                Ok(NextVariable::EndOfList)
            }
        } else {
            Ok(match self.nvram.iter().next() {
                Some(v) => NextVariable::Exists {
                    name: v.0.name.clone(),
                    vendor: v.0.vendor,
                    attr: v.1.attr,
                },
                None => NextVariable::EndOfList,
            })
        }
    }
}

/// A collection of test-implementation helpers that operate on a generic
/// implementation of [`NvramStorage`]
pub mod impl_agnostic_tests {
    use crate::NextVariable;
    use crate::NvramStorage;
    use crate::EFI_TIME;
    use guid::Guid;
    use ucs2::Ucs2LeSlice;
    use wchar::wchz;
    use zerocopy::AsBytes;
    use zerocopy::FromZeroes;

    pub async fn test_single_variable(nvram: &mut dyn NvramStorage) {
        let vendor = Guid::new_random();
        let name = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap();
        let attr = 0x1234;
        let data = vec![0x1, 0x2, 0x3, 0x4, 0x5];
        let data1 = vec![0xa, 0xb, 0xc];
        let timestamp = EFI_TIME::new_zeroed();

        nvram
            .set_variable(name, vendor, attr, data.clone(), timestamp)
            .await
            .unwrap();

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name, vendor).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, data);
        assert_eq!(result_timestamp, timestamp);

        let result = nvram.next_variable(Some((name, vendor))).await.unwrap();
        assert!(matches!(result, NextVariable::EndOfList));

        // set existing variable with new data
        nvram
            .set_variable(name, vendor, attr, data1.clone(), timestamp)
            .await
            .unwrap();

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name, vendor).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, data1);
        assert_eq!(result_timestamp, timestamp);

        nvram.remove_variable(name, vendor).await.unwrap();

        // try to get removed variable
        let result = nvram.get_variable(name, vendor).await.unwrap();
        assert!(result.is_none());
    }

    pub async fn test_next(nvram: &mut dyn NvramStorage) {
        let vendor1 = Guid::new_random();
        let name1 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap();
        let vendor2 = Guid::new_random();
        let name2 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var2").as_bytes()).unwrap();
        let vendor3 = Guid::new_random();
        let name3 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var3").as_bytes()).unwrap();
        let attr = 0x1234;
        let data = vec![0x1, 0x2, 0x3, 0x4, 0x5];
        let timestamp = EFI_TIME::new_zeroed();

        nvram
            .set_variable(name1, vendor1, attr, data.clone(), timestamp)
            .await
            .unwrap();
        nvram
            .set_variable(name2, vendor2, attr, data.clone(), timestamp)
            .await
            .unwrap();
        nvram
            .set_variable(name3, vendor3, attr, data, timestamp)
            .await
            .unwrap();

        let mut expected = {
            let mut s = std::collections::BTreeSet::new();

            s.insert(NextVariable::Exists {
                name: name1.to_owned(),
                vendor: vendor1,
                attr,
            });
            s.insert(NextVariable::Exists {
                name: name2.to_owned(),
                vendor: vendor2,
                attr,
            });
            s.insert(NextVariable::Exists {
                name: name3.to_owned(),
                vendor: vendor3,
                attr,
            });

            s
        };

        let mut owned_key;
        let mut key = None;
        loop {
            let var = nvram.next_variable(key).await.unwrap();
            match &var {
                NextVariable::InvalidKey => panic!(),
                NextVariable::EndOfList => break,
                NextVariable::Exists {
                    name,
                    vendor,
                    attr: _,
                } => owned_key = Some((name.clone(), *vendor)),
            };

            key = owned_key
                .as_ref()
                .map(|(name, vendor)| (name.as_ref(), *vendor));

            let removed = expected.remove(&var);
            assert!(removed);
        }

        assert!(expected.is_empty());

        // check to make sure calls to next_variable are idempotent

        let var1 = nvram.next_variable(None).await.unwrap();
        let var2 = nvram.next_variable(None).await.unwrap();
        assert_eq!(var1, var2);

        let key = match nvram.next_variable(None).await.unwrap() {
            NextVariable::Exists {
                name,
                vendor,
                attr: _,
            } => Some((name, vendor)),
            _ => panic!(),
        };
        let key = key.as_ref().map(|(name, vendor)| (name.as_ref(), *vendor));

        let var1 = nvram.next_variable(key).await.unwrap();
        let var2 = nvram.next_variable(key).await.unwrap();
        assert_eq!(var1, var2);
    }

    pub async fn test_multiple_variable(nvram: &mut dyn NvramStorage) {
        let vendor1 = Guid::new_random();
        let name1 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var1").as_bytes()).unwrap();
        let vendor2 = Guid::new_random();
        let name2 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var2").as_bytes()).unwrap();
        let vendor3 = Guid::new_random();
        let name3 = Ucs2LeSlice::from_slice_with_nul(wchz!(u16, "var3").as_bytes()).unwrap();
        let attr = 0x1234;
        let data = vec![0x1, 0x2, 0x3, 0x4, 0x5];
        let timestamp = EFI_TIME::new_zeroed();

        // add all variables to nvram
        nvram
            .set_variable(name1, vendor1, attr, data.clone(), timestamp)
            .await
            .unwrap();
        nvram
            .set_variable(name2, vendor2, attr, data.clone(), timestamp)
            .await
            .unwrap();
        nvram
            .set_variable(name3, vendor3, attr, data.clone(), timestamp)
            .await
            .unwrap();

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name1, vendor1).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, data);
        assert_eq!(result_timestamp, timestamp);

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name2, vendor2).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, data);
        assert_eq!(result_timestamp, timestamp);

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name3, vendor3).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, data);
        assert_eq!(result_timestamp, timestamp);

        // throw an append in there for good measure
        let appended = nvram
            .append_variable(name1, vendor1, vec![6, 7, 8], timestamp)
            .await
            .unwrap();
        assert!(appended);

        let (result_attr, result_data, result_timestamp) =
            nvram.get_variable(name1, vendor1).await.unwrap().unwrap();
        assert_eq!(result_attr, attr);
        assert_eq!(result_data, (1..=8).collect::<Vec<u8>>());
        assert_eq!(result_timestamp, timestamp);
    }
}

#[cfg(test)]
mod tests {
    use super::impl_agnostic_tests;
    use super::*;
    use pal_async::async_test;

    #[async_test]
    async fn nvram_trait_single_variable() {
        let mut nvram = InMemoryNvram::new();
        impl_agnostic_tests::test_single_variable(&mut nvram).await;
    }

    #[async_test]
    async fn nvram_trait_next() {
        let mut nvram = InMemoryNvram::new();
        impl_agnostic_tests::test_next(&mut nvram).await;
    }

    #[async_test]
    async fn nvram_trait_multiple_variable() {
        let mut nvram = InMemoryNvram::new();
        impl_agnostic_tests::test_multiple_variable(&mut nvram).await;
    }
}