├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── derive ├── Cargo.toml └── src │ ├── encoding.rs │ └── lib.rs ├── ed-dark.svg ├── ed.svg ├── rustfmt.toml ├── src └── lib.rs └── tests └── derive.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ master, develop ] 6 | pull_request: 7 | branches: [ master, develop ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build-base: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v2 18 | - name: Use Nightly 19 | uses: actions-rs/toolchain@v1 20 | with: 21 | toolchain: nightly 22 | override: true 23 | - name: Build 24 | uses: actions-rs/cargo@v1 25 | with: 26 | command: build 27 | args: --verbose 28 | 29 | build-all-features: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v2 34 | - name: Use Nightly 35 | uses: actions-rs/toolchain@v1 36 | with: 37 | toolchain: nightly 38 | override: true 39 | - name: Build 40 | uses: actions-rs/cargo@v1 41 | with: 42 | command: build 43 | args: --verbose --all-features 44 | 45 | test-base: 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: Checkout 49 | uses: actions/checkout@v2 50 | - name: Use Nightly 51 | uses: actions-rs/toolchain@v1 52 | with: 53 | toolchain: nightly 54 | override: true 55 | - name: Test 56 | uses: actions-rs/cargo@v1 57 | with: 58 | command: test 59 | args: --verbose 60 | 61 | test-all-features: 62 | runs-on: ubuntu-latest 63 | steps: 64 | - name: Checkout 65 | uses: actions/checkout@v2 66 | - name: Use Nightly 67 | uses: actions-rs/toolchain@v1 68 | with: 69 | toolchain: nightly 70 | override: true 71 | - name: Test 72 | uses: actions-rs/cargo@v1 73 | with: 74 | command: test 75 | args: --verbose --all-features 76 | 77 | coverage: 78 | runs-on: ubuntu-latest 79 | steps: 80 | - name: Checkout 81 | uses: actions/checkout@v2 82 | - name: Use Nightly 83 | uses: actions-rs/toolchain@v1 84 | with: 85 | toolchain: nightly 86 | components: llvm-tools-preview 87 | override: true 88 | - name: Install Coverage Tooling 89 | uses: actions-rs/cargo@v1 90 | with: 91 | command: install 92 | args: cargo-llvm-cov 93 | - name: Run Coverage 94 | uses: actions-rs/cargo@v1 95 | with: 96 | command: llvm-cov 97 | args: --all-features --workspace --lcov --output-path lcov.info 98 | - name: Upload to codecov.io 99 | uses: codecov/codecov-action@v1 100 | with: 101 | files: lcov.info 102 | fail_ci_if_error: true 103 | 104 | format: 105 | runs-on: ubuntu-latest 106 | steps: 107 | - name: Checkout 108 | uses: actions/checkout@v2 109 | - name: Use Nightly 110 | uses: actions-rs/toolchain@v1 111 | with: 112 | toolchain: nightly 113 | components: rustfmt 114 | override: true 115 | - name: Check 116 | uses: actions-rs/cargo@v1 117 | with: 118 | command: fmt 119 | args: --all -- --check 120 | 121 | clippy: 122 | runs-on: ubuntu-latest 123 | steps: 124 | - name: Checkout 125 | uses: actions/checkout@v2 126 | - name: Use Nightly 127 | uses: actions-rs/toolchain@v1 128 | with: 129 | toolchain: nightly 130 | components: clippy 131 | override: true 132 | - name: Check 133 | uses: actions-rs/clippy-check@v1 134 | with: 135 | token: ${{ secrets.GITHUB_TOKEN }} 136 | args: --all-features -- -D warnings 137 | 138 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | macros/target 4 | macros/Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ed" 3 | version = "0.3.0" 4 | authors = ["Turbofish "] 5 | edition = "2018" 6 | description = "Minimalist crate for deterministic binary encodings" 7 | license = "Apache-2.0" 8 | 9 | [dependencies] 10 | ed-derive = { version = "0.3.0", path = "derive" } 11 | thiserror = "1.0" 12 | 13 | [profile.bench] 14 | lto = true 15 | 16 | [profile.release] 17 | lto = true 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 | 5 | ed 6 | 7 |

8 | 9 | *Minimalist crate for deterministic binary encodings in Rust* 10 | 11 | ![CI](https://github.com/nomic-io/ed/actions/workflows/ci.yml/badge.svg) 12 | [![codecov](https://codecov.io/gh/nomic-io/ed/branch/master/graph/badge.svg?token=BZK1DP4CF4)](https://codecov.io/gh/nomic-io/ed) 13 | [![Crate](https://img.shields.io/crates/v/ed.svg)](https://crates.io/crates/ed) 14 | [![API](https://docs.rs/ed/badge.svg)](https://docs.rs/ed) 15 | 16 | This crate provides `Encode` and `Decode` traits which can be implemented for any type that can be converted to or from bytes, and implements these traits for many built-in Rust types. It also provides derive macros so that `Encode` and `Decode` can be easily derived for structs. 17 | 18 | `ed` is far simpler than `serde` because it does not attempt to create an abstraction which allows arbitrary kinds of encoding (JSON, MessagePack, etc.), and instead forces focuses on binary encodings. It is also significantly faster than [`bincode`](https://docs.rs/bincode), the leading binary `serde` serializer. 19 | 20 | One aim of `ed` is to force top-level type authors to design their own encoding, rather than attempting to provide a one-size-fits-all encoding scheme. This lets users of `ed` be sure their encodings are as effiient as possible, and makes it easier to understand the encoding for compatability in other languages or libraries (contrasted with something like `bincode`, where it is not obvious how a type is being encoded without understanding the internals of `bincode`). 21 | 22 | Another property of this crate is a focus on determinism (important for cryptographically hashed types) - built-in encodings are always big-endian and there are no provided encodings for floating point numbers or `usize`. 23 | 24 | ## Usage 25 | ```rust 26 | use ed::{Encode, Decode}; 27 | 28 | // traits are implemented for built-in types 29 | let bytes = 123u32.encode()?; // `bytes` is a Vec 30 | let n = u32::decode(bytes.as_slice())?; // `n` is a u32 31 | 32 | // derive macros are available 33 | #[derive(Encode, Decode)] 34 | struct Foo { 35 | bar: (u32, u32), 36 | baz: Vec 37 | } 38 | 39 | // encoding and decoding can be done in-place to reduce allocations 40 | let mut bytes = vec![0xba; 40]; 41 | let mut foo = Foo { 42 | bar: (0, 0), 43 | baz: Vec::with_capacity(32) 44 | }; 45 | 46 | // in-place decode, re-using pre-allocated `foo.baz` vec 47 | foo.decode_into(bytes.as_slice())?; 48 | assert_eq!(foo, Foo { 49 | bar: (0xbabababa, 0xbabababa), 50 | baz: vec![0xba; 32] 51 | }); 52 | 53 | // in-place encode, into pre-allocated `bytes` vec 54 | bytes.clear(); 55 | foo.encode_into(&mut bytes)?; 56 | ``` 57 | Ed is currently used by [Nomic](https://github.com/nomic-io/nomic), a blockchain powering decentralized custody of Bitcoin, built on [Orga](https://github.com/turbofish-org/orga). 58 | 59 | ## Contributing 60 | 61 | Ed is an open-source project spearheaded by Turbofish. Anyone is able to contribute to Ed via GitHub. 62 | 63 | [Contribute to Ed](https://github.com/turbofish-io/ed/contribute) 64 | 65 | ## Security 66 | 67 | Ed is currently undergoing security audits. 68 | 69 | Vulnerabilities should not be reported through public channels, including GitHub Issues. You can report a vulnerability via GitHub's Private Vulnerability Reporting or to Turbofish at `security@turbofish.org`. 70 | 71 | [Report a Vulnerability](https://github.com/turbofish-org/ed/security/advisories/new) 72 | 73 | ## License 74 | 75 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use the files in this repository except in compliance with the License. You may obtain a copy of the License at 76 | 77 | https://www.apache.org/licenses/LICENSE-2.0 78 | 79 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 80 | 81 | --- 82 | 83 | Copyright © 2024 Turbofish, Inc. 84 | -------------------------------------------------------------------------------- /derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ed-derive" 3 | version = "0.3.0" 4 | authors = ["Matt Bell "] 5 | edition = "2018" 6 | description = "Derive macros for the ed crate" 7 | license = "MIT" 8 | 9 | [lib] 10 | proc-macro = true 11 | 12 | [dependencies] 13 | syn = "2.0.55" 14 | proc-macro2 = "1.0.79" 15 | quote = "1.0.35" 16 | -------------------------------------------------------------------------------- /derive/src/encoding.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Literal, Span, TokenStream}; 2 | use quote::quote; 3 | use syn::*; 4 | 5 | // TODO: use correct spans so errors are shown on fields 6 | 7 | pub fn derive_encode(item: proc_macro::TokenStream) -> proc_macro::TokenStream { 8 | let item = parse_macro_input!(item as DeriveInput); 9 | 10 | let output = match item.data.clone() { 11 | Data::Struct(data) => struct_encode(item, data), 12 | Data::Enum(data) => enum_encode(item, data), 13 | Data::Union(_) => unimplemented!("Not implemented for unions"), 14 | }; 15 | 16 | output.into() 17 | } 18 | 19 | fn struct_encode(item: DeriveInput, data: DataStruct) -> TokenStream { 20 | let name = &item.ident; 21 | 22 | let mut generics_sanitized = item.generics.clone(); 23 | generics_sanitized.params.iter_mut().for_each(|p| { 24 | if let GenericParam::Type(ref mut ty) = p { 25 | ty.default.take(); 26 | } 27 | }); 28 | let gen_params = gen_param_input(&item.generics); 29 | let terminated_bounds = iter_terminated_bounds(&item, quote!(::ed::Encode)); 30 | let where_preds = item 31 | .generics 32 | .where_clause 33 | .as_ref() 34 | .map(|w| { 35 | let preds = w.predicates.clone().into_iter(); 36 | quote!(#(#preds,)*) 37 | }) 38 | .unwrap_or_default(); 39 | 40 | let encode_into = fields_encode_into(iter_field_names(&data.fields), Some(quote!(self))); 41 | let encoding_length = 42 | fields_encoding_length(iter_field_names(&data.fields), Some(quote!(self))); 43 | 44 | let terminated = terminated_impl(&item); 45 | 46 | quote! { 47 | impl#generics_sanitized ::ed::Encode for #name#gen_params 48 | where #where_preds #terminated_bounds 49 | { 50 | #[inline] 51 | fn encode_into<__W: std::io::Write>(&self, mut dest: &mut __W) -> ::ed::Result<()> { 52 | #encode_into 53 | 54 | Ok(()) 55 | } 56 | 57 | #[inline] 58 | fn encoding_length(&self) -> ::ed::Result { 59 | Ok(#encoding_length) 60 | } 61 | } 62 | 63 | #terminated 64 | } 65 | } 66 | 67 | fn enum_encode(item: DeriveInput, data: DataEnum) -> TokenStream { 68 | let name = &item.ident; 69 | 70 | let mut generics_sanitized = item.generics.clone(); 71 | generics_sanitized.params.iter_mut().for_each(|p| { 72 | if let GenericParam::Type(ref mut ty) = p { 73 | ty.default.take(); 74 | } 75 | }); 76 | let gen_params = gen_param_input(&item.generics); 77 | let terminated_bounds = iter_terminated_bounds(&item, quote!(::ed::Encode)); 78 | let where_preds = item 79 | .generics 80 | .where_clause 81 | .as_ref() 82 | .map(|w| { 83 | let preds = w.predicates.clone().into_iter(); 84 | quote!(#(#preds,)*) 85 | }) 86 | .unwrap_or_default(); 87 | 88 | let arms = data 89 | .variants 90 | .iter() 91 | .filter(|v| filter_skipped_variants(*v)) 92 | .enumerate() 93 | .map(|(i, v)| { 94 | let i = i as u8; 95 | let ident = &v.ident; 96 | let destructure = variant_destructure(&v); 97 | let encode = fields_encode_into(iter_field_destructure(&v), None); 98 | quote!(Self::#ident #destructure => { 99 | dest.write_all(&[ #i ][..])?; 100 | #encode 101 | }) 102 | }); 103 | 104 | let encode_into = quote! { 105 | #[inline] 106 | fn encode_into<__W: std::io::Write>(&self, mut dest: &mut __W) -> ::ed::Result<()> { 107 | match self { 108 | #(#arms)* 109 | _ => return Err(::ed::Error::UnencodableVariant) 110 | } 111 | 112 | Ok(()) 113 | } 114 | }; 115 | 116 | let arms = data 117 | .variants 118 | .iter() 119 | .filter(|v| filter_skipped_variants(*v)) 120 | .map(|v| { 121 | let arm = fields_encoding_length(iter_field_destructure(&v), None); 122 | let ident = &v.ident; 123 | let destructure = variant_destructure(&v); 124 | quote!(Self::#ident #destructure => { #arm }) 125 | }); 126 | 127 | let encoding_length = quote! { 128 | #[inline] 129 | fn encoding_length(&self) -> ::ed::Result { 130 | Ok(1 + match self { 131 | #(#arms)* 132 | _ => return Err(::ed::Error::UnencodableVariant) 133 | }) 134 | } 135 | }; 136 | 137 | let terminated = terminated_impl(&item); 138 | 139 | quote! { 140 | impl#generics_sanitized ::ed::Encode for #name#gen_params 141 | where #where_preds #terminated_bounds 142 | { 143 | #encode_into 144 | #encoding_length 145 | } 146 | 147 | #terminated 148 | } 149 | } 150 | 151 | pub fn derive_decode(item: proc_macro::TokenStream) -> proc_macro::TokenStream { 152 | let item = parse_macro_input!(item as DeriveInput); 153 | 154 | let output = match item.data.clone() { 155 | Data::Struct(data) => struct_decode(item, data), 156 | Data::Enum(data) => enum_decode(item, data), 157 | Data::Union(_) => unimplemented!("Not implemented for unions"), 158 | }; 159 | 160 | output.into() 161 | } 162 | 163 | fn struct_decode(item: DeriveInput, data: DataStruct) -> TokenStream { 164 | let name = &item.ident; 165 | 166 | let decode = fields_decode(&data.fields, None); 167 | let decode_into = fields_decode_into(&data.fields, None); 168 | 169 | let mut generics = item.generics.clone(); 170 | generics.params.iter_mut().for_each(|p| { 171 | if let GenericParam::Type(ref mut ty) = p { 172 | ty.default.take(); 173 | } 174 | }); 175 | let gen_params = gen_param_input(&item.generics); 176 | let terminated_bounds = iter_terminated_bounds(&item, quote!(::ed::Decode)); 177 | let where_preds = item 178 | .generics 179 | .where_clause 180 | .as_ref() 181 | .map(|w| { 182 | let preds = w.predicates.clone().into_iter(); 183 | quote!(#(#preds,)*) 184 | }) 185 | .unwrap_or_default(); 186 | 187 | quote! { 188 | impl#generics ed::Decode for #name#gen_params 189 | where #where_preds #terminated_bounds 190 | { 191 | #[inline] 192 | fn decode<__R: std::io::Read>(mut input: __R) -> ed::Result { 193 | Ok(#decode) 194 | } 195 | 196 | #[inline] 197 | fn decode_into<__R: std::io::Read>(&mut self, mut input: __R) -> ed::Result<()> { 198 | #decode_into 199 | Ok(()) 200 | } 201 | } 202 | } 203 | } 204 | 205 | fn enum_decode(item: DeriveInput, data: DataEnum) -> TokenStream { 206 | let name = &item.ident; 207 | 208 | let mut generics = item.generics.clone(); 209 | generics.params.iter_mut().for_each(|p| { 210 | if let GenericParam::Type(ref mut ty) = p { 211 | ty.default.take(); 212 | } 213 | }); 214 | let gen_params = gen_param_input(&item.generics); 215 | let terminated_bounds = iter_terminated_bounds(&item, quote!(::ed::Decode)); 216 | let where_preds = item 217 | .generics 218 | .where_clause 219 | .as_ref() 220 | .map(|w| { 221 | let preds = w.predicates.clone().into_iter(); 222 | quote!(#(#preds,)*) 223 | }) 224 | .unwrap_or_default(); 225 | 226 | let arms = data 227 | .variants 228 | .iter() 229 | .filter(|v| filter_skipped_variants(*v)) 230 | .enumerate() 231 | .map(|(i, v)| { 232 | let i = i as u8; 233 | let arm = fields_decode(&v.fields, Some(v.ident.clone())); 234 | quote!(#i => { #arm }) 235 | }); 236 | 237 | quote! { 238 | impl#generics ::ed::Decode for #name#gen_params 239 | where #where_preds #terminated_bounds 240 | { 241 | #[inline] 242 | fn decode<__R: std::io::Read>(mut input: __R) -> ::ed::Result { 243 | let mut variant = [0; 1]; 244 | input.read_exact(&mut variant[..])?; 245 | let variant = variant[0]; 246 | 247 | Ok(match variant { 248 | #(#arms),* 249 | n => return Err(::ed::Error::UnexpectedByte(n)), 250 | }) 251 | } 252 | 253 | // TODO: decode_into 254 | } 255 | } 256 | } 257 | 258 | fn terminated_impl(item: &DeriveInput) -> TokenStream { 259 | let name = &item.ident; 260 | 261 | let mut generics = item.generics.clone(); 262 | generics.params.iter_mut().for_each(|p| { 263 | if let GenericParam::Type(ref mut ty) = p { 264 | ty.default.take(); 265 | } 266 | }); 267 | let gen_params = gen_param_input(&item.generics); 268 | let where_preds = item 269 | .generics 270 | .where_clause 271 | .as_ref() 272 | .map(|w| { 273 | let preds = w.predicates.clone().into_iter(); 274 | quote!(#(#preds,)*) 275 | }) 276 | .unwrap_or_default(); 277 | 278 | let bounds = iter_field_groups(item.clone()).map(|fields| { 279 | let bounds = fields 280 | .iter() 281 | .map(|f| f.ty.clone()) 282 | .map(|ty| quote!(#ty: ::ed::Terminated,)); 283 | quote!(#(#bounds)*) 284 | }); 285 | let bounds = quote!(#(#bounds)*); 286 | 287 | quote! { 288 | impl#generics ::ed::Terminated for #name#gen_params 289 | where #where_preds #bounds 290 | {} 291 | } 292 | } 293 | 294 | fn iter_fields(fields: &Fields) -> Box> { 295 | match fields.clone() { 296 | Fields::Named(fields) => Box::new(fields.named.into_iter()), 297 | Fields::Unnamed(fields) => Box::new(fields.unnamed.into_iter()), 298 | Fields::Unit => Box::new(vec![].into_iter()), 299 | } 300 | } 301 | 302 | fn iter_field_names(fields: &Fields) -> impl Iterator { 303 | iter_fields(fields) 304 | .enumerate() 305 | .map(|(i, field)| match field.ident { 306 | Some(ident) => quote!(#ident), 307 | None => { 308 | let i = Literal::usize_unsuffixed(i); 309 | quote!(#i) 310 | } 311 | }) 312 | } 313 | 314 | fn iter_field_destructure(variant: &Variant) -> Box> { 315 | match variant.fields.clone() { 316 | Fields::Named(fields) => Box::new(fields.named.into_iter().map(|v| { 317 | let ident = v.ident; 318 | quote!(#ident) 319 | })), 320 | Fields::Unnamed(_) => Box::new((0..variant.fields.len()).map(|i| { 321 | let ident = Ident::new( 322 | ("var".to_string() + i.to_string().as_str()).as_str(), 323 | Span::call_site(), 324 | ); 325 | quote!(#ident) 326 | })), 327 | Fields::Unit => Box::new(vec![].into_iter()), 328 | } 329 | } 330 | 331 | fn filter_skipped_variants(variant: &Variant) -> bool { 332 | !variant 333 | .attrs 334 | .iter() 335 | .any(|attr| attr.path().is_ident("skip")) 336 | } 337 | 338 | fn iter_field_groups(item: DeriveInput) -> Box> { 339 | match item.data { 340 | Data::Struct(data) => Box::new(vec![data.fields].into_iter()), 341 | Data::Enum(data) => Box::new( 342 | data.variants 343 | .into_iter() 344 | .filter(filter_skipped_variants) 345 | .map(|v| v.fields), 346 | ), 347 | Data::Union(_) => unimplemented!("Not implemented for unions"), 348 | } 349 | } 350 | 351 | fn iter_terminated_bounds(item: &DeriveInput, add: TokenStream) -> TokenStream { 352 | let bounds = iter_field_groups(item.clone()).map(|fields| { 353 | if fields.len() == 0 { 354 | return quote!(); 355 | } 356 | 357 | let bounds = iter_fields(&fields) 358 | .map(|f| f.ty.clone()) 359 | .enumerate() 360 | .map(|(i, ty)| { 361 | let terminated = if i < fields.len() - 1 { 362 | quote!(::ed::Terminated+) 363 | } else { 364 | quote!() 365 | }; 366 | quote!(#ty: #terminated #add,) 367 | }); 368 | quote!(#(#bounds)*) 369 | }); 370 | quote!(#(#bounds)*) 371 | } 372 | 373 | fn variant_destructure(variant: &Variant) -> TokenStream { 374 | let names = iter_field_destructure(&variant); 375 | match &variant.fields { 376 | Fields::Named(_) => quote!({ #(#names),* }), 377 | Fields::Unnamed(_) => quote!(( #(#names),* )), 378 | Fields::Unit => quote!(), 379 | } 380 | } 381 | 382 | fn gen_param_input(generics: &Generics) -> TokenStream { 383 | let gen_params = generics.params.iter().map(|p| match p { 384 | GenericParam::Type(p) => { 385 | let ident = &p.ident; 386 | quote!(#ident) 387 | } 388 | GenericParam::Lifetime(p) => { 389 | let ident = &p.lifetime.ident; 390 | quote!(#ident) 391 | } 392 | GenericParam::Const(p) => { 393 | let ident = &p.ident; 394 | quote!(#ident) 395 | } 396 | }); 397 | 398 | if gen_params.len() == 0 { 399 | quote!() 400 | } else { 401 | quote!(<#(#gen_params),*>) 402 | } 403 | } 404 | 405 | fn fields_encode_into( 406 | field_names: impl Iterator, 407 | parent: Option, 408 | ) -> TokenStream { 409 | let field_names: Vec<_> = field_names.collect(); 410 | let mut field_names_minus_last = field_names.clone(); 411 | field_names_minus_last.pop(); 412 | 413 | let parent_dot = parent.as_ref().map(|_| quote!(.)); 414 | 415 | quote! { 416 | #(#parent#parent_dot#field_names.encode_into(&mut dest)?;)* 417 | } 418 | } 419 | 420 | fn fields_encoding_length( 421 | field_names: impl Iterator, 422 | parent: Option, 423 | ) -> TokenStream { 424 | let parent_dot = parent.as_ref().map(|_| quote!(.)); 425 | 426 | quote! { 427 | 0 #( + #parent#parent_dot#field_names.encoding_length()?)* 428 | } 429 | } 430 | 431 | fn fields_decode(fields: &Fields, variant_name: Option) -> TokenStream { 432 | let field_names = iter_field_names(&fields); 433 | 434 | let item_name = match variant_name { 435 | Some(name) => quote!(Self::#name), 436 | None => quote!(Self), 437 | }; 438 | 439 | quote! { 440 | #item_name { 441 | #( 442 | #field_names: ::ed::Decode::decode(&mut input)?, 443 | )* 444 | } 445 | } 446 | } 447 | 448 | fn fields_decode_into(fields: &Fields, parent: Option) -> TokenStream { 449 | let field_names = iter_field_names(&fields); 450 | let parent = parent.unwrap_or(quote!(self)); 451 | 452 | quote! { 453 | #( 454 | #parent.#field_names.decode_into(&mut input)?; 455 | )* 456 | } 457 | } 458 | -------------------------------------------------------------------------------- /derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod encoding; 2 | 3 | #[proc_macro_derive(Encode, attributes(skip))] 4 | pub fn encode(item: proc_macro::TokenStream) -> proc_macro::TokenStream { 5 | encoding::derive_encode(item) 6 | } 7 | 8 | #[proc_macro_derive(Decode, attributes(skip))] 9 | pub fn decode(item: proc_macro::TokenStream) -> proc_macro::TokenStream { 10 | encoding::derive_decode(item) 11 | } 12 | -------------------------------------------------------------------------------- /ed-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /ed.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | comment_width = 80 2 | wrap_comments = true 3 | 4 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! *`ed` is a minimalist crate for deterministic binary encodings.* 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This crate provides `Encode` and `Decode` traits which can be implemented 6 | //! for any type that can be converted to or from bytes, and implements these 7 | //! traits for many built-in Rust types. It also provides derive macros so that 8 | //! `Encode` and `Decode` can be easily derived for structs. 9 | //! 10 | //! `ed` is far simpler than `serde` because it does not attempt to create an 11 | //! abstraction which allows arbitrary kinds of encoding (JSON, MessagePack, 12 | //! etc.), and instead forces focuses on binary encodings. It is also 13 | //! significantly faster than [`bincode`](https://docs.rs/bincode), the leading 14 | //! binary `serde` serializer. 15 | //! 16 | //! One aim of `ed` is to force top-level type authors to design their own 17 | //! encoding, rather than attempting to provide a one-size-fits-all encoding 18 | //! scheme. This lets users of `ed` be sure their encodings are as effiient as 19 | //! possible, and makes it easier to understand the encoding for compatability 20 | //! in other languages or libraries (contrasted with something like `bincode`, 21 | //! where it is not obvious how a type is being encoded without understanding 22 | //! the internals of `bincode`). 23 | //! 24 | //! Another property of this crate is a focus on determinism (important for 25 | //! cryptographically hashed types) - built-in encodings are always big-endian 26 | //! and there are no provided encodings for floating point numbers or `usize`. 27 | //! 28 | //! ## Usage 29 | //! 30 | //! ```rust 31 | //! #![feature(trivial_bounds)] 32 | //! use ed::{Encode, Decode}; 33 | //! 34 | //! # fn main() -> ed::Result<()> { 35 | //! // traits are implemented for built-in types 36 | //! let bytes = 123u32.encode()?; // `bytes` is a Vec 37 | //! let n = u32::decode(bytes.as_slice())?; // `n` is a u32 38 | //! 39 | //! // derive macros are available 40 | //! #[derive(Encode, Decode)] 41 | //! # #[derive(PartialEq, Eq, Debug)] 42 | //! struct Foo { 43 | //! bar: (u32, u32), 44 | //! baz: Vec 45 | //! } 46 | //! 47 | //! // encoding and decoding can be done in-place to reduce allocations 48 | //! 49 | //! let mut bytes = vec![0xba; 40]; 50 | //! let mut foo = Foo { 51 | //! bar: (0, 0), 52 | //! baz: Vec::with_capacity(32) 53 | //! }; 54 | //! 55 | //! // in-place decode, re-using pre-allocated `foo.baz` vec 56 | //! foo.decode_into(bytes.as_slice())?; 57 | //! assert_eq!(foo, Foo { 58 | //! bar: (0xbabababa, 0xbabababa), 59 | //! baz: vec![0xba; 32] 60 | //! }); 61 | //! 62 | //! // in-place encode, into pre-allocated `bytes` vec 63 | //! bytes.clear(); 64 | //! foo.encode_into(&mut bytes)?; 65 | //! 66 | //! # Ok(()) 67 | //! # } 68 | //! ``` 69 | 70 | #![warn(missing_docs)] 71 | #![warn(clippy::missing_docs_in_private_items)] 72 | 73 | use std::convert::TryInto; 74 | use std::io::{Read, Write}; 75 | 76 | pub use ed_derive::*; 77 | 78 | /// An enum that defines the `ed` error types. 79 | #[derive(thiserror::Error, Debug)] 80 | pub enum Error { 81 | // TODO: more variants 82 | /// An error that occurs when decoding a value and encountering a byte that 83 | /// was not in a valid expected range. 84 | #[error("Unexpected byte: {0}")] 85 | UnexpectedByte(u8), 86 | /// An error that occurs when encoding an enum value that does not have an 87 | /// encoding defined. 88 | #[error("Unencodable variant")] 89 | UnencodableVariant, 90 | /// An io error that occurs when reading or writing bytes. 91 | #[error(transparent)] 92 | IOError(#[from] std::io::Error), 93 | } 94 | 95 | /// A Result bound to the standard `ed` error type. 96 | pub type Result = std::result::Result; 97 | 98 | /// A trait for values that can be encoded into bytes deterministically. 99 | pub trait Encode { 100 | /// Writes the encoded representation of the value to the destination 101 | /// writer. Can error due to either a write error from `dest`, or an 102 | /// encoding error for types where invalid values are possible. 103 | /// 104 | /// It may be more convenient to call [`encode`](#method.encode) which 105 | /// returns bytes, however `encode_into` will often be more efficient since 106 | /// it can write the encoding without necessarily allocating a new 107 | /// `Vec`. 108 | fn encode_into(&self, dest: &mut W) -> Result<()>; 109 | 110 | /// Calculates the length of the encoding for this value. Can error for 111 | /// types where invalid values are possible. 112 | fn encoding_length(&self) -> Result; 113 | 114 | /// Returns the encoded representation of the value as a `Vec`. 115 | /// 116 | /// While this method is convenient, it will often be more efficient to call 117 | /// [`encode_into`](#method.encode_into) since `encode` usually involves 118 | /// allocating a new `Vec`. 119 | #[inline] 120 | fn encode(&self) -> Result> { 121 | let length = self.encoding_length()?; 122 | let mut bytes = Vec::with_capacity(length); 123 | self.encode_into(&mut bytes)?; 124 | Ok(bytes) 125 | } 126 | } 127 | 128 | /// A trait for values that can be decoded from bytes deterministically. 129 | pub trait Decode: Sized { 130 | /// Reads bytes from the reader and returns the decoded value. 131 | /// 132 | /// When possible, calling [`decode_into`](#method.decode_into) will often 133 | /// be more efficient since it lets the caller reuse memory to avoid 134 | /// allocating for fields with types such as `Vec`. 135 | fn decode(input: R) -> Result; 136 | 137 | /// Reads bytes from the reader and mutates self to the decoded value. 138 | /// 139 | /// This is often more efficient than calling [`decode`](#method.decode) 140 | /// when reading fields with heap-allocated types such as `Vec` since it 141 | /// can reuse the memory already allocated in self. 142 | /// 143 | /// When possible, implementations should recursively call `decode_into` on 144 | /// any child fields. 145 | /// 146 | /// The default implementation of `decode_into` simply calls 147 | /// [`decode`](#method.decode) for ease of implementation, but should be 148 | /// overridden when in-place decoding is possible. 149 | #[inline] 150 | fn decode_into(&mut self, input: R) -> Result<()> { 151 | let value = Self::decode(input)?; 152 | *self = value; 153 | Ok(()) 154 | } 155 | } 156 | 157 | /// A type is `Terminated` the length of the value being read can be determined 158 | /// when decoding. 159 | /// 160 | /// Since `Terminated` is an auto trait, it is automatically present for any 161 | /// type made of fields which are all `Terminated`. 162 | /// 163 | /// Consider a type like `u32` - it is always 4 bytes long. If a slice of length 164 | /// 5 was passed to its `decode` method, it would know to stop reading after the 165 | /// 4th byte, which means it is `Terminated`. 166 | /// 167 | /// For an example of something which is NOT terminated, consider `Vec`. Its 168 | /// encoding and decoding do not use a length prefix or end with a null byte, so 169 | /// `decode` would have no way to know where to stop reading. 170 | pub trait Terminated {} 171 | 172 | /// Generates `Encode`, `Decode`, and `Terminated` impls for a fixed-size 173 | /// integer type. 174 | macro_rules! int_impl { 175 | ($type:ty, $length:expr) => { 176 | impl Encode for $type { 177 | #[doc = "Encodes the integer as fixed-size big-endian bytes."] 178 | #[inline] 179 | fn encode_into(&self, dest: &mut W) -> Result<()> { 180 | let bytes = self.to_be_bytes(); 181 | dest.write_all(&bytes[..])?; 182 | Ok(()) 183 | } 184 | 185 | #[doc = "Returns the size of the integer in bytes. Will always"] 186 | #[doc = " return an `Ok` result."] 187 | #[inline] 188 | fn encoding_length(&self) -> Result { 189 | Ok($length) 190 | } 191 | } 192 | 193 | impl Decode for $type { 194 | #[doc = "Decodes the integer from fixed-size big-endian bytes."] 195 | #[inline] 196 | fn decode(mut input: R) -> Result { 197 | let mut bytes = [0; $length]; 198 | input.read_exact(&mut bytes[..])?; 199 | Ok(Self::from_be_bytes(bytes)) 200 | } 201 | } 202 | 203 | impl Terminated for $type {} 204 | }; 205 | } 206 | 207 | int_impl!(u8, 1); 208 | int_impl!(u16, 2); 209 | int_impl!(u32, 4); 210 | int_impl!(u64, 8); 211 | int_impl!(u128, 16); 212 | int_impl!(i8, 1); 213 | int_impl!(i16, 2); 214 | int_impl!(i32, 4); 215 | int_impl!(i64, 8); 216 | int_impl!(i128, 16); 217 | 218 | impl Encode for bool { 219 | /// Encodes the boolean as a single byte: 0 for false or 1 for true. 220 | #[inline] 221 | fn encode_into(&self, dest: &mut W) -> Result<()> { 222 | let bytes = [*self as u8]; 223 | dest.write_all(&bytes[..])?; 224 | Ok(()) 225 | } 226 | 227 | /// Always returns Ok(1). 228 | #[inline] 229 | fn encoding_length(&self) -> Result { 230 | Ok(1) 231 | } 232 | } 233 | 234 | impl Decode for bool { 235 | /// Decodes the boolean from a single byte: 0 for false or 1 for true. 236 | /// Errors for any other value. 237 | #[inline] 238 | fn decode(mut input: R) -> Result { 239 | let mut buf = [0; 1]; 240 | input.read_exact(&mut buf[..])?; 241 | match buf[0] { 242 | 0 => Ok(false), 243 | 1 => Ok(true), 244 | byte => Err(Error::UnexpectedByte(byte)), 245 | } 246 | } 247 | } 248 | 249 | impl Terminated for bool {} 250 | 251 | impl Encode for Option { 252 | /// Encodes as a 0 byte for `None`, or as a 1 byte followed by the encoding 253 | /// of the inner value for `Some`. 254 | #[inline] 255 | fn encode_into(&self, dest: &mut W) -> Result<()> { 256 | match self { 257 | None => dest.write_all(&[0]).map_err(Error::IOError), 258 | Some(value) => { 259 | dest.write_all(&[1]).map_err(Error::IOError)?; 260 | value.encode_into(dest) 261 | } 262 | } 263 | } 264 | 265 | /// Length will be 1 for `None`, or 1 plus the encoding length of the inner 266 | /// value for `Some`. 267 | #[inline] 268 | fn encoding_length(&self) -> Result { 269 | match self { 270 | None => Ok(1), 271 | Some(value) => Ok(1 + value.encoding_length()?), 272 | } 273 | } 274 | } 275 | 276 | impl Decode for Option { 277 | /// Decodes a 0 byte as `None`, or a 1 byte followed by the encoding of the 278 | /// inner value as `Some`. Errors for all other values. 279 | #[inline] 280 | fn decode(input: R) -> Result { 281 | let mut option: Option = None; 282 | option.decode_into(input)?; 283 | Ok(option) 284 | } 285 | 286 | /// Decodes a 0 byte as `None`, or a 1 byte followed by the encoding of the 287 | /// inner value as `Some`. Errors for all other values. 288 | // 289 | // When the first byte is 1 and self is `Some`, `decode_into` will be called 290 | // on the inner type. When the first byte is 1 and self is `None`, `decode` 291 | // will be called for the inner type. 292 | #[inline] 293 | fn decode_into(&mut self, mut input: R) -> Result<()> { 294 | let mut byte = [0; 1]; 295 | input.read_exact(&mut byte[..])?; 296 | 297 | match byte[0] { 298 | 0 => *self = None, 299 | 1 => match self { 300 | None => *self = Some(T::decode(input)?), 301 | Some(value) => value.decode_into(input)?, 302 | }, 303 | byte => { 304 | return Err(Error::UnexpectedByte(byte)); 305 | } 306 | }; 307 | 308 | Ok(()) 309 | } 310 | } 311 | 312 | impl Terminated for Option {} 313 | 314 | impl Encode for () { 315 | /// Encoding a unit tuple is a no-op. 316 | #[inline] 317 | fn encode_into(&self, _: &mut W) -> Result<()> { 318 | Ok(()) 319 | } 320 | 321 | /// Always returns Ok(0). 322 | #[inline] 323 | fn encoding_length(&self) -> Result { 324 | Ok(0) 325 | } 326 | } 327 | 328 | impl Decode for () { 329 | /// Returns a unit tuple without reading any bytes. 330 | #[inline] 331 | fn decode(_: R) -> Result { 332 | Ok(()) 333 | } 334 | } 335 | 336 | impl Terminated for () {} 337 | 338 | /// Generates `Encode`, `Decode`, and `Terminated` implementations for tuples. 339 | macro_rules! tuple_impl { 340 | ($( $type:ident ),*; $last_type:ident) => { 341 | impl<$($type: Encode + Terminated,)* $last_type: Encode> Encode for ($($type,)* $last_type,) { 342 | #[doc = "Encodes the fields of the tuple one after another, in"] 343 | #[doc = " order."] 344 | #[allow(non_snake_case, unused_mut)] 345 | #[inline] 346 | fn encode_into(&self, mut dest: &mut W) -> Result<()> { 347 | let ($($type,)* $last_type,) = self; 348 | $($type.encode_into(&mut dest)?;)* 349 | $last_type.encode_into(dest) 350 | } 351 | 352 | #[doc = "Returns the sum of the encoding lengths of the fields of"] 353 | #[doc = " the tuple."] 354 | #[allow(non_snake_case)] 355 | #[allow(clippy::needless_question_mark)] 356 | #[inline] 357 | fn encoding_length(&self) -> Result { 358 | let ($($type,)* $last_type,) = self; 359 | Ok( 360 | $($type.encoding_length()? +)* 361 | $last_type.encoding_length()? 362 | ) 363 | } 364 | } 365 | 366 | impl<$($type: Decode + Terminated,)* $last_type: Decode> Decode for ($($type,)* $last_type,) { 367 | #[doc = "Decodes the fields of the tuple one after another, in"] 368 | #[doc = " order."] 369 | #[allow(unused_mut)] 370 | #[inline] 371 | fn decode(mut input: R) -> Result { 372 | Ok(( 373 | $($type::decode(&mut input)?,)* 374 | $last_type::decode(input)?, 375 | )) 376 | } 377 | 378 | #[doc = "Decodes the fields of the tuple one after another, in"] 379 | #[doc = " order."] 380 | #[doc = ""] 381 | #[doc = "Recursively calls `decode_into` for each field."] 382 | #[allow(non_snake_case, unused_mut)] 383 | #[inline] 384 | fn decode_into(&mut self, mut input: R) -> Result<()> { 385 | let ($($type,)* $last_type,) = self; 386 | $($type.decode_into(&mut input)?;)* 387 | $last_type.decode_into(input)?; 388 | Ok(()) 389 | } 390 | } 391 | 392 | impl<$($type: Terminated,)* $last_type: Terminated> Terminated for ($($type,)* $last_type,) {} 393 | } 394 | } 395 | 396 | tuple_impl!(; A); 397 | tuple_impl!(A; B); 398 | tuple_impl!(A, B; C); 399 | tuple_impl!(A, B, C; D); 400 | tuple_impl!(A, B, C, D; E); 401 | tuple_impl!(A, B, C, D, E; F); 402 | tuple_impl!(A, B, C, D, E, F; G); 403 | tuple_impl!(A, B, C, D, E, F, G; H); 404 | tuple_impl!(A, B, C, D, E, F, G, H; I); 405 | tuple_impl!(A, B, C, D, E, F, G, H, I; J); 406 | tuple_impl!(A, B, C, D, E, F, G, H, I, J; K); 407 | tuple_impl!(A, B, C, D, E, F, G, H, I, J, K; L); 408 | 409 | impl Encode for [T; N] { 410 | #[inline] 411 | fn encode_into(&self, mut dest: &mut W) -> Result<()> { 412 | for element in self[..].iter() { 413 | element.encode_into(&mut dest)?; 414 | } 415 | Ok(()) 416 | } 417 | 418 | #[inline] 419 | fn encoding_length(&self) -> Result { 420 | let mut sum = 0; 421 | for element in self[..].iter() { 422 | sum += element.encoding_length()?; 423 | } 424 | Ok(sum) 425 | } 426 | } 427 | 428 | impl Decode for [T; N] { 429 | #[allow(unused_variables, unused_mut)] 430 | #[inline] 431 | fn decode(mut input: R) -> Result { 432 | let mut v: Vec = Vec::with_capacity(N); 433 | for i in 0..N { 434 | v.push(T::decode(&mut input)?); 435 | } 436 | Ok(v.try_into() 437 | .unwrap_or_else(|v: Vec| panic!("Input Vec not of length {}", N))) 438 | } 439 | 440 | #[inline] 441 | fn decode_into(&mut self, mut input: R) -> Result<()> { 442 | for item in self.iter_mut().take(N) { 443 | T::decode_into(item, &mut input)?; 444 | } 445 | Ok(()) 446 | } 447 | } 448 | 449 | impl Terminated for [T; N] {} 450 | 451 | impl Encode for Vec { 452 | #[doc = "Encodes the elements of the vector one after another, in order."] 453 | #[inline] 454 | fn encode_into(&self, dest: &mut W) -> Result<()> { 455 | for element in self.iter() { 456 | element.encode_into(dest)?; 457 | } 458 | Ok(()) 459 | } 460 | 461 | #[doc = "Returns the sum of the encoding lengths of all elements."] 462 | #[inline] 463 | fn encoding_length(&self) -> Result { 464 | let mut sum = 0; 465 | for element in self.iter() { 466 | sum += element.encoding_length()?; 467 | } 468 | Ok(sum) 469 | } 470 | } 471 | 472 | impl Decode for Vec { 473 | #[doc = "Decodes the elements of the vector one after another, in order."] 474 | #[inline] 475 | fn decode(input: R) -> Result { 476 | let mut vec = Vec::with_capacity(128); 477 | vec.decode_into(input)?; 478 | Ok(vec) 479 | } 480 | 481 | #[doc = "Encodes the elements of the vector one after another, in order."] 482 | #[doc = ""] 483 | #[doc = "Recursively calls `decode_into` for each element."] 484 | #[inline] 485 | fn decode_into(&mut self, mut input: R) -> Result<()> { 486 | let old_len = self.len(); 487 | 488 | let mut bytes = Vec::with_capacity(256); 489 | input.read_to_end(&mut bytes)?; 490 | 491 | let mut slice = bytes.as_slice(); 492 | let mut i = 0; 493 | while !slice.is_empty() { 494 | if i < old_len { 495 | self[i].decode_into(&mut slice)?; 496 | } else { 497 | let el = T::decode(&mut slice)?; 498 | self.push(el); 499 | } 500 | 501 | i += 1; 502 | } 503 | 504 | if i < old_len { 505 | self.truncate(i); 506 | } 507 | 508 | Ok(()) 509 | } 510 | } 511 | 512 | impl Encode for [T] { 513 | #[doc = "Encodes the elements of the slice one after another, in order."] 514 | #[inline] 515 | fn encode_into(&self, mut dest: &mut W) -> Result<()> { 516 | for element in self[..].iter() { 517 | element.encode_into(&mut dest)?; 518 | } 519 | Ok(()) 520 | } 521 | 522 | #[doc = "Returns the sum of the encoding lengths of all elements."] 523 | #[inline] 524 | fn encoding_length(&self) -> Result { 525 | let mut sum = 0; 526 | for element in self[..].iter() { 527 | sum += element.encoding_length()?; 528 | } 529 | Ok(sum) 530 | } 531 | } 532 | 533 | impl Encode for Box { 534 | #[doc = "Encodes the inner value."] 535 | #[inline] 536 | fn encode_into(&self, dest: &mut W) -> Result<()> { 537 | (**self).encode_into(dest) 538 | } 539 | 540 | #[doc = "Returns the encoding length of the inner value."] 541 | #[inline] 542 | fn encoding_length(&self) -> Result { 543 | (**self).encoding_length() 544 | } 545 | } 546 | 547 | impl Decode for Box { 548 | #[doc = "Decodes the inner value into a new Box."] 549 | #[inline] 550 | fn decode(input: R) -> Result { 551 | T::decode(input).map(|v| v.into()) 552 | } 553 | 554 | #[doc = "Decodes the inner value into the existing Box."] 555 | #[doc = ""] 556 | #[doc = "Recursively calls `decode_into` on the inner value."] 557 | #[inline] 558 | fn decode_into(&mut self, input: R) -> Result<()> { 559 | (**self).decode_into(input) 560 | } 561 | } 562 | 563 | impl Terminated for Box {} 564 | 565 | impl Encode for std::cell::RefCell { 566 | #[doc = "Encodes the inner value."] 567 | #[inline] 568 | fn encode_into(&self, dest: &mut W) -> Result<()> { 569 | self.borrow().encode_into(dest) 570 | } 571 | 572 | #[doc = "Returns the encoding length of the inner value."] 573 | #[inline] 574 | fn encoding_length(&self) -> Result { 575 | self.borrow().encoding_length() 576 | } 577 | } 578 | 579 | impl Decode for std::cell::RefCell { 580 | #[doc = "Decodes the inner value into a new RefCell."] 581 | #[inline] 582 | fn decode(input: R) -> Result { 583 | T::decode(input).map(std::cell::RefCell::new) 584 | } 585 | 586 | #[doc = "Decodes the inner value into the existing Box."] 587 | #[doc = ""] 588 | #[doc = "Recursively calls `decode_into` on the inner value."] 589 | #[inline] 590 | fn decode_into(&mut self, input: R) -> Result<()> { 591 | self.borrow_mut().decode_into(input) 592 | } 593 | } 594 | 595 | impl Terminated for std::cell::RefCell {} 596 | 597 | impl Encode for std::marker::PhantomData { 598 | /// Encoding PhantomData is a no-op. 599 | #[inline] 600 | fn encode_into(&self, _: &mut W) -> Result<()> { 601 | Ok(()) 602 | } 603 | 604 | /// Always returns Ok(0). 605 | #[inline] 606 | fn encoding_length(&self) -> Result { 607 | Ok(0) 608 | } 609 | } 610 | 611 | impl Decode for std::marker::PhantomData { 612 | /// Returns a PhantomData without reading any bytes. 613 | #[inline] 614 | fn decode(_: R) -> Result { 615 | Ok(Self {}) 616 | } 617 | } 618 | 619 | impl Terminated for std::marker::PhantomData {} 620 | 621 | #[cfg(test)] 622 | mod tests { 623 | #[allow(unused_imports)] 624 | use super::*; 625 | 626 | #[test] 627 | fn encode_decode_u8() { 628 | let value = 0x12u8; 629 | let bytes = value.encode().unwrap(); 630 | assert_eq!(bytes.as_slice(), &[0x12]); 631 | let decoded_value = u8::decode(bytes.as_slice()).unwrap(); 632 | assert_eq!(decoded_value, value); 633 | } 634 | 635 | #[test] 636 | fn encode_decode_u64() { 637 | let value = 0x1234567890u64; 638 | let bytes = value.encode().unwrap(); 639 | assert_eq!(bytes.as_slice(), &[0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x90]); 640 | let decoded_value = u64::decode(bytes.as_slice()).unwrap(); 641 | assert_eq!(decoded_value, value); 642 | } 643 | 644 | #[test] 645 | fn encode_decode_option() { 646 | let value = Some(0x1234567890u64); 647 | let bytes = value.encode().unwrap(); 648 | assert_eq!( 649 | bytes.as_slice(), 650 | &[1, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x90] 651 | ); 652 | let decoded_value: Option = Decode::decode(bytes.as_slice()).unwrap(); 653 | assert_eq!(decoded_value, value); 654 | 655 | let value: Option = None; 656 | let bytes = value.encode().unwrap(); 657 | assert_eq!(bytes.as_slice(), &[0]); 658 | let decoded_value: Option = Decode::decode(bytes.as_slice()).unwrap(); 659 | assert_eq!(decoded_value, None); 660 | } 661 | 662 | #[test] 663 | fn encode_decode_tuple() { 664 | let value: (u16, u16) = (1, 2); 665 | let bytes = value.encode().unwrap(); 666 | assert_eq!(bytes.as_slice(), &[0, 1, 0, 2]); 667 | let decoded_value: (u16, u16) = Decode::decode(bytes.as_slice()).unwrap(); 668 | assert_eq!(decoded_value, value); 669 | 670 | let value = (); 671 | let bytes = value.encode().unwrap(); 672 | assert_eq!(bytes.as_slice().len(), 0); 673 | let decoded_value: () = Decode::decode(bytes.as_slice()).unwrap(); 674 | assert_eq!(decoded_value, value); 675 | } 676 | 677 | #[test] 678 | fn encode_decode_array() { 679 | let value: [u16; 4] = [1, 2, 3, 4]; 680 | let bytes = value.encode().unwrap(); 681 | assert_eq!(bytes.as_slice(), &[0, 1, 0, 2, 0, 3, 0, 4]); 682 | let decoded_value: [u16; 4] = Decode::decode(bytes.as_slice()).unwrap(); 683 | assert_eq!(decoded_value, value); 684 | } 685 | 686 | #[test] 687 | #[should_panic(expected = "failed to fill whole buffer")] 688 | fn encode_decode_array_eof_length() { 689 | let bytes = [0, 1, 0, 2, 0, 3]; 690 | let _: [u16; 4] = Decode::decode(&bytes[..]).unwrap(); 691 | } 692 | 693 | #[test] 694 | #[should_panic(expected = "failed to fill whole buffer")] 695 | fn encode_decode_array_eof_element() { 696 | let bytes = [0, 1, 0, 2, 0, 3, 0]; 697 | let _: [u16; 4] = Decode::decode(&bytes[..]).unwrap(); 698 | } 699 | 700 | #[test] 701 | fn encode_decode_vec() { 702 | let value: Vec = vec![1, 2, 3, 4]; 703 | let bytes = value.encode().unwrap(); 704 | assert_eq!(bytes.as_slice(), &[0, 1, 0, 2, 0, 3, 0, 4]); 705 | let decoded_value: Vec = Decode::decode(bytes.as_slice()).unwrap(); 706 | assert_eq!(decoded_value, value); 707 | } 708 | 709 | #[test] 710 | #[should_panic(expected = "failed to fill whole buffer")] 711 | fn encode_decode_vec_eof_element() { 712 | let bytes = [0, 1, 0, 2, 0, 3, 0]; 713 | let _: Vec = Decode::decode(&bytes[..]).unwrap(); 714 | } 715 | 716 | #[test] 717 | fn test_encode_bool() { 718 | let value: bool = true; 719 | let bytes = value.encode().unwrap(); 720 | assert_eq!(bytes.as_slice(), &[1]); 721 | } 722 | 723 | #[test] 724 | fn test_encoding_length_bool() { 725 | let value: bool = true; 726 | let enc_length = value.encoding_length().unwrap(); 727 | assert!(enc_length == 1); 728 | } 729 | #[test] 730 | fn test_decode_bool_true() { 731 | let bytes = vec![1]; 732 | let decoded_value: bool = Decode::decode(bytes.as_slice()).unwrap(); 733 | assert_eq!(decoded_value, true); 734 | } 735 | 736 | #[test] 737 | fn test_decode_bool_false() { 738 | let bytes = vec![0]; 739 | let decoded_value: bool = Decode::decode(bytes.as_slice()).unwrap(); 740 | assert_eq!(decoded_value, false); 741 | } 742 | 743 | #[test] 744 | fn test_decode_bool_bail() { 745 | let bytes = vec![42]; 746 | let result: Result = Decode::decode(bytes.as_slice()); 747 | assert_eq!(result.unwrap_err().to_string(), "Unexpected byte: 42"); 748 | } 749 | 750 | #[test] 751 | fn test_encode_decode_phantom_data() { 752 | use std::marker::PhantomData; 753 | let pd: PhantomData = PhantomData; 754 | let bytes = pd.encode().unwrap(); 755 | assert_eq!(bytes.len(), 0); 756 | let decoded_value: PhantomData = Decode::decode(bytes.as_slice()).unwrap(); 757 | assert_eq!(decoded_value, PhantomData); 758 | } 759 | 760 | #[test] 761 | fn test_default_decode() { 762 | struct Foo { 763 | bar: u8, 764 | } 765 | 766 | impl Decode for Foo { 767 | fn decode(_input: R) -> Result { 768 | Ok(Foo { bar: 42 }) 769 | } 770 | } 771 | 772 | let bytes = vec![42, 12, 68]; 773 | let mut foo: Foo = Foo { bar: 41 }; 774 | foo.decode_into(bytes.as_slice()).unwrap(); 775 | assert_eq!(foo.bar, 42); 776 | } 777 | 778 | #[test] 779 | fn test_option_encode_into() { 780 | let option = Some(0x12u8); 781 | let mut vec: Vec = vec![]; 782 | option.encode_into(&mut vec).unwrap(); 783 | assert_eq!(vec, vec![1, 18]); 784 | } 785 | 786 | #[test] 787 | fn test_option_encoding_length() { 788 | let val = 0x12u8; 789 | let option = Some(val); 790 | let option_length = option.encoding_length().unwrap(); 791 | let val_length = val.encoding_length().unwrap(); 792 | assert!(option_length == val_length + 1); 793 | } 794 | #[test] 795 | fn test_option_none_encode_into() { 796 | let option: Option = None; 797 | let mut vec: Vec = vec![]; 798 | option.encode_into(&mut vec).unwrap(); 799 | assert_eq!(vec, vec![0]); 800 | } 801 | 802 | #[test] 803 | fn test_option_none_encoding_length() { 804 | let option: Option = None; 805 | let length = option.encoding_length().unwrap(); 806 | assert!(length == 1); 807 | } 808 | 809 | #[test] 810 | fn test_bail_option_decode_into() { 811 | let mut option: Option = Some(42); 812 | let bytes = vec![42]; 813 | let err = option.decode_into(bytes.as_slice()).unwrap_err(); 814 | assert_eq!(err.to_string(), "Unexpected byte: 42"); 815 | } 816 | 817 | #[test] 818 | fn test_some_option_decode_into() { 819 | let mut option: Option = Some(0); 820 | let bytes = vec![1, 0x12u8]; 821 | option.decode_into(bytes.as_slice()).unwrap(); 822 | assert_eq!(option.unwrap(), 18); 823 | } 824 | 825 | #[test] 826 | fn test_vec_decode_into() { 827 | let mut vec: Vec = vec![42, 42, 42]; 828 | let bytes = vec![12, 13]; 829 | vec.decode_into(bytes.as_slice()).unwrap(); 830 | assert_eq!(vec, vec![12, 13]); 831 | } 832 | 833 | #[test] 834 | fn test_vec_encoding_length() { 835 | let forty_two: u8 = 42; 836 | let vec: Vec = vec![42, 42, 42]; 837 | let vec_length = vec.encoding_length().unwrap(); 838 | let indv_num_length = forty_two.encoding_length().unwrap(); 839 | assert!(vec_length == indv_num_length * 3); 840 | } 841 | 842 | #[test] 843 | fn test_box_encoding_length() { 844 | let forty_two = Box::new(42); 845 | let length = forty_two.encoding_length().unwrap(); 846 | assert_eq!(length, 4); 847 | } 848 | 849 | #[test] 850 | fn test_box_encode_into() { 851 | let test = Box::new(42); 852 | let mut vec = vec![12]; 853 | test.encode_into(&mut vec).unwrap(); 854 | assert_eq!(*test, 42); 855 | } 856 | 857 | #[test] 858 | fn test_box_decode() { 859 | let bytes = vec![1]; 860 | let test = Box::new(bytes.as_slice()); 861 | let decoded_value: Box = Decode::decode(test).unwrap(); 862 | assert_eq!(*decoded_value, true); 863 | } 864 | 865 | #[test] 866 | fn test_box_decode_into() { 867 | let mut test = Box::new(false); 868 | let bytes = vec![1]; 869 | test.decode_into(bytes.as_slice()).unwrap(); 870 | assert_eq!(*test, true); 871 | } 872 | 873 | #[test] 874 | fn test_slice_encode_into() { 875 | let vec = vec![1, 2, 1]; 876 | let slice = &vec[0..3]; 877 | let mut vec: Vec = vec![]; 878 | slice.encode_into(&mut vec).unwrap(); 879 | assert_eq!(vec, vec![0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1]); 880 | } 881 | 882 | #[test] 883 | fn test_slice_encoding_length() { 884 | let vec = vec![1, 2, 1]; 885 | let slice = &vec[0..3]; 886 | let size = slice.encoding_length().unwrap(); 887 | assert_eq!(size, 12); 888 | } 889 | 890 | #[test] 891 | fn test_unit_encoding_length() { 892 | let unit = (); 893 | let length = unit.encoding_length().unwrap(); 894 | assert!(length == 0); 895 | } 896 | 897 | #[test] 898 | fn test_phantom_data_encoding_length() { 899 | use std::marker::PhantomData; 900 | let pd: PhantomData = PhantomData; 901 | let length = pd.encoding_length().unwrap(); 902 | assert_eq!(length, 0); 903 | } 904 | } 905 | -------------------------------------------------------------------------------- /tests/derive.rs: -------------------------------------------------------------------------------- 1 | use ed::{Decode, Encode}; 2 | 3 | #[derive(Encode, Decode)] 4 | struct Foo { 5 | x: u32, 6 | y: (u32, u32), 7 | } 8 | 9 | #[derive(Encode, Decode)] 10 | struct Foo2(u32, (u32, u32)); 11 | 12 | #[derive(Encode, Decode)] 13 | struct Foo3; 14 | 15 | #[derive(Encode, Decode)] 16 | struct Foo4(T); 17 | 18 | #[derive(Encode, Decode)] 19 | enum Bar { 20 | A { x: u32, y: (u32, u32) }, 21 | B(u32, (u32, u32)), 22 | C, 23 | } 24 | 25 | trait Subtype { 26 | type Subtype; 27 | } 28 | 29 | #[derive(Encode, Decode)] 30 | enum Bar2 { 31 | A { x: u32, y: (u32, u32) }, 32 | B(u32, (u32, u32)), 33 | C, 34 | D(T::Subtype, U), 35 | } 36 | --------------------------------------------------------------------------------