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::{borrow::Cow, vec::Vec};
6 use mls_rs_codec::{MlsDecode, MlsEncode, MlsSize};
7 
8 use crate::{client::MlsError, tree_kem::node::NodeVec};
9 
10 #[cfg_attr(
11     all(feature = "ffi", not(test)),
12     safer_ffi_gen::ffi_type(clone, opaque)
13 )]
14 #[derive(Debug, MlsSize, MlsEncode, MlsDecode, PartialEq, Clone)]
15 pub struct ExportedTree<'a>(pub(crate) Cow<'a, NodeVec>);
16 
17 #[cfg_attr(all(feature = "ffi", not(test)), ::safer_ffi_gen::safer_ffi_gen)]
18 impl<'a> ExportedTree<'a> {
new(node_data: NodeVec) -> Self19     pub(crate) fn new(node_data: NodeVec) -> Self {
20         Self(Cow::Owned(node_data))
21     }
22 
new_borrowed(node_data: &'a NodeVec) -> Self23     pub(crate) fn new_borrowed(node_data: &'a NodeVec) -> Self {
24         Self(Cow::Borrowed(node_data))
25     }
26 
to_bytes(&self) -> Result<Vec<u8>, MlsError>27     pub fn to_bytes(&self) -> Result<Vec<u8>, MlsError> {
28         self.mls_encode_to_vec().map_err(Into::into)
29     }
30 
byte_size(&self) -> usize31     pub fn byte_size(&self) -> usize {
32         self.mls_encoded_len()
33     }
34 
into_owned(self) -> ExportedTree<'static>35     pub fn into_owned(self) -> ExportedTree<'static> {
36         ExportedTree(Cow::Owned(self.0.into_owned()))
37     }
38 }
39 
40 #[cfg_attr(all(feature = "ffi", not(test)), ::safer_ffi_gen::safer_ffi_gen)]
41 impl ExportedTree<'static> {
from_bytes(bytes: &[u8]) -> Result<Self, MlsError>42     pub fn from_bytes(bytes: &[u8]) -> Result<Self, MlsError> {
43         Self::mls_decode(&mut &*bytes).map_err(Into::into)
44     }
45 }
46 
47 impl From<ExportedTree<'_>> for NodeVec {
from(value: ExportedTree) -> Self48     fn from(value: ExportedTree) -> Self {
49         value.0.into_owned()
50     }
51 }
52