| 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 crate::{MlsDecode, MlsEncode, MlsSize}; |
| 6 |
use alloc::vec::Vec; |
| 7 |
|
| 8 |
impl<const N: usize> MlsSize for [u8; N] { |
| 9 |
#[inline(always)] |
| 10 |
fn mls_encoded_len(&self) -> usize { |
| 11 |
N |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
impl<const N: usize> MlsEncode for [u8; N] { |
| 16 |
#[inline(always)] |
| 17 |
fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> { |
| 18 |
writer.extend_from_slice(self); |
| 19 |
Ok(()) |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
impl<const N: usize> MlsDecode for [u8; N] { |
| 24 |
fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> { |
| 25 |
let array = reader |
| 26 |
.get(..N) |
| 27 |
.and_then(|head| head.try_into().ok()) |
| 28 |
.ok_or(crate::Error::UnexpectedEOF)?; |
| 29 |
|
| 30 |
*reader = &reader[N..]; |
| 31 |
Ok(array) |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
#[cfg(test)] |
| 36 |
mod tests { |
| 37 |
#[cfg(target_arch = "wasm32")] |
| 38 |
use wasm_bindgen_test::wasm_bindgen_test as test; |
| 39 |
|
| 40 |
use alloc::vec; |
| 41 |
|
| 42 |
use crate::{Error, MlsEncode}; |
| 43 |
use assert_matches::assert_matches; |
| 44 |
|
| 45 |
#[test] |
| 46 |
fn serialize_works() { |
| 47 |
let arr = [0u8, 1u8, 2u8]; |
| 48 |
assert_eq!(arr.mls_encode_to_vec().unwrap(), vec![0u8, 1u8, 2u8]); |
| 49 |
} |
| 50 |
|
| 51 |
#[test] |
| 52 |
fn serialize_round_trip() { |
| 53 |
let arr = [0u8, 1u8, 2u8]; |
| 54 |
let serialized = arr.mls_encode_to_vec().unwrap(); |
| 55 |
let restored: [u8; 3] = crate::MlsDecode::mls_decode(&mut &*serialized).unwrap(); |
| 56 |
assert_eq!(arr, restored); |
| 57 |
} |
| 58 |
|
| 59 |
#[test] |
| 60 |
fn end_of_file_error() { |
| 61 |
let arr = [0u8, 1u8, 2u8]; |
| 62 |
let serialized = arr.mls_encode_to_vec().unwrap(); |
| 63 |
let res: Result<[u8; 5], Error> = crate::MlsDecode::mls_decode(&mut &*serialized); |
| 64 |
|
| 65 |
assert_matches!(res, Err(Error::UnexpectedEOF)) |
| 66 |
} |
| 67 |
} |