• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4 
5 #[cfg(target_has_atomic = "ptr")]
6 use alloc::sync::Arc;
7 
8 #[cfg(not(target_has_atomic = "ptr"))]
9 use portable_atomic_util::Arc;
10 
11 use core::convert::Infallible;
12 
13 use mls_rs_core::psk::{ExternalPskId, PreSharedKey, PreSharedKeyStorage};
14 
15 #[cfg(mls_build_async)]
16 use alloc::boxed::Box;
17 #[cfg(feature = "std")]
18 use std::sync::Mutex;
19 
20 #[cfg(not(feature = "std"))]
21 use spin::Mutex;
22 
23 use crate::map::LargeMap;
24 
25 #[derive(Clone, Debug, Default)]
26 /// In memory pre-shared key storage backed by a HashMap.
27 ///
28 /// All clones of an instance of this type share the same underlying HashMap.
29 pub struct InMemoryPreSharedKeyStorage {
30     inner: Arc<Mutex<LargeMap<ExternalPskId, PreSharedKey>>>,
31 }
32 
33 impl InMemoryPreSharedKeyStorage {
34     /// Insert a pre-shared key into storage.
insert(&mut self, id: ExternalPskId, psk: PreSharedKey)35     pub fn insert(&mut self, id: ExternalPskId, psk: PreSharedKey) {
36         #[cfg(feature = "std")]
37         let mut lock = self.inner.lock().unwrap();
38 
39         #[cfg(not(feature = "std"))]
40         let mut lock = self.inner.lock();
41 
42         lock.insert(id, psk);
43     }
44 
45     /// Get a pre-shared key by `id`.
get(&self, id: &ExternalPskId) -> Option<PreSharedKey>46     pub fn get(&self, id: &ExternalPskId) -> Option<PreSharedKey> {
47         #[cfg(feature = "std")]
48         let lock = self.inner.lock().unwrap();
49 
50         #[cfg(not(feature = "std"))]
51         let lock = self.inner.lock();
52 
53         lock.get(id).cloned()
54     }
55 
56     /// Delete a pre-shared key from storage.
delete(&mut self, id: &ExternalPskId)57     pub fn delete(&mut self, id: &ExternalPskId) {
58         #[cfg(feature = "std")]
59         let mut lock = self.inner.lock().unwrap();
60 
61         #[cfg(not(feature = "std"))]
62         let mut lock = self.inner.lock();
63 
64         lock.remove(id);
65     }
66 }
67 
68 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
69 #[cfg_attr(mls_build_async, maybe_async::must_be_async)]
70 impl PreSharedKeyStorage for InMemoryPreSharedKeyStorage {
71     type Error = Infallible;
72 
get(&self, id: &ExternalPskId) -> Result<Option<PreSharedKey>, Self::Error>73     async fn get(&self, id: &ExternalPskId) -> Result<Option<PreSharedKey>, Self::Error> {
74         Ok(self.get(id))
75     }
76 }
77