| 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 |
use alloc::{collections::BTreeMap, vec::Vec}; |
| 6 |
|
| 7 |
#[cfg(feature = "std")] |
| 8 |
use std::{collections::HashMap, hash::Hash}; |
| 9 |
|
| 10 |
use crate::{MlsDecode, MlsEncode, MlsSize}; |
| 11 |
|
| 12 |
#[cfg(feature = "std")] |
| 13 |
impl<K, V> MlsSize for HashMap<K, V> |
| 14 |
where |
| 15 |
K: MlsSize, |
| 16 |
V: MlsSize, |
| 17 |
{ |
| 18 |
fn mls_encoded_len(&self) -> usize { |
| 19 |
crate::iter::mls_encoded_len(self.iter()) |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
#[cfg(feature = "std")] |
| 24 |
impl<K, V> MlsEncode for HashMap<K, V> |
| 25 |
where |
| 26 |
K: MlsEncode, |
| 27 |
V: MlsEncode, |
| 28 |
{ |
| 29 |
fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> { |
| 30 |
crate::iter::mls_encode(self.iter(), writer) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
#[cfg(feature = "std")] |
| 35 |
impl<K, V> MlsDecode for HashMap<K, V> |
| 36 |
where |
| 37 |
K: MlsDecode + Hash + Eq, |
| 38 |
V: MlsDecode, |
| 39 |
{ |
| 40 |
fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> { |
| 41 |
crate::iter::mls_decode_collection(reader, |data| { |
| 42 |
let mut items = HashMap::new(); |
| 43 |
|
| 44 |
while !data.is_empty() { |
| 45 |
items.insert(K::mls_decode(data)?, V::mls_decode(data)?); |
| 46 |
} |
| 47 |
|
| 48 |
Ok(items) |
| 49 |
}) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
impl<K, V> MlsSize for BTreeMap<K, V> |
| 54 |
where |
| 55 |
K: MlsSize, |
| 56 |
V: MlsSize, |
| 57 |
{ |
| 58 |
fn mls_encoded_len(&self) -> usize { |
| 59 |
crate::iter::mls_encoded_len(self.iter()) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
impl<K, V> MlsEncode for BTreeMap<K, V> |
| 64 |
where |
| 65 |
K: MlsEncode, |
| 66 |
V: MlsEncode, |
| 67 |
{ |
| 68 |
fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> { |
| 69 |
crate::iter::mls_encode(self.iter(), writer) |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
impl<K, V> MlsDecode for BTreeMap<K, V> |
| 74 |
where |
| 75 |
K: MlsDecode + Eq + Ord, |
| 76 |
V: MlsDecode, |
| 77 |
{ |
| 78 |
fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> { |
| 79 |
crate::iter::mls_decode_collection(reader, |data| { |
| 80 |
let mut items = BTreeMap::new(); |
| 81 |
|
| 82 |
while !data.is_empty() { |
| 83 |
items.insert(K::mls_decode(data)?, V::mls_decode(data)?); |
| 84 |
} |
| 85 |
|
| 86 |
Ok(items) |
| 87 |
}) |
| 88 |
} |
| 89 |
} |