summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorInna Palant <ipalant@google.com>2024-04-05 05:48:07 +0000
committerInna Palant <ipalant@google.com>2024-04-05 05:48:07 +0000
commit19e832d53460d0191b7d2ad302831f07448bb82b (patch)
tree66509c93116faf2116efaaf9b08ffa2e5fe3932c
parentaa9c8901eeced936708e64b63ec4f799917e9f42 (diff)
parente7cfe92d2530b456d5a06446a423487ce8c43d7d (diff)
downloadmls-rs-codec-19e832d53460d0191b7d2ad302831f07448bb82b.tar.gz
Merge remote-tracking branch 'origin/upstream'
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--Android.bp26
-rw-r--r--Cargo.lock290
-rw-r--r--Cargo.toml48
l---------LICENSE1
-rw-r--r--LICENSE-apache176
-rw-r--r--LICENSE-mit9
-rw-r--r--METADATA21
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--OWNERS2
-rw-r--r--cargo_embargo.json3
-rw-r--r--src/array.rs67
-rw-r--r--src/byte_vec.rs56
-rw-r--r--src/cow.rs35
-rw-r--r--src/iter.rs84
-rw-r--r--src/lib.rs132
-rw-r--r--src/map.rs89
-rw-r--r--src/option.rs81
-rw-r--r--src/stdint.rs84
-rw-r--r--src/string.rs78
-rw-r--r--src/tuple.rs38
-rw-r--r--src/varint.rs190
-rw-r--r--src/vec.rs100
-rw-r--r--src/writer.rs40
-rw-r--r--tests/macro_usage.rs164
25 files changed, 1820 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..b89d10b
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "468ffc50b740b540c5a840979b943d964ccdc7c7"
+ },
+ "path_in_vcs": "mls-rs-codec"
+} \ No newline at end of file
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..38fbcbc
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,26 @@
+// This file is generated by cargo_embargo.
+// Do not modify this file as changes will be overridden on upgrade.
+
+// TODO: Add license.
+rust_library {
+ name: "libmls_rs_codec",
+ host_supported: true,
+ crate_name: "mls_rs_codec",
+ cargo_env_compat: true,
+ cargo_pkg_version: "0.5.1",
+ srcs: ["src/lib.rs"],
+ edition: "2021",
+ features: [
+ "default",
+ "preallocate",
+ "std",
+ ],
+ rustlibs: ["libthiserror"],
+ proc_macros: ["libmls_rs_codec_derive"],
+ apex_available: [
+ "//apex_available:platform",
+ "//apex_available:anyapex",
+ ],
+ product_available: true,
+ vendor_available: true,
+}
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..63305e8
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,290 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "assert_matches"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
+
+[[package]]
+name = "bumpalo"
+version = "3.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3b1be7772ee4501dba05acbe66bb1e8760f6a6c474a36035631638e4415f130"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "console_error_panic_hook"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
+dependencies = [
+ "cfg-if",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "darling"
+version = "0.20.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c376d08ea6aa96aafe61237c7200d1241cb177b7d3a542d791f2d118e9cbb955"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.20.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33043dcd19068b8192064c704b3f83eb464f91f1ff527b44a4e2b08d9cdb8855"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.20.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5a91391accf613803c2a9bf9abccdbaa07c54b4244a5b64883f9c3c137c86be"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "js-sys"
+version = "0.3.68"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee"
+dependencies = [
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "log"
+version = "0.4.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+
+[[package]]
+name = "mls-rs-codec"
+version = "0.5.1"
+dependencies = [
+ "assert_matches",
+ "mls-rs-codec-derive",
+ "thiserror",
+ "wasm-bindgen",
+ "wasm-bindgen-test",
+]
+
+[[package]]
+name = "mls-rs-codec-derive"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f3fbf25b68713ec768c250f2b450c93ed997a5d2127b255d547ea7c6b21872b"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.78"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "scoped-tls"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
+
+[[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
+[[package]]
+name = "syn"
+version = "2.0.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f"
+dependencies = [
+ "cfg-if",
+ "wasm-bindgen-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b"
+dependencies = [
+ "bumpalo",
+ "log",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877b9c3f61ceea0e56331985743b13f3d25c406a7098d45180fb5f09bc19ed97"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838"
+
+[[package]]
+name = "wasm-bindgen-test"
+version = "0.3.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "143ddeb4f833e2ed0d252e618986e18bfc7b0e52f2d28d77d05b2f045dd8eb61"
+dependencies = [
+ "console_error_panic_hook",
+ "js-sys",
+ "scoped-tls",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-bindgen-test-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-test-macro"
+version = "0.3.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5211b7550606857312bba1d978a8ec75692eae187becc5e680444fffc5e6f89"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.68"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96565907687f7aceb35bc5fc03770a8a0471d82e479f25832f54a0e3f4b28446"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..66383f7
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,48 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+name = "mls-rs-codec"
+version = "0.5.1"
+description = "TLS codec and MLS specific encoding used by mls-rs"
+homepage = "https://github.com/awslabs/mls-rs"
+keywords = [
+ "mls",
+ "mls-rs",
+]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/awslabs/mls-rs"
+
+[dependencies.mls-rs-codec-derive]
+version = "0.1.0"
+
+[dependencies.thiserror]
+version = "1.0.40"
+optional = true
+
+[dev-dependencies.assert_matches]
+version = "1.5.0"
+
+[features]
+default = [
+ "std",
+ "preallocate",
+]
+preallocate = []
+std = ["dep:thiserror"]
+
+[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen]
+version = "0.2.79"
+
+[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-test]
+version = "0.3.26"
+default-features = false
diff --git a/LICENSE b/LICENSE
new file mode 120000
index 0000000..4ce7dad
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1 @@
+LICENSE-apache \ No newline at end of file
diff --git a/LICENSE-apache b/LICENSE-apache
new file mode 100644
index 0000000..831fbc5
--- /dev/null
+++ b/LICENSE-apache
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, orother modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/LICENSE-mit b/LICENSE-mit
new file mode 100644
index 0000000..e547c4a
--- /dev/null
+++ b/LICENSE-mit
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..4a3a3ef
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,21 @@
+name: "mls-rs-codec"
+description: "TLS codec and MLS specific encoding used by mls-rs"
+third_party {
+ identifier {
+ type: "crates.io"
+ value: "mls-rs-codec"
+ }
+ identifier {
+ type: "Archive"
+ value: "https://static.crates.io/crates/mls-rs-codec/mls-rs-codec-0.5.1.crate"
+ primary_source: true
+ }
+ version: "0.5.1"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2024
+ month: 3
+ day: 22
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..48bea6e
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1,2 @@
+# Bug component: 688011
+include platform/prebuilts/rust:main:/OWNERS
diff --git a/cargo_embargo.json b/cargo_embargo.json
new file mode 100644
index 0000000..cb908d7
--- /dev/null
+++ b/cargo_embargo.json
@@ -0,0 +1,3 @@
+{
+ "run_cargo": false
+}
diff --git a/src/array.rs b/src/array.rs
new file mode 100644
index 0000000..331e86e
--- /dev/null
+++ b/src/array.rs
@@ -0,0 +1,67 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+use alloc::vec::Vec;
+
+impl<const N: usize> MlsSize for [u8; N] {
+ #[inline(always)]
+ fn mls_encoded_len(&self) -> usize {
+ N
+ }
+}
+
+impl<const N: usize> MlsEncode for [u8; N] {
+ #[inline(always)]
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ writer.extend_from_slice(self);
+ Ok(())
+ }
+}
+
+impl<const N: usize> MlsDecode for [u8; N] {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ let array = reader
+ .get(..N)
+ .and_then(|head| head.try_into().ok())
+ .ok_or(crate::Error::UnexpectedEOF)?;
+
+ *reader = &reader[N..];
+ Ok(array)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ use alloc::vec;
+
+ use crate::{Error, MlsEncode};
+ use assert_matches::assert_matches;
+
+ #[test]
+ fn serialize_works() {
+ let arr = [0u8, 1u8, 2u8];
+ assert_eq!(arr.mls_encode_to_vec().unwrap(), vec![0u8, 1u8, 2u8]);
+ }
+
+ #[test]
+ fn serialize_round_trip() {
+ let arr = [0u8, 1u8, 2u8];
+ let serialized = arr.mls_encode_to_vec().unwrap();
+ let restored: [u8; 3] = crate::MlsDecode::mls_decode(&mut &*serialized).unwrap();
+ assert_eq!(arr, restored);
+ }
+
+ #[test]
+ fn end_of_file_error() {
+ let arr = [0u8, 1u8, 2u8];
+ let serialized = arr.mls_encode_to_vec().unwrap();
+ let res: Result<[u8; 5], Error> = crate::MlsDecode::mls_decode(&mut &*serialized);
+
+ assert_matches!(res, Err(Error::UnexpectedEOF))
+ }
+}
diff --git a/src/byte_vec.rs b/src/byte_vec.rs
new file mode 100644
index 0000000..923c580
--- /dev/null
+++ b/src/byte_vec.rs
@@ -0,0 +1,56 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{iter::mls_decode_split_on_collection, Error, MlsEncode, MlsSize, VarInt};
+
+use alloc::vec::Vec;
+
+/// Optimized length calculation for types that can be represented as u8 slices.
+pub fn mls_encoded_len<T>(data: &T) -> usize
+where
+ T: AsRef<[u8]>,
+{
+ fn slice_len(data: &[u8]) -> usize {
+ let len = data.len();
+ let header_length = VarInt::try_from(len).unwrap_or(VarInt(0)).mls_encoded_len();
+
+ header_length + len
+ }
+
+ slice_len(data.as_ref())
+}
+
+/// Optimized encoding for types that can be represented as u8 slices.
+pub fn mls_encode<T>(data: &T, writer: &mut Vec<u8>) -> Result<(), Error>
+where
+ T: AsRef<[u8]>,
+{
+ fn encode_slice(data: &[u8], writer: &mut Vec<u8>) -> Result<(), Error> {
+ let len = VarInt::try_from(data.len())?;
+
+ len.mls_encode(writer)?;
+ writer.extend_from_slice(data);
+
+ Ok(())
+ }
+
+ encode_slice(data.as_ref(), writer)
+}
+
+/// Optimized decoding for types that can be represented as `Vec<u8>`
+pub fn mls_decode<T>(reader: &mut &[u8]) -> Result<T, crate::Error>
+where
+ T: From<Vec<u8>>,
+{
+ fn decode_vec(reader: &mut &[u8]) -> Result<Vec<u8>, crate::Error> {
+ let (data, rest) = mls_decode_split_on_collection(reader)?;
+
+ *reader = rest;
+
+ Ok(data.to_vec())
+ }
+
+ let out = decode_vec(reader)?;
+ Ok(out.into())
+}
diff --git a/src/cow.rs b/src/cow.rs
new file mode 100644
index 0000000..5951ca3
--- /dev/null
+++ b/src/cow.rs
@@ -0,0 +1,35 @@
+use alloc::{
+ borrow::{Cow, ToOwned},
+ vec::Vec,
+};
+
+use crate::{Error, MlsDecode, MlsEncode, MlsSize};
+
+impl<'a, T> MlsSize for Cow<'a, T>
+where
+ T: MlsSize + ToOwned,
+{
+ fn mls_encoded_len(&self) -> usize {
+ self.as_ref().mls_encoded_len()
+ }
+}
+
+impl<'a, T> MlsEncode for Cow<'a, T>
+where
+ T: MlsEncode + ToOwned,
+{
+ #[inline]
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
+ self.as_ref().mls_encode(writer)
+ }
+}
+
+impl<'a, T> MlsDecode for Cow<'a, T>
+where
+ T: ToOwned,
+ <T as ToOwned>::Owned: MlsDecode,
+{
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error> {
+ MlsDecode::mls_decode(reader).map(Cow::Owned)
+ }
+}
diff --git a/src/iter.rs b/src/iter.rs
new file mode 100644
index 0000000..6408a68
--- /dev/null
+++ b/src/iter.rs
@@ -0,0 +1,84 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{MlsDecode, MlsEncode, MlsSize, VarInt};
+
+use alloc::vec::Vec;
+
+pub fn mls_encoded_len<T>(iter: impl Iterator<Item = T>) -> usize
+where
+ T: MlsSize,
+{
+ let len = iter.map(|x| x.mls_encoded_len()).sum::<usize>();
+
+ let header_length = VarInt::try_from(len).unwrap_or(VarInt(0)).mls_encoded_len();
+
+ header_length + len
+}
+
+#[cfg(feature = "preallocate")]
+pub fn mls_encode<I>(iter: I, writer: &mut Vec<u8>) -> Result<(), crate::Error>
+where
+ I: IntoIterator + Clone,
+ I::Item: MlsEncode,
+{
+ let len = iter
+ .clone()
+ .into_iter()
+ .map(|x| x.mls_encoded_len())
+ .sum::<usize>();
+
+ let header_length = VarInt::try_from(len)?;
+ header_length.mls_encode(writer)?;
+
+ writer.reserve(len);
+
+ iter.into_iter().try_for_each(|x| x.mls_encode(writer))?;
+
+ Ok(())
+}
+
+#[cfg(not(feature = "preallocate"))]
+pub fn mls_encode<I>(iter: I, writer: &mut Vec<u8>) -> Result<(), crate::Error>
+where
+ I: IntoIterator + Clone,
+ I::Item: MlsEncode,
+{
+ let mut buffer = Vec::new();
+
+ iter.into_iter()
+ .try_for_each(|x| x.mls_encode(&mut buffer))?;
+
+ let len = VarInt::try_from(buffer.len())?;
+
+ len.mls_encode(writer)?;
+ writer.extend(buffer);
+
+ Ok(())
+}
+
+pub fn mls_decode_collection<T, F>(reader: &mut &[u8], item_decode: F) -> Result<T, crate::Error>
+where
+ F: Fn(&mut &[u8]) -> Result<T, crate::Error>,
+{
+ let (mut data, rest) = mls_decode_split_on_collection(reader)?;
+
+ let items = item_decode(&mut data)?;
+
+ *reader = rest;
+
+ Ok(items)
+}
+
+pub fn mls_decode_split_on_collection<'b>(
+ reader: &mut &'b [u8],
+) -> Result<(&'b [u8], &'b [u8]), crate::Error> {
+ let len = VarInt::mls_decode(reader)?.0 as usize;
+
+ if len > reader.len() {
+ return Err(crate::Error::UnexpectedEOF);
+ }
+
+ Ok(reader.split_at(len))
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..7db6f86
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,132 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+#![cfg_attr(not(feature = "std"), no_std)]
+extern crate alloc;
+
+use alloc::boxed::Box;
+
+pub use alloc::vec::Vec;
+
+mod array;
+
+/// Optimized encoding and decoding for types that can be represented by `Vec<u8>`.
+///
+/// Compatible with derive macros by using `mls_codec(with = "mls_rs_codec::byte_vec")`
+pub mod byte_vec;
+
+pub mod iter;
+
+mod cow;
+mod map;
+mod option;
+mod stdint;
+mod string;
+mod tuple;
+mod varint;
+mod vec;
+
+pub use varint::*;
+
+pub use mls_rs_codec_derive::*;
+
+#[derive(Debug)]
+#[cfg_attr(feature = "std", derive(thiserror::Error))]
+#[non_exhaustive]
+pub enum Error {
+ #[cfg_attr(feature = "std", error("Integer out of range for VarInt"))]
+ VarIntOutOfRange,
+ #[cfg_attr(feature = "std", error("Invalid varint prefix {0}"))]
+ InvalidVarIntPrefix(u8),
+ #[cfg_attr(feature = "std", error("VarInt does not use the min-length encoding"))]
+ VarIntMinimumLengthEncoding,
+ #[cfg_attr(feature = "std", error("UnexpectedEOF"))]
+ UnexpectedEOF,
+ #[cfg_attr(feature = "std", error("Option marker out of range: {0}"))]
+ OptionOutOfRange(u8),
+ #[cfg_attr(feature = "std", error("Unsupported enum discriminant"))]
+ UnsupportedEnumDiscriminant,
+ #[cfg_attr(feature = "std", error("Expected UTF-8 string"))]
+ Utf8,
+ #[cfg_attr(feature = "std", error("mls codec error: {0}"))]
+ Custom(u8),
+}
+
+/// Trait that determines the encoded length in MLS encoding.
+pub trait MlsSize {
+ fn mls_encoded_len(&self) -> usize;
+}
+
+impl<T> MlsSize for &T
+where
+ T: MlsSize + ?Sized,
+{
+ #[inline]
+ fn mls_encoded_len(&self) -> usize {
+ (*self).mls_encoded_len()
+ }
+}
+
+impl<T> MlsSize for Box<T>
+where
+ T: MlsSize + ?Sized,
+{
+ #[inline]
+ fn mls_encoded_len(&self) -> usize {
+ self.as_ref().mls_encoded_len()
+ }
+}
+
+/// Trait to support serializing a type with MLS encoding.
+pub trait MlsEncode: MlsSize {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error>;
+
+ #[inline]
+ fn mls_encode_to_vec(&self) -> Result<Vec<u8>, Error> {
+ #[cfg(feature = "preallocate")]
+ let mut vec = Vec::with_capacity(self.mls_encoded_len());
+
+ #[cfg(not(feature = "preallocate"))]
+ let mut vec = Vec::new();
+
+ self.mls_encode(&mut vec)?;
+
+ Ok(vec)
+ }
+}
+
+impl<T> MlsEncode for &T
+where
+ T: MlsEncode + ?Sized,
+{
+ #[inline]
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
+ (*self).mls_encode(writer)
+ }
+}
+
+impl<T> MlsEncode for Box<T>
+where
+ T: MlsEncode + ?Sized,
+{
+ #[inline]
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
+ self.as_ref().mls_encode(writer)
+ }
+}
+
+/// Trait to support deserialzing to a type using MLS encoding.
+pub trait MlsDecode: Sized {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error>;
+}
+
+impl<T> MlsDecode for Box<T>
+where
+ T: MlsDecode + ?Sized,
+{
+ #[inline]
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error> {
+ T::mls_decode(reader).map(Box::new)
+ }
+}
diff --git a/src/map.rs b/src/map.rs
new file mode 100644
index 0000000..e1e29f9
--- /dev/null
+++ b/src/map.rs
@@ -0,0 +1,89 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use alloc::{collections::BTreeMap, vec::Vec};
+
+#[cfg(feature = "std")]
+use std::{collections::HashMap, hash::Hash};
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+
+#[cfg(feature = "std")]
+impl<K, V> MlsSize for HashMap<K, V>
+where
+ K: MlsSize,
+ V: MlsSize,
+{
+ fn mls_encoded_len(&self) -> usize {
+ crate::iter::mls_encoded_len(self.iter())
+ }
+}
+
+#[cfg(feature = "std")]
+impl<K, V> MlsEncode for HashMap<K, V>
+where
+ K: MlsEncode,
+ V: MlsEncode,
+{
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ crate::iter::mls_encode(self.iter(), writer)
+ }
+}
+
+#[cfg(feature = "std")]
+impl<K, V> MlsDecode for HashMap<K, V>
+where
+ K: MlsDecode + Hash + Eq,
+ V: MlsDecode,
+{
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ crate::iter::mls_decode_collection(reader, |data| {
+ let mut items = HashMap::new();
+
+ while !data.is_empty() {
+ items.insert(K::mls_decode(data)?, V::mls_decode(data)?);
+ }
+
+ Ok(items)
+ })
+ }
+}
+
+impl<K, V> MlsSize for BTreeMap<K, V>
+where
+ K: MlsSize,
+ V: MlsSize,
+{
+ fn mls_encoded_len(&self) -> usize {
+ crate::iter::mls_encoded_len(self.iter())
+ }
+}
+
+impl<K, V> MlsEncode for BTreeMap<K, V>
+where
+ K: MlsEncode,
+ V: MlsEncode,
+{
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ crate::iter::mls_encode(self.iter(), writer)
+ }
+}
+
+impl<K, V> MlsDecode for BTreeMap<K, V>
+where
+ K: MlsDecode + Eq + Ord,
+ V: MlsDecode,
+{
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ crate::iter::mls_decode_collection(reader, |data| {
+ let mut items = BTreeMap::new();
+
+ while !data.is_empty() {
+ items.insert(K::mls_decode(data)?, V::mls_decode(data)?);
+ }
+
+ Ok(items)
+ })
+ }
+}
diff --git a/src/option.rs b/src/option.rs
new file mode 100644
index 0000000..ac1023c
--- /dev/null
+++ b/src/option.rs
@@ -0,0 +1,81 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+use alloc::vec::Vec;
+
+impl<T: MlsSize> MlsSize for Option<T> {
+ #[inline]
+ fn mls_encoded_len(&self) -> usize {
+ 1 + match self {
+ Some(v) => v.mls_encoded_len(),
+ None => 0,
+ }
+ }
+}
+
+impl<T: MlsEncode> MlsEncode for Option<T> {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ if let Some(item) = self {
+ writer.push(1);
+ item.mls_encode(writer)
+ } else {
+ writer.push(0);
+ Ok(())
+ }
+ }
+}
+
+impl<T: MlsDecode> MlsDecode for Option<T> {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ match u8::mls_decode(reader)? {
+ 0 => Ok(None),
+ 1 => T::mls_decode(reader).map(Some),
+ n => Err(crate::Error::OptionOutOfRange(n)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use alloc::vec;
+
+ use crate::{Error, MlsDecode, MlsEncode};
+ use assert_matches::assert_matches;
+
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ #[test]
+ fn none_is_serialized_correctly() {
+ assert_eq!(vec![0u8], None::<u8>.mls_encode_to_vec().unwrap());
+ }
+
+ #[test]
+ fn some_is_serialized_correctly() {
+ assert_eq!(vec![1u8, 2], Some(2u8).mls_encode_to_vec().unwrap());
+ }
+
+ #[test]
+ fn none_round_trips() {
+ let val = None::<u8>;
+ let x = val.mls_encode_to_vec().unwrap();
+ assert_eq!(val, Option::mls_decode(&mut &*x).unwrap());
+ }
+
+ #[test]
+ fn some_round_trips() {
+ let val = Some(32u8);
+ let x = val.mls_encode_to_vec().unwrap();
+ assert_eq!(val, Option::mls_decode(&mut &*x).unwrap());
+ }
+
+ #[test]
+ fn deserializing_invalid_discriminant_fails() {
+ assert_matches!(
+ Option::<u8>::mls_decode(&mut &[2u8][..]),
+ Err(Error::OptionOutOfRange(_))
+ );
+ }
+}
diff --git a/src/stdint.rs b/src/stdint.rs
new file mode 100644
index 0000000..38460f5
--- /dev/null
+++ b/src/stdint.rs
@@ -0,0 +1,84 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+use alloc::vec::Vec;
+
+macro_rules! impl_stdint {
+ ($t:ty) => {
+ impl MlsSize for $t {
+ fn mls_encoded_len(&self) -> usize {
+ core::mem::size_of::<$t>()
+ }
+ }
+
+ impl MlsEncode for $t {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ writer.extend(self.to_be_bytes());
+ Ok(())
+ }
+ }
+
+ impl MlsDecode for $t {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ MlsDecode::mls_decode(reader).map(<$t>::from_be_bytes)
+ }
+ }
+ };
+}
+
+impl_stdint!(u8);
+impl_stdint!(u16);
+impl_stdint!(u32);
+impl_stdint!(u64);
+
+#[cfg(test)]
+mod tests {
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ use crate::{MlsDecode, MlsEncode};
+
+ use alloc::vec;
+
+ #[test]
+ fn u8_round_trip() {
+ let serialized = 42u8.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized, vec![42u8]);
+
+ let recovered = u8::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(recovered, 42u8);
+ }
+
+ #[test]
+ fn u16_round_trip() {
+ let serialized = 1024u16.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized, vec![4, 0]);
+
+ let recovered = u16::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(recovered, 1024u16);
+ }
+
+ #[test]
+ fn u32_round_trip() {
+ let serialized = 1000000u32.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized, vec![0, 15, 66, 64]);
+
+ let recovered = u32::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(recovered, 1000000u32);
+ }
+
+ #[test]
+ fn u64_round_trip() {
+ let serialized = 100000000000u64.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized, vec![0, 0, 0, 23, 72, 118, 232, 0]);
+
+ let recovered = u64::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(recovered, 100000000000u64);
+ }
+}
diff --git a/src/string.rs b/src/string.rs
new file mode 100644
index 0000000..120c82d
--- /dev/null
+++ b/src/string.rs
@@ -0,0 +1,78 @@
+use crate::{MlsDecode, MlsEncode, MlsSize};
+use alloc::{string::String, vec::Vec};
+
+impl MlsSize for str {
+ fn mls_encoded_len(&self) -> usize {
+ self.as_bytes().mls_encoded_len()
+ }
+}
+
+impl MlsEncode for str {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ self.as_bytes().mls_encode(writer)
+ }
+}
+
+impl MlsSize for String {
+ fn mls_encoded_len(&self) -> usize {
+ self.as_str().mls_encoded_len()
+ }
+}
+
+impl MlsEncode for String {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ self.as_str().mls_encode(writer)
+ }
+}
+
+impl MlsDecode for String {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ String::from_utf8(Vec::mls_decode(reader)?).map_err(|_| crate::Error::Utf8)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{Error, MlsDecode, MlsEncode};
+ use alloc::string::String;
+ use assert_matches::assert_matches;
+
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ #[test]
+ fn serialization_works() {
+ assert_eq!(
+ vec![3, b'b', b'a', b'r'],
+ "bar".mls_encode_to_vec().unwrap()
+ );
+ }
+
+ #[test]
+ fn data_round_trips() {
+ let val = "foo";
+ let x = val.mls_encode_to_vec().unwrap();
+ assert_eq!(val, String::mls_decode(&mut &*x).unwrap());
+ }
+
+ #[test]
+ fn empty_string_can_be_deserialized() {
+ assert_eq!(String::new(), String::mls_decode(&mut &[0u8][..]).unwrap());
+ }
+
+ #[test]
+ fn too_short_string_to_deserialize_gives_an_error() {
+ assert_matches!(
+ String::mls_decode(&mut &[2, 3][..]),
+ Err(Error::UnexpectedEOF)
+ );
+ }
+
+ #[test]
+ fn deserializing_invalid_utf8_fails() {
+ assert_matches!(
+ String::mls_decode(&mut &[0x02, 0xdf, 0xff][..]),
+ Err(Error::Utf8)
+ );
+ }
+}
diff --git a/src/tuple.rs b/src/tuple.rs
new file mode 100644
index 0000000..2d0e4ec
--- /dev/null
+++ b/src/tuple.rs
@@ -0,0 +1,38 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+
+use alloc::vec::Vec;
+
+impl<T, U> MlsSize for (T, U)
+where
+ T: MlsSize,
+ U: MlsSize,
+{
+ fn mls_encoded_len(&self) -> usize {
+ self.0.mls_encoded_len() + self.1.mls_encoded_len()
+ }
+}
+
+impl<T, U> MlsEncode for (T, U)
+where
+ T: MlsEncode,
+ U: MlsEncode,
+{
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ self.0.mls_encode(writer)?;
+ self.1.mls_encode(writer)
+ }
+}
+
+impl<T, U> MlsDecode for (T, U)
+where
+ T: MlsDecode,
+ U: MlsDecode,
+{
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ Ok((T::mls_decode(reader)?, U::mls_decode(reader)?))
+ }
+}
diff --git a/src/varint.rs b/src/varint.rs
new file mode 100644
index 0000000..7193a15
--- /dev/null
+++ b/src/varint.rs
@@ -0,0 +1,190 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::{Error, MlsDecode, MlsEncode, MlsSize};
+use alloc::vec::Vec;
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct VarInt(pub u32);
+
+impl VarInt {
+ pub const MAX: VarInt = VarInt((1 << 30) - 1);
+}
+
+impl From<VarInt> for u32 {
+ #[inline]
+ fn from(n: VarInt) -> u32 {
+ n.0
+ }
+}
+
+impl TryFrom<u32> for VarInt {
+ type Error = Error;
+
+ fn try_from(n: u32) -> Result<Self, Error> {
+ (n <= u32::from(VarInt::MAX))
+ .then_some(VarInt(n))
+ .ok_or(Error::VarIntOutOfRange)
+ }
+}
+
+impl TryFrom<usize> for VarInt {
+ type Error = Error;
+
+ fn try_from(n: usize) -> Result<Self, Error> {
+ u32::try_from(n)
+ .map_err(|_| Error::VarIntOutOfRange)?
+ .try_into()
+ }
+}
+
+impl MlsSize for VarInt {
+ #[inline]
+ fn mls_encoded_len(&self) -> usize {
+ count_bytes_to_encode_int(*self) as usize
+ }
+}
+
+impl MlsEncode for VarInt {
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
+ let mut bytes = self.0.to_be_bytes();
+
+ let bytes = match count_bytes_to_encode_int(*self) {
+ LengthEncoding::One => &bytes[3..],
+ LengthEncoding::Two => {
+ bytes[2] |= 0x40;
+ &bytes[2..]
+ }
+ LengthEncoding::Four => {
+ bytes[0] |= 0x80;
+ &bytes
+ }
+ };
+
+ writer.extend_from_slice(bytes);
+ Ok(())
+ }
+}
+
+impl MlsDecode for VarInt {
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, Error> {
+ let first = u8::mls_decode(reader)?;
+
+ let prefix = first >> 6;
+
+ let count = (prefix < 3)
+ .then_some(1 << prefix)
+ .ok_or(Error::InvalidVarIntPrefix(prefix))?;
+
+ let n = (1..count).try_fold(u32::from(first & 0x3f), |n, _| {
+ u8::mls_decode(reader).map(|b| n << 8 | u32::from(b))
+ })?;
+
+ let n = VarInt(n);
+
+ if count_bytes_to_encode_int(n) as usize == count {
+ Ok(n)
+ } else {
+ Err(Error::VarIntMinimumLengthEncoding)
+ }
+ }
+}
+
+/// Number of bytes to encode a variable-size integer.
+#[derive(Debug)]
+enum LengthEncoding {
+ One = 1,
+ Two = 2,
+ Four = 4,
+}
+
+fn count_bytes_to_encode_int(n: VarInt) -> LengthEncoding {
+ let used_bits = 32 - n.0.leading_zeros();
+ match used_bits {
+ 0..=6 => LengthEncoding::One,
+ 7..=14 => LengthEncoding::Two,
+ 15..=30 => LengthEncoding::Four,
+ _ => panic!("Such a large VarInt cannot be instantiated"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::VarInt;
+ use crate::{Error, MlsDecode, MlsEncode};
+ use assert_matches::assert_matches;
+
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ #[test]
+ fn zero_is_convertible_to_varint() {
+ assert_matches!(VarInt::try_from(0u32).map(u32::from), Ok(0));
+ }
+
+ #[test]
+ fn successor_of_max_varint_is_not_convertible_to_varint() {
+ let n = u32::from(VarInt::MAX) + 1;
+ assert_matches!(VarInt::try_from(n), Err(Error::VarIntOutOfRange));
+ }
+
+ #[test]
+ fn zero_serializes_as_single_null_byte() {
+ assert_eq!(
+ VarInt::try_from(0u32).unwrap().mls_encode_to_vec().unwrap(),
+ [0]
+ );
+ }
+
+ #[test]
+ fn zero_roundtrips() {
+ let n = VarInt::try_from(0u32).unwrap();
+
+ let serialized = n.mls_encode_to_vec().unwrap();
+ let restored = VarInt::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(restored, n);
+ }
+
+ #[test]
+ fn varint_max_roundtrips() {
+ let n = VarInt::MAX;
+
+ let serialized = n.mls_encode_to_vec().unwrap();
+ let restored = VarInt::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(restored, n);
+ }
+
+ fn decoding_matches_rfc(encoded: u32, decoded: u32) {
+ let bytes = encoded.to_be_bytes();
+
+ let start = bytes
+ .iter()
+ .position(|&b| b != 0)
+ .unwrap_or(bytes.len() - 1);
+
+ let bytes = &bytes[start..];
+
+ assert_eq!(
+ VarInt::mls_decode(&mut &*bytes).unwrap(),
+ VarInt::try_from(decoded).unwrap()
+ );
+ }
+
+ #[test]
+ fn decoding_0x25_matches_rfc_result() {
+ decoding_matches_rfc(0x25, 37);
+ }
+
+ #[test]
+ fn decoding_0x7bbd_matches_rfc_result() {
+ decoding_matches_rfc(0x7bbd, 15293);
+ }
+
+ #[test]
+ fn decoding_0x9d7f3e7d_matches_rfc_result() {
+ decoding_matches_rfc(0x9d7f3e7d, 494878333);
+ }
+}
diff --git a/src/vec.rs b/src/vec.rs
new file mode 100644
index 0000000..3d7f1a8
--- /dev/null
+++ b/src/vec.rs
@@ -0,0 +1,100 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use alloc::vec::Vec;
+
+use crate::{MlsDecode, MlsEncode, MlsSize};
+
+impl<T> MlsSize for [T]
+where
+ T: MlsSize,
+{
+ fn mls_encoded_len(&self) -> usize {
+ crate::iter::mls_encoded_len(self.iter())
+ }
+}
+
+impl<T> MlsSize for Vec<T>
+where
+ T: MlsSize,
+{
+ #[inline]
+ fn mls_encoded_len(&self) -> usize {
+ self.as_slice().mls_encoded_len()
+ }
+}
+
+impl<T> MlsEncode for [T]
+where
+ T: MlsEncode,
+{
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ crate::iter::mls_encode(self.iter(), writer)
+ }
+}
+
+impl<T> MlsEncode for Vec<T>
+where
+ T: MlsEncode,
+{
+ #[inline]
+ fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
+ self.as_slice().mls_encode(writer)
+ }
+}
+
+impl<T> MlsDecode for Vec<T>
+where
+ T: MlsDecode,
+{
+ fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
+ crate::iter::mls_decode_collection(reader, |data| {
+ let mut items = Vec::new();
+
+ while !data.is_empty() {
+ items.push(T::mls_decode(data)?);
+ }
+
+ Ok(items)
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{Error, MlsDecode, MlsEncode};
+ use alloc::{vec, vec::Vec};
+ use assert_matches::assert_matches;
+
+ #[cfg(target_arch = "wasm32")]
+ use wasm_bindgen_test::wasm_bindgen_test as test;
+
+ #[test]
+ fn serialization_works() {
+ assert_eq!(
+ vec![3, 1, 2, 3],
+ vec![1u8, 2, 3].mls_encode_to_vec().unwrap()
+ );
+ }
+
+ #[test]
+ fn data_round_trips() {
+ let val = vec![1u8, 2, 3];
+ let x = val.mls_encode_to_vec().unwrap();
+ assert_eq!(val, Vec::mls_decode(&mut &*x).unwrap());
+ }
+
+ #[test]
+ fn empty_vec_can_be_deserialized() {
+ assert_eq!(Vec::<u8>::new(), Vec::mls_decode(&mut &[0u8][..]).unwrap());
+ }
+
+ #[test]
+ fn too_few_items_to_deserialize_gives_an_error() {
+ assert_matches!(
+ Vec::<u8>::mls_decode(&mut &[2, 3][..]),
+ Err(Error::UnexpectedEOF)
+ );
+ }
+}
diff --git a/src/writer.rs b/src/writer.rs
new file mode 100644
index 0000000..9af487f
--- /dev/null
+++ b/src/writer.rs
@@ -0,0 +1,40 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use crate::Error;
+
+use alloc::vec::Vec;
+
+pub trait Writer {
+ fn write(&mut self, bytes: &[u8]) -> Result<(), Error>;
+}
+
+impl<T: Writer + ?Sized> Writer for &mut T {
+ #[inline]
+ fn write(&mut self, bytes: &[u8]) -> Result<(), Error> {
+ (**self).write(bytes)
+ }
+}
+
+impl Writer for &mut [u8] {
+ fn write(&mut self, bytes: &[u8]) -> Result<(), Error> {
+ if bytes.len() > self.len() {
+ return Err(Error::UnexpectedEOF);
+ }
+
+ let (a, b) = core::mem::take(self).split_at_mut(bytes.len());
+ a.copy_from_slice(bytes);
+ *self = b;
+
+ Ok(())
+ }
+}
+
+impl Writer for Vec<u8> {
+ #[inline]
+ fn write(&mut self, bytes: &[u8]) -> Result<(), Error> {
+ self.extend_from_slice(bytes);
+ Ok(())
+ }
+}
diff --git a/tests/macro_usage.rs b/tests/macro_usage.rs
new file mode 100644
index 0000000..72e17db
--- /dev/null
+++ b/tests/macro_usage.rs
@@ -0,0 +1,164 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// Copyright by contributors to this project.
+// SPDX-License-Identifier: (Apache-2.0 OR MIT)
+
+use mls_rs_codec::{MlsDecode, MlsEncode, MlsSize};
+
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
+struct TestTupleStruct(u64);
+
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
+struct TestFieldStruct {
+ item1: Option<u8>,
+ item2: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
+struct TestType {
+ field_a: u8,
+ field_b: Vec<u8>,
+ field_c: u16,
+ field_d: Option<Vec<u8>>,
+ field_e: u32,
+ field_f: Option<u16>,
+ field_g: Vec<TestTupleStruct>,
+ field_h: TestFieldStruct,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode)]
+struct BorrowedTestType<'a> {
+ field_a: u8,
+ field_b: Option<&'a [u8]>,
+ field_c: &'a [u16],
+}
+
+#[repr(u16)]
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
+enum TestEnum {
+ Case1 = 1u16,
+ Case2(TestFieldStruct) = 200u16,
+ Case3(TestTupleStruct) = 42u16,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
+struct TestGeneric<T: MlsSize + MlsEncode + MlsDecode>(T);
+
+#[test]
+fn round_trip_struct_encode() {
+ let item = TestType {
+ field_a: 42,
+ field_b: vec![1, 3, 5, 7, 9],
+ field_c: 65000,
+ field_d: Some(vec![0, 2, 4, 6, 8]),
+ field_e: 1000000,
+ field_f: None,
+ field_g: vec![
+ TestTupleStruct(100),
+ TestTupleStruct(200),
+ TestTupleStruct(300),
+ ],
+ field_h: TestFieldStruct {
+ item1: Some(42),
+ item2: 84,
+ },
+ };
+
+ let data = item.mls_encode_to_vec().unwrap();
+ let restored = TestType::mls_decode(&mut &*data).unwrap();
+
+ assert_eq!(restored, item);
+}
+
+#[test]
+fn round_trip_generic_encode() {
+ let item = TestGeneric(42u16);
+ let data = item.mls_encode_to_vec().unwrap();
+ let restored = TestGeneric::mls_decode(&mut &*data).unwrap();
+
+ assert_eq!(restored, item);
+}
+
+#[test]
+fn round_trip_enum_encode_simple() {
+ let item = TestEnum::Case1;
+
+ let serialized = item.mls_encode_to_vec().unwrap();
+ let decoded = TestEnum::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(serialized, 1u16.mls_encode_to_vec().unwrap());
+ assert_eq!(decoded, item);
+}
+
+#[test]
+fn round_trip_enum_encode_one_field() {
+ let item = TestEnum::Case2(TestFieldStruct {
+ item1: None,
+ item2: 42,
+ });
+
+ let serialized = item.mls_encode_to_vec().unwrap();
+ let decoded = TestEnum::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(decoded, item);
+}
+
+#[test]
+fn round_trip_enum_encode_one_tuple() {
+ let item = TestEnum::Case3(TestTupleStruct(42));
+
+ let serialized = item.mls_encode_to_vec().unwrap();
+ let decoded = TestEnum::mls_decode(&mut &*serialized).unwrap();
+
+ assert_eq!(decoded, item);
+}
+
+#[test]
+fn round_trip_custom_module_struct() {
+ #[derive(Debug, PartialEq, Eq, Clone, MlsSize, MlsEncode, MlsDecode)]
+ struct TestCustomStruct {
+ #[mls_codec(with = "self::test_with")]
+ value: u8,
+ }
+
+ let item = TestCustomStruct { value: 33 };
+
+ let serialized = item.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized.len(), 2);
+
+ let decoded = TestCustomStruct::mls_decode(&mut &*serialized).unwrap();
+ assert_eq!(item, decoded);
+}
+
+#[test]
+fn round_trip_custom_module_enum() {
+ #[derive(Debug, PartialEq, Eq, Clone, MlsSize, MlsEncode, MlsDecode)]
+ #[repr(u16)]
+ enum TestCustomEnum {
+ CustomCase(#[mls_codec(with = "self::test_with")] u8) = 2u16,
+ }
+
+ let item = TestCustomEnum::CustomCase(33);
+
+ let serialized = item.mls_encode_to_vec().unwrap();
+ assert_eq!(serialized.len(), 4);
+
+ let decoded = TestCustomEnum::mls_decode(&mut &*serialized).unwrap();
+ assert_eq!(item, decoded)
+}
+
+mod test_with {
+ use mls_rs_codec::MlsDecode;
+
+ pub fn mls_encoded_len(_val: &u8) -> usize {
+ 2
+ }
+
+ pub fn mls_encode(val: &u8, writer: &mut Vec<u8>) -> Result<(), mls_rs_codec::Error> {
+ writer.extend([*val, 42]);
+ Ok(())
+ }
+
+ pub fn mls_decode(reader: &mut &[u8]) -> Result<u8, mls_rs_codec::Error> {
+ Ok(<[u8; 2]>::mls_decode(reader)?[0])
+ }
+}