Skip to main content

mls_rs_codec/
lib.rs

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_attr(not(feature = "std"), no_std)]
6extern crate alloc;
7
8use alloc::boxed::Box;
9
10pub use alloc::vec::Vec;
11
12mod array;
13
14/// Optimized encoding and decoding for types that can be represented by `Vec<u8>`.
15///
16/// Compatible with derive macros by using `mls_codec(with = "mls_rs_codec::byte_vec")`
17pub mod byte_vec;
18
19pub mod iter;
20
21mod bool;
22mod cow;
23mod map;
24mod option;
25mod stdint;
26mod string;
27mod tuple;
28mod varint;
29mod vec;
30
31pub use varint::*;
32
33pub use mls_rs_codec_derive::*;
34
35#[derive(Debug)]
36#[cfg_attr(feature = "std", derive(thiserror::Error))]
37#[non_exhaustive]
38pub enum Error {
39    #[cfg_attr(feature = "std", error("Integer out of range for VarInt"))]
40    VarIntOutOfRange,
41    #[cfg_attr(feature = "std", error("Invalid varint prefix {0}"))]
42    InvalidVarIntPrefix(u8),
43    #[cfg_attr(feature = "std", error("VarInt does not use the min-length encoding"))]
44    VarIntMinimumLengthEncoding,
45    #[cfg_attr(feature = "std", error("UnexpectedEOF"))]
46    UnexpectedEOF,
47    #[cfg_attr(feature = "std", error("Option marker out of range: {0}"))]
48    OptionOutOfRange(u8),
49    #[cfg_attr(feature = "std", error("Unsupported enum discriminant"))]
50    UnsupportedEnumDiscriminant,
51    #[cfg_attr(feature = "std", error("Expected UTF-8 string"))]
52    Utf8,
53    #[cfg_attr(feature = "std", error("Invalid content"))]
54    InvalidContent,
55    #[cfg_attr(feature = "std", error("Unexpected trailing data"))]
56    UnexpectedTrailingData,
57    #[cfg_attr(feature = "std", error("mls codec error: {0}"))]
58    Custom(u8),
59}
60
61/// Trait that determines the encoded length in MLS encoding.
62pub trait MlsSize {
63    fn mls_encoded_len(&self) -> usize;
64}
65
66impl<T> MlsSize for &T
67where
68    T: MlsSize + ?Sized,
69{
70    #[inline]
71    fn mls_encoded_len(&self) -> usize {
72        (*self).mls_encoded_len()
73    }
74}
75
76impl<T> MlsSize for Box<T>
77where
78    T: MlsSize + ?Sized,
79{
80    #[inline]
81    fn mls_encoded_len(&self) -> usize {
82        self.as_ref().mls_encoded_len()
83    }
84}
85
86/// Trait to support serializing a type with MLS encoding.
87pub trait MlsEncode: MlsSize {
88    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error>;
89
90    #[inline]
91    fn mls_encode_to_vec(&self) -> Result<Vec<u8>, Error> {
92        #[cfg(feature = "preallocate")]
93        let mut vec = Vec::with_capacity(self.mls_encoded_len());
94
95        #[cfg(not(feature = "preallocate"))]
96        let mut vec = Vec::new();
97
98        self.mls_encode(&mut vec)?;
99
100        Ok(vec)
101    }
102}
103
104impl<T> MlsEncode for &T
105where
106    T: MlsEncode + ?Sized,
107{
108    #[inline]
109    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
110        (*self).mls_encode(writer)
111    }
112}
113
114impl<T> MlsEncode for Box<T>
115where
116    T: MlsEncode + ?Sized,
117{
118    #[inline]
119    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
120        self.as_ref().mls_encode(writer)
121    }
122}
123
124/// Trait to support deserialzing to a type using MLS encoding.
125pub trait MlsDecode: Sized {
126    fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error>;
127
128    /// Decode a value spanning all of `bytes`, rejecting any trailing data.
129    ///
130    /// [`mls_decode`](MlsDecode::mls_decode) only reads a prefix, which is what a field of a
131    /// larger structure needs but lets distinct inputs decode to the same top level value.
132    #[inline]
133    fn mls_decode_exhaustive(mut bytes: &[u8]) -> Result<Self, Error> {
134        let value = Self::mls_decode(&mut bytes)?;
135
136        bytes
137            .is_empty()
138            .then_some(value)
139            .ok_or(Error::UnexpectedTrailingData)
140    }
141}
142
143impl<T: MlsDecode> MlsDecode for Box<T> {
144    #[inline]
145    fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error> {
146        T::mls_decode(reader).map(Box::new)
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use crate::{Error, MlsDecode, MlsEncode};
153    use alloc::{vec, vec::Vec};
154    use assert_matches::assert_matches;
155
156    #[cfg(target_arch = "wasm32")]
157    use wasm_bindgen_test::wasm_bindgen_test as test;
158
159    #[test]
160    fn exhaustive_decode_accepts_exact_input() {
161        let serialized = vec![1u8, 2, 3].mls_encode_to_vec().unwrap();
162
163        assert_eq!(
164            Vec::<u8>::mls_decode_exhaustive(&serialized).unwrap(),
165            vec![1u8, 2, 3]
166        );
167    }
168
169    #[test]
170    fn exhaustive_decode_rejects_trailing_data() {
171        let mut serialized = vec![1u8, 2, 3].mls_encode_to_vec().unwrap();
172        serialized.push(0);
173
174        assert_matches!(
175            Vec::<u8>::mls_decode_exhaustive(&serialized),
176            Err(Error::UnexpectedTrailingData)
177        );
178    }
179
180    #[test]
181    fn exhaustive_decode_rejects_truncated_input() {
182        assert_matches!(
183            Vec::<u8>::mls_decode_exhaustive(&[2, 3]),
184            Err(Error::UnexpectedEOF)
185        );
186    }
187}