├── serde_mtproto_derive ├── LICENSE-MIT ├── LICENSE-APACHE ├── src │ ├── ext.rs │ ├── lib.rs │ ├── ast.rs │ ├── macros.rs │ ├── sized.rs │ └── identifiable.rs └── Cargo.toml ├── clippy.toml ├── bench-suite ├── Cargo.toml └── bench-nightly-test │ ├── Cargo.toml │ └── benches │ ├── strings.rs │ ├── primitives.rs │ └── data_types.rs ├── tests ├── version_numbers.rs ├── with_quickcheck.rs ├── fuzz_regressions.rs ├── serde_interop.rs └── regression_tests.rs ├── .editorconfig ├── .gitignore ├── LICENSE-MIT ├── Cargo.toml ├── README.md ├── src ├── lib.rs ├── helpers.rs ├── utils.rs ├── identifiable.rs ├── error.rs ├── sized.rs ├── wrappers.rs ├── ser.rs └── de.rs ├── .travis.yml ├── CHANGELOG.md └── LICENSE-APACHE /serde_mtproto_derive/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /serde_mtproto_derive/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /clippy.toml: -------------------------------------------------------------------------------- 1 | doc-valid-idents = ["MTProto", "MtProto"] 2 | -------------------------------------------------------------------------------- /bench-suite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "bench-nightly-test", 4 | ] 5 | -------------------------------------------------------------------------------- /tests/version_numbers.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn test_readme_deps() { 3 | version_sync::assert_markdown_deps_updated!("README.md"); 4 | } 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [*.rs] 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | *.rs.bk 11 | 12 | # Vim swap files 13 | [._]*.sw? 14 | [._]sw? 15 | 16 | # Temporary files 17 | *~ 18 | -------------------------------------------------------------------------------- /bench-suite/bench-nightly-test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bench-nightly-test" 3 | version = "0.0.0" 4 | description = "Benchmark suite using nightly `test::Bencher`" 5 | authors = ["Nguyen Duc My "] 6 | license = "MIT OR Apache-2.0" 7 | publish = false 8 | 9 | [dev-dependencies] 10 | lipsum = "0.6" 11 | rand = "0.6" 12 | serde = "1.0" 13 | serde_derive = "1.0" 14 | serde_mtproto = { path = "../.." } 15 | serde_mtproto_derive = { path = "../../serde_mtproto_derive" } 16 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/ext.rs: -------------------------------------------------------------------------------- 1 | pub(crate) trait IteratorResultExt: Iterator> { 2 | fn collect_results(self) -> Result, Vec>; 3 | } 4 | 5 | impl IteratorResultExt for I 6 | where 7 | I: Iterator>, 8 | { 9 | fn collect_results(self) -> Result, Vec> { 10 | let mut items = Vec::with_capacity(self.size_hint().0); 11 | let mut errors = Vec::new(); 12 | 13 | for res in self { 14 | match res { 15 | Ok(item) => items.push(item), 16 | Err(error) => errors.push(error), 17 | } 18 | } 19 | 20 | match errors.len() { 21 | 0 => Ok(items), 22 | _ => Err(errors), 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /serde_mtproto_derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde_mtproto_derive" 3 | version = "0.3.1" 4 | description = "Procedural macro helper for serde_mtproto" 5 | authors = ["Nguyen Duc My "] 6 | license = "MIT OR Apache-2.0" 7 | homepage = "https://github.com/hcpl/serde_mtproto" 8 | documentation = "https://docs.rs/serde_mtproto_derive" 9 | repository = "https://github.com/hcpl/serde_mtproto" 10 | keywords = ["serde", "serialization", "telegram"] 11 | edition = "2018" 12 | 13 | [badges] 14 | travis-ci = { repository = "hcpl/serde_mtproto" } 15 | 16 | [lib] 17 | proc-macro = true 18 | 19 | [dependencies] 20 | proc-macro2 = "0.4.19" 21 | quote = "0.6.3" 22 | syn = "0.15.22" 23 | 24 | [dev-dependencies] 25 | serde_mtproto = { path = "..", version = "=0.3.1" } # Update in lockstep 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 hcpl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde_mtproto" 3 | version = "0.3.1" 4 | description = "MTProto [de]serialization for Rust" 5 | authors = ["Nguyen Duc My "] 6 | license = "MIT OR Apache-2.0" 7 | readme = "README.md" 8 | homepage = "https://github.com/hcpl/serde_mtproto" 9 | documentation = "https://docs.rs/serde_mtproto" 10 | repository = "https://github.com/hcpl/serde_mtproto" 11 | keywords = ["serde", "serialization", "telegram"] 12 | edition = "2018" 13 | include = ["Cargo.toml", "LICENSE-APACHE", "LICENSE-MIT", "README.md", "src/**/*"] 14 | 15 | [badges] 16 | travis-ci = { repository = "hcpl/serde_mtproto" } 17 | 18 | [workspace] 19 | members = ["serde_mtproto_derive"] 20 | 21 | [build-dependencies] 22 | version_check = "0.1.5" 23 | 24 | [dependencies] 25 | byteorder = "1.0" 26 | error-chain = "0.12.1" 27 | log = "0.4" 28 | num-traits = "0.2" 29 | quickcheck = { version = "0.8", optional = true } 30 | serde = "1.0" 31 | serde_bytes = "0.11" 32 | serde_derive = "1.0" 33 | 34 | [dev-dependencies] 35 | derivative = "1.0.2" 36 | lazy_static = "1.2" 37 | maplit = "1.0" 38 | pretty_assertions = "0.6" 39 | #quickcheck_derive = "0.2" 40 | quickcheck_derive = { git = "https://github.com/hcpl/quickcheck_derive", branch = "minimum-supported-rustc" } 41 | rand = "0.6" 42 | serde_json = "1.0" 43 | serde_mtproto_derive = { path = "serde_mtproto_derive", version = "=0.3.1" } # Update in lockstep 44 | serde_yaml = "0.8" 45 | toml = "0.5" 46 | version-sync = "0.8" 47 | 48 | [features] 49 | default = [] 50 | nightly = [] 51 | # WARNING: This Cargo feature is not intended for public usage! 52 | # Used to test `serde_mtproto` against new unstable features in Rust language 53 | # and Rust standard library. 54 | test-nightly-regressions = [] 55 | 56 | 57 | [[test]] 58 | name = "fuzz_regressions" 59 | 60 | [[test]] 61 | name = "regression_tests" 62 | 63 | [[test]] 64 | name = "serde_interop" 65 | 66 | [[test]] 67 | name = "version_numbers" 68 | 69 | [[test]] 70 | name = "with_quickcheck" 71 | required-features = ["quickcheck"] 72 | 73 | 74 | [package.metadata.docs.rs] 75 | features = ["quickcheck"] 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serde MTProto 2 | 3 | [![Latest Version]][crates.io] 4 | [![Latest Docs]][docs.rs] 5 | ![Supported Rust Versions] 6 | ![License] 7 | [![Travis Build Status]][travis] 8 | [![Dependency Status]][deps] 9 | 10 | [Latest Version]: https://img.shields.io/crates/v/serde\_mtproto.svg 11 | [crates.io]: https://crates.io/crates/serde\_mtproto 12 | [Latest Docs]: https://docs.rs/serde_mtproto/badge.svg 13 | [docs.rs]: https://docs.rs/serde\_mtproto 14 | [Supported Rust Versions]: https://img.shields.io/badge/rustc-1.30+-red.svg 15 | [License]: https://img.shields.io/crates/l/serde\_mtproto.svg 16 | [Travis Build Status]: https://api.travis-ci.org/hcpl/serde\_mtproto.svg?branch=master 17 | [travis]: https://travis-ci.org/hcpl/serde\_mtproto 18 | [Dependency Status]: https://deps.rs/repo/github/hcpl/serde\_mtproto/status.svg 19 | [deps]: https://deps.rs/repo/github/hcpl/serde\_mtproto 20 | 21 | [MTProto](https://core.telegram.org/mtproto) [de]serialization for Rust which 22 | utilizes [Serde](https://serde.rs) framework. 23 | 24 | ```toml,no_sync 25 | [dependencies] 26 | serde_mtproto = { git = "https://github.com/hcpl/serde_mtproto" } 27 | ``` 28 | 29 | You may be looking for: 30 | 31 | - [Serde MTProto API documentation (latest published)](https://docs.rs/serde_mtproto/) 32 | - [Serde MTProto API documentation (master)](https://hcpl.github.io/serde_mtproto/master/) 33 | - [Serde API documentation](https://docs.rs/serde/) 34 | - [Detailed documentation about Serde](https://serde.rs/) 35 | - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) 36 | 37 | Supports Rust 1.30 and newer. 38 | Older versions may work, but are not guaranteed to. 39 | 40 | ### Optional Cargo features 41 | 42 | - **`quickcheck`** — `quickcheck::Arbitrary` implmentations for several types 43 | defined in `serde_mtproto`. 44 | For now, those only include wrapper types `Boxed`, `WithSize`. 45 | 46 | ## Changelog 47 | 48 | Maintained in [CHANGELOG.md](CHANGELOG.md). 49 | 50 | 51 | ## License 52 | 53 | Serde MTProto is licensed under either of 54 | 55 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 56 | http://www.apache.org/licenses/LICENSE-2.0) 57 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 58 | http://opensource.org/licenses/MIT) 59 | 60 | at your option. 61 | 62 | ### Contribution 63 | 64 | Unless you explicitly state otherwise, any contribution intentionally submitted 65 | for inclusion in Serde MTProto by you, as defined in the Apache-2.0 license, 66 | shall be dual licensed as above, without any additional terms or conditions. 67 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides Serde MTProto's two derive macros. 2 | //! 3 | //! ``` 4 | //! # #[macro_use] extern crate serde_mtproto_derive; 5 | //! #[derive(MtProtoIdentifiable, MtProtoSized)] 6 | //! # #[mtproto_identifiable(id = "0x00000000")] 7 | //! # struct Stub; 8 | //! # fn main() {} 9 | //! ``` 10 | //! 11 | //! # Examples 12 | //! 13 | //! ``` 14 | //! extern crate serde_mtproto; 15 | //! #[macro_use] 16 | //! extern crate serde_mtproto_derive; 17 | //! 18 | //! #[derive(MtProtoIdentifiable, MtProtoSized)] 19 | //! #[mtproto_identifiable(id = "0xbeefdead")] 20 | //! struct Message { 21 | //! message_id: u32, 22 | //! user_id: u32, 23 | //! text: String, 24 | //! attachment: Attachment, 25 | //! } 26 | //! 27 | //! #[derive(MtProtoIdentifiable, MtProtoSized)] 28 | //! enum Attachment { 29 | //! #[mtproto_identifiable(id = "0xdef19e00")] 30 | //! Nothing, 31 | //! #[mtproto_identifiable(id = "0xbadf00d0")] 32 | //! Link { 33 | //! url: String, 34 | //! }, 35 | //! #[mtproto_identifiable(id = "0xdeafbeef")] 36 | //! Repost { 37 | //! message_id: u32, 38 | //! }, 39 | //! } 40 | //! 41 | //! # fn main() {} 42 | //! ``` 43 | 44 | // For `quote!` and `control_flow_chain!` macros 45 | #![recursion_limit = "79"] 46 | 47 | // This lint is not compatible with defensive programming, let's disable it 48 | #![cfg_attr(feature = "cargo-clippy", allow(clippy::unneeded_field_pattern))] 49 | 50 | extern crate proc_macro; 51 | 52 | 53 | #[macro_use] 54 | mod macros; 55 | 56 | mod ast; 57 | mod ext; 58 | mod identifiable; 59 | mod sized; 60 | 61 | 62 | use proc_macro::TokenStream; 63 | 64 | 65 | #[proc_macro_derive(MtProtoIdentifiable, attributes(mtproto_identifiable))] 66 | pub fn mt_proto_identifiable(input: TokenStream) -> TokenStream { 67 | let ast = syn::parse_macro_input!(input as syn::DeriveInput); 68 | let tokens = match ast::Container::from_derive_input(ast, "mtproto::Identifiable") { 69 | Ok(container) => crate::identifiable::impl_derive(container), 70 | Err(e) => e.to_compile_error(), 71 | }; 72 | 73 | tokens.into() 74 | } 75 | 76 | #[proc_macro_derive(MtProtoSized, attributes(mtproto_sized))] 77 | pub fn mt_proto_sized(input: TokenStream) -> TokenStream { 78 | let ast = syn::parse_macro_input!(input as syn::DeriveInput); 79 | let tokens = match ast::Container::from_derive_input(ast, "mtproto::MtProtoSized") { 80 | Ok(container) => crate::sized::impl_derive(container), 81 | Err(e) => e.to_compile_error(), 82 | }; 83 | 84 | tokens.into() 85 | } 86 | -------------------------------------------------------------------------------- /bench-suite/bench-nightly-test/benches/strings.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | 4 | extern crate lipsum; 5 | extern crate rand; 6 | extern crate serde_mtproto; 7 | extern crate test; 8 | 9 | 10 | use rand::Rng; 11 | use serde_mtproto::{MtProtoSized, to_bytes, to_writer, from_bytes}; 12 | use test::Bencher; 13 | 14 | 15 | macro_rules! bench_string { 16 | ($( ($ser:ident, $de:ident) => $init_value:expr, )*) => { 17 | $( 18 | #[bench] 19 | fn $ser(b: &mut Bencher) { 20 | let string = $init_value; 21 | let mut v = vec![0; string.size_hint().unwrap()]; 22 | 23 | b.iter(|| { 24 | to_writer(v.as_mut_slice(), &string).unwrap(); 25 | }); 26 | } 27 | 28 | #[bench] 29 | fn $de(b: &mut Bencher) { 30 | let string_serialized = to_bytes(&$init_value).unwrap(); 31 | 32 | b.iter(|| { 33 | from_bytes::(&string_serialized, &[]).unwrap(); 34 | }); 35 | } 36 | )* 37 | }; 38 | } 39 | 40 | 41 | // STATIC STRINGS 42 | 43 | bench_string! { 44 | (string_empty_serialize, string_empty_deserialize) => "", 45 | (string_short_serialize, string_short_deserialize) => "foobar", 46 | (string_medium_serialize, string_medium_deserialize) => lipsum::LOREM_IPSUM, 47 | (string_long_serialize, string_long_deserialize) => lipsum::LIBER_PRIMUS, 48 | } 49 | 50 | 51 | // RANDOM STRINGS 52 | 53 | fn random_string(rng: &mut R, words_count: (usize, usize)) -> String { 54 | let lipsum_words_count = rng.gen_range(words_count.0, words_count.1); 55 | lipsum::lipsum(lipsum_words_count) 56 | } 57 | 58 | const RANGE_SHORT: (usize, usize) = (0, 32); 59 | const RANGE_MEDIUM: (usize, usize) = (128, 512); 60 | const RANGE_LONG: (usize, usize) = (32_768, 65_536); 61 | const RANGE_VERY_LONG: (usize, usize) = (1_048_576, 2_097_152); 62 | 63 | macro_rules! bench_random_string { 64 | ($( ($ser:ident, $de:ident) => $range:expr, )*) => { 65 | bench_string! { 66 | $( ($ser, $de) => random_string(&mut rand::thread_rng(), $range), )* 67 | } 68 | }; 69 | } 70 | 71 | bench_random_string! { 72 | (random_string_short_serialize, random_string_short_deserialize) => RANGE_SHORT, 73 | (random_string_medium_serialize, random_string_medium_deserialize) => RANGE_MEDIUM, 74 | (random_string_long_serialize, random_string_long_deserialize) => RANGE_LONG, 75 | (random_string_very_long_serialize, random_string_very_long_deserialize) => RANGE_VERY_LONG, 76 | } 77 | -------------------------------------------------------------------------------- /tests/with_quickcheck.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BTreeMap; 2 | 3 | use quickcheck::{TestResult, quickcheck}; 4 | use quickcheck_derive::Arbitrary; 5 | use rand::Rng; 6 | use serde_derive::{Serialize, Deserialize}; 7 | //use serde_mtproto::ByteBuf; 8 | use serde_mtproto::{Boxed, Identifiable, WithSize}; 9 | use serde_mtproto_derive::{MtProtoIdentifiable, MtProtoSized}; 10 | 11 | 12 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Arbitrary, MtProtoIdentifiable, MtProtoSized)] 13 | #[mtproto_identifiable(id = "0x02020202")] 14 | struct PhantomStruct; 15 | 16 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Arbitrary, MtProtoIdentifiable, MtProtoSized)] 17 | #[mtproto_identifiable(id = "0xa821f7fe")] 18 | struct SimpleStruct { 19 | field1: bool, 20 | field2: PhantomStruct, 21 | field3: String, 22 | field4: Boxed, 23 | field5: SimpleStruct2, 24 | field6: i16, 25 | } 26 | 27 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Arbitrary, MtProtoIdentifiable, MtProtoSized)] 28 | #[mtproto_identifiable(id = "0x341b1c93")] 29 | struct SimpleStruct2((i8,), PhantomStruct, WithSize<(i64, u16)>); 30 | 31 | #[cfg_attr(feature = "cargo-clippy", allow(enum_variant_names))] 32 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Arbitrary, MtProtoIdentifiable, MtProtoSized)] 33 | enum SimpleEnum { 34 | #[mtproto_identifiable(id = "0x2d893c40")] 35 | Variant1, 36 | #[mtproto_identifiable(id = "0x037cb665")] 37 | Variant2, 38 | #[mtproto_identifiable(id = "0xb5a92a28")] 39 | Variant3 { 40 | variant3_field1: Vec, // replace by ByteBuf 41 | variant3_field2: Boxed>, // replace by [u32; 4] 42 | }, 43 | #[mtproto_identifiable(id = "0x8d72c9e1")] 44 | Variant4(((u64, i32), f32, BTreeMap, f64)), // replace by 45 | } 46 | 47 | 48 | quickcheck! { 49 | fn ser_de_reversible(data: SimpleStruct) -> bool { 50 | let enum_variant_id = data.field4.inner().enum_variant_id().unwrap(); 51 | 52 | let ser = serde_mtproto::to_bytes(&data).unwrap(); 53 | let de = serde_mtproto::from_bytes::(&ser, &[enum_variant_id]).unwrap(); 54 | 55 | de == data 56 | } 57 | 58 | fn de_ser_reversible(byte_buf: Vec) -> TestResult { 59 | if let Ok(de) = serde_mtproto::from_bytes::(&byte_buf, &[]) { 60 | let ser = serde_mtproto::to_bytes(&de).unwrap(); 61 | 62 | TestResult::from_bool(ser == byte_buf) 63 | } else { 64 | TestResult::discard() 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/fuzz_regressions.rs: -------------------------------------------------------------------------------- 1 | //! Testing inputs obtained from fuzzers. 2 | 3 | use serde_derive::{Serialize, Deserialize}; 4 | use serde_mtproto_derive::{MtProtoIdentifiable, MtProtoSized}; 5 | 6 | // Tests under `success` should successfully make a roundtrip for a prefix of 7 | // `DATA` while those under `fail` should fail to parse and return `Err`. Tests 8 | // are arranged this way to detect undesirable panics. 9 | macro_rules! test_roundtrips { 10 | ( 11 | success { 12 | $($roundtrip_success:ident => $data_success:tt as $ty_success:ty,)+ 13 | } 14 | 15 | fail { 16 | $($roundtrip_fail:ident => $data_fail:tt as $ty_fail:ty,)+ 17 | } 18 | ) => { 19 | $( 20 | #[test] 21 | fn $roundtrip_success() { 22 | const DATA: &[u8] = $data_success; 23 | 24 | let (value, remaining) = serde_mtproto::from_bytes_reuse::<$ty_success>(DATA, &[]).unwrap(); 25 | let bytes = serde_mtproto::to_bytes(&value).unwrap(); 26 | 27 | assert_eq!(bytes.len() + remaining.len(), DATA.len()); 28 | assert_eq!(bytes, &DATA[0..bytes.len()]); 29 | } 30 | )+ 31 | 32 | $( 33 | #[test] 34 | fn $roundtrip_fail() { 35 | const DATA: &[u8] = $data_fail; 36 | 37 | assert!(serde_mtproto::from_bytes::<$ty_fail>(DATA, &[]).is_err()); 38 | } 39 | )+ 40 | }; 41 | } 42 | 43 | 44 | #[derive(Debug, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 45 | #[mtproto_identifiable(id = "0xdeadbeef")] 46 | struct Foo { 47 | a: String, 48 | b: Vec, 49 | c: serde_mtproto::ByteBuf, 50 | } 51 | 52 | test_roundtrips! { 53 | success { 54 | roundtrip_success1 => b"\x00\x00\x00\x00\x00\x00\x00\x08" as String, 55 | } 56 | 57 | fail { 58 | roundtrip_fail1 => b"\x00\n\xff\xf8\xff\xfb\xff\xff\xff\xff\x07\x00\x00\x00\xfe\xff\xff\xff\xff\xff\xff" as String, 59 | roundtrip_fail2 => b"\xfe\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" as String, 60 | roundtrip_fail3 => b"\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n" as Foo, 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/ast.rs: -------------------------------------------------------------------------------- 1 | pub(crate) struct Container { 2 | pub(crate) attrs: Vec, 3 | pub(crate) vis: syn::Visibility, 4 | pub(crate) ident: proc_macro2::Ident, 5 | pub(crate) generics: syn::Generics, 6 | pub(crate) data: Data, 7 | } 8 | 9 | pub(crate) enum Data { 10 | Struct(syn::DataStruct), 11 | Enum(syn::DataEnum), 12 | } 13 | 14 | impl Container { 15 | pub(crate) fn from_derive_input(input: syn::DeriveInput, trait_name: &str) -> syn::Result { 16 | let data = match input.data { 17 | syn::Data::Struct(data_struct) => Data::Struct(data_struct), 18 | syn::Data::Enum(data_enum) => Data::Enum(data_enum), 19 | syn::Data::Union(_) => { 20 | let msg = format!("Cannot derive `{}` for unions", trait_name); 21 | return Err(syn::Error::new_spanned(input, msg)); 22 | }, 23 | }; 24 | 25 | let syn::DeriveInput { attrs, vis, ident, generics, data: _ } = input; 26 | 27 | Ok(Self { attrs, vis, ident, generics, data }) 28 | } 29 | } 30 | 31 | impl quote::ToTokens for Container { 32 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { 33 | for attr in self.attrs.iter().filter(|a| matches!(a.style, syn::AttrStyle::Outer)) { 34 | attr.to_tokens(tokens); 35 | } 36 | self.vis.to_tokens(tokens); 37 | match self.data { 38 | Data::Struct(ref d) => d.struct_token.to_tokens(tokens), 39 | Data::Enum(ref d) => d.enum_token.to_tokens(tokens), 40 | } 41 | self.ident.to_tokens(tokens); 42 | self.generics.to_tokens(tokens); 43 | match self.data { 44 | Data::Struct(ref data) => match data.fields { 45 | syn::Fields::Named(ref fields) => { 46 | self.generics.where_clause.to_tokens(tokens); 47 | fields.to_tokens(tokens); 48 | }, 49 | syn::Fields::Unnamed(ref fields) => { 50 | fields.to_tokens(tokens); 51 | self.generics.where_clause.to_tokens(tokens); 52 | TokensOrDefault(&data.semi_token).to_tokens(tokens); 53 | 54 | }, 55 | syn::Fields::Unit => { 56 | self.generics.where_clause.to_tokens(tokens); 57 | TokensOrDefault(&data.semi_token).to_tokens(tokens); 58 | }, 59 | }, 60 | Data::Enum(ref data) => { 61 | self.generics.where_clause.to_tokens(tokens); 62 | data.brace_token.surround(tokens, |tokens| { 63 | data.variants.to_tokens(tokens); 64 | }); 65 | }, 66 | } 67 | } 68 | } 69 | 70 | 71 | pub(crate) struct TokensOrDefault<'a, T>(pub(crate) &'a Option); 72 | 73 | impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T> 74 | where 75 | T: quote::ToTokens + Default, 76 | { 77 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { 78 | match *self.0 { 79 | Some(ref t) => t.to_tokens(tokens), 80 | None => T::default().to_tokens(tokens), 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /bench-suite/bench-nightly-test/benches/primitives.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | 4 | extern crate rand; 5 | extern crate test; 6 | extern crate serde_mtproto; 7 | 8 | 9 | use serde_mtproto::{to_bytes, to_writer, from_bytes}; 10 | use test::Bencher; 11 | 12 | 13 | macro_rules! bench_primitive { 14 | ($($ty:ty, $ser:ident => [u8; $ser_bytes_count:expr], $de:ident;)*) => { 15 | $( 16 | #[bench] 17 | fn $ser(b: &mut Bencher) { 18 | let random_value: $ty = rand::random(); 19 | let mut v: [u8; $ser_bytes_count] = [0; $ser_bytes_count]; 20 | 21 | b.iter(|| { 22 | to_writer(v.as_mut(), &random_value).unwrap(); 23 | }); 24 | } 25 | 26 | #[bench] 27 | fn $de(b: &mut Bencher) { 28 | let random_value: $ty = rand::random(); 29 | let random_value_serialized = to_bytes(&random_value).unwrap(); 30 | 31 | b.iter(|| { 32 | from_bytes::<$ty>(&random_value_serialized, &[]).unwrap(); 33 | }); 34 | } 35 | )* 36 | }; 37 | } 38 | 39 | 40 | bench_primitive! { 41 | bool, bool_serialize => [u8; 4], bool_deserialize; 42 | 43 | i8, i8_serialize => [u8; 4], i8_deserialize; 44 | i16, i16_serialize => [u8; 4], i16_deserialize; 45 | i32, i32_serialize => [u8; 4], i32_deserialize; 46 | i64, i64_serialize => [u8; 8], i64_deserialize; 47 | i128, i128_serialize => [u8; 16], i128_deserialize; 48 | 49 | u8, u8_serialize => [u8; 4], u8_deserialize; 50 | u16, u16_serialize => [u8; 4], u16_deserialize; 51 | u32, u32_serialize => [u8; 4], u32_deserialize; 52 | u64, u64_serialize => [u8; 8], u64_deserialize; 53 | u128, u128_serialize => [u8; 16], u128_deserialize; 54 | 55 | f32, f32_serialize => [u8; 8], f32_deserialize; 56 | f64, f64_serialize => [u8; 8], f64_deserialize; 57 | 58 | (i128, i128), two_i128_tuple_serialize => [u8; 32], two_i128_tuple_deserialize; 59 | (u128, u128), two_u128_tuple_serialize => [u8; 32], two_u128_tuple_deserialize; 60 | 61 | // randomly shuffled 62 | (u8, i16, f32, f64, i64, u64, u32, i32, i8, u16), // <- truly random! 63 | all_numeric_primitives_tuple_serialize => [u8; 56], all_numeric_primitives_tuple_deserialize; 64 | 65 | [i8; 32], i8_array32_serialize => [u8; 128], i8_array32_deserialize; 66 | [i16; 32], i16_array32_serialize => [u8; 128], i16_array32_deserialize; 67 | [i32; 32], i32_array32_serialize => [u8; 128], i32_array32_deserialize; 68 | [i64; 32], i64_array32_serialize => [u8; 256], i64_array32_deserialize; 69 | [i128; 32], i128_array32_serialize => [u8; 512], i128_array32_deserialize; 70 | 71 | [u8; 32], u8_array32_serialize => [u8; 128], u8_array32_deserialize; 72 | [u16; 32], u16_array32_serialize => [u8; 128], u16_array32_deserialize; 73 | [u32; 32], u32_array32_serialize => [u8; 128], u32_array32_deserialize; 74 | [u64; 32], u64_array32_serialize => [u8; 256], u64_array32_deserialize; 75 | [u128; 32], u128_array32_serialize => [u8; 512], u128_array32_deserialize; 76 | 77 | [f32; 32], f32_array32_serialize => [u8; 256], f32_array32_deserialize; 78 | [f64; 32], f64_array32_serialize => [u8; 256], f64_array32_deserialize; 79 | } 80 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Serde MTProto 2 | //! 3 | //! MTProto is a mobile-first protocol for access to a server API. 4 | //! This crate provides means to serialize Rust types to its binary 5 | //! representation and to deserialize from said representation. 6 | 7 | 8 | // For `error_chain!` macro used in `error` module 9 | #![recursion_limit = "66"] 10 | 11 | #![cfg_attr(feature = "test-nightly-regressions", feature(nll))] 12 | 13 | 14 | // ========== RUSTC LINTS ========== // 15 | 16 | #![warn( 17 | // Warn some allow-level lints 18 | anonymous_parameters, 19 | missing_debug_implementations, 20 | missing_docs, 21 | rust_2018_idioms, 22 | trivial_casts, 23 | trivial_numeric_casts, 24 | unsafe_code, 25 | unstable_name_collisions, 26 | unused_import_braces, 27 | unused_results, 28 | )] 29 | 30 | 31 | // ========== CLIPPY LINTS ========== // 32 | 33 | #![cfg_attr(feature = "cargo-clippy", warn( 34 | // Restrict our code to ease reviewing and auditing in some cases 35 | clippy::clone_on_ref_ptr, 36 | clippy::decimal_literal_representation, 37 | clippy::float_arithmetic, 38 | clippy::indexing_slicing, 39 | clippy::mem_forget, 40 | clippy::print_stdout, 41 | clippy::result_unwrap_used, 42 | clippy::shadow_unrelated, 43 | clippy::wrong_pub_self_convention, 44 | 45 | // Additional pedantic warns about numeric casts 46 | clippy::cast_possible_truncation, 47 | clippy::cast_possible_wrap, 48 | clippy::cast_precision_loss, 49 | clippy::cast_sign_loss, 50 | clippy::invalid_upcast_comparisons, 51 | 52 | // Other pedantic lints we consider useful to use as warns in this crate 53 | clippy::doc_markdown, 54 | clippy::empty_enum, 55 | clippy::enum_glob_use, 56 | clippy::items_after_statements, 57 | clippy::match_same_arms, 58 | clippy::maybe_infinite_iter, 59 | clippy::mut_mut, 60 | clippy::needless_continue, 61 | clippy::pub_enum_variant_names, 62 | clippy::similar_names, 63 | clippy::string_add_assign, 64 | clippy::unseparated_literal_suffix, 65 | clippy::used_underscore_binding, 66 | ))] 67 | 68 | 69 | // Workaround for 70 | #[allow(unused_extern_crates)] 71 | extern crate serde; 72 | 73 | 74 | mod utils; 75 | 76 | pub mod de; 77 | pub mod error; 78 | pub mod helpers; 79 | pub mod identifiable; 80 | pub mod ser; 81 | pub mod sized; 82 | pub mod wrappers; 83 | 84 | 85 | // Extern crate re-export for convenience 86 | pub use serde_bytes::{ByteBuf, Bytes}; 87 | 88 | macro_rules! doc_inline { 89 | ($($i:item)*) => ($(#[doc(inline)] $i)*) 90 | } 91 | 92 | doc_inline! { 93 | // Serde essential re-exports 94 | pub use crate::ser::{ 95 | Serializer, 96 | to_bytes, 97 | to_writer, 98 | unsized_bytes_pad_to_bytes, 99 | unsized_bytes_pad_to_writer, 100 | }; 101 | pub use crate::de::{ 102 | Deserializer, 103 | from_bytes, 104 | from_bytes_reuse, 105 | from_bytes_seed, 106 | from_reader, 107 | from_reader_reuse, 108 | from_reader_seed, 109 | }; 110 | 111 | // Error types and typedefs 112 | pub use crate::error::{Error, ErrorKind, Result, ResultExt}; 113 | 114 | // Other items generally useful for MTProto [de]serialization 115 | pub use crate::helpers::{UnsizedByteBuf, UnsizedByteBufSeed}; 116 | pub use crate::identifiable::Identifiable; 117 | pub use crate::sized::{MtProtoSized, size_hint_from_byte_seq_len}; 118 | pub use crate::wrappers::{Boxed, WithId, WithSize}; 119 | } 120 | -------------------------------------------------------------------------------- /tests/serde_interop.rs: -------------------------------------------------------------------------------- 1 | use lazy_static::lazy_static; 2 | use serde_bytes::ByteBuf; 3 | use serde_derive::{Serialize, Deserialize}; 4 | use serde_mtproto_derive::{MtProtoIdentifiable, MtProtoSized}; 5 | 6 | 7 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 8 | #[mtproto_identifiable(id = "0x7e298afc")] 9 | struct Data { 10 | id: u64, 11 | raw_data: ByteBuf, 12 | metadata: Metadata, 13 | } 14 | 15 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 16 | #[mtproto_identifiable(id = "0xb3185db0")] 17 | struct Metadata { 18 | username: String, 19 | encrypted: bool, 20 | seen_times: u32, 21 | } 22 | 23 | 24 | lazy_static! { 25 | static ref DATA: Data = Data { 26 | id: 0x5922_0494_9ed2_18af, 27 | raw_data: ByteBuf::from(b"content".as_ref().to_owned()), 28 | metadata: Metadata { 29 | username: "new_user".to_owned(), 30 | encrypted: false, 31 | seen_times: 31, 32 | }, 33 | }; 34 | 35 | static ref DATA_MTPROTO: Vec = serde_mtproto::to_bytes(&*DATA).unwrap(); 36 | static ref DATA_JSON: Vec = serde_json::to_vec(&*DATA).unwrap(); 37 | static ref DATA_YAML: Vec = serde_yaml::to_vec(&*DATA).unwrap(); 38 | static ref DATA_TOML: Vec = toml::to_vec(&*DATA).unwrap(); 39 | } 40 | 41 | 42 | #[test] 43 | fn json_to_mtproto() { 44 | let data: Data = serde_json::from_slice(&*DATA_JSON).unwrap(); 45 | let data_mtproto = serde_mtproto::to_bytes(&data).unwrap(); 46 | 47 | assert_eq!(data_mtproto, *DATA_MTPROTO); 48 | } 49 | 50 | #[test] 51 | fn mtproto_to_json() { 52 | let data: Data = serde_mtproto::from_bytes(&*DATA_MTPROTO, &[]).unwrap(); 53 | let data_json = serde_json::to_vec(&data).unwrap(); 54 | 55 | assert_eq!(data_json, *DATA_JSON); 56 | } 57 | 58 | #[test] 59 | fn yaml_to_mtproto() { 60 | let data: Data = serde_yaml::from_slice(&*DATA_YAML).unwrap(); 61 | let data_mtproto = serde_mtproto::to_bytes(&data).unwrap(); 62 | 63 | assert_eq!(data_mtproto, *DATA_MTPROTO); 64 | } 65 | 66 | #[test] 67 | fn mtproto_to_yaml() { 68 | let data: Data = serde_mtproto::from_bytes(&*DATA_MTPROTO, &[]).unwrap(); 69 | let data_yaml = serde_yaml::to_vec(&data).unwrap(); 70 | 71 | assert_eq!(data_yaml, *DATA_YAML); 72 | } 73 | 74 | #[test] 75 | fn toml_to_mtproto() { 76 | let data: Data = toml::from_slice(&*DATA_TOML).unwrap(); 77 | let data_mtproto = serde_mtproto::to_bytes(&data).unwrap(); 78 | 79 | assert_eq!(data_mtproto, *DATA_MTPROTO); 80 | } 81 | 82 | #[test] 83 | fn mtproto_to_toml() { 84 | let data: Data = serde_mtproto::from_bytes(&*DATA_MTPROTO, &[]).unwrap(); 85 | let data_toml = toml::to_vec(&data).unwrap(); 86 | 87 | assert_eq!(data_toml, *DATA_TOML); 88 | } 89 | 90 | 91 | #[test] 92 | fn extern_serde_formats_interop() { 93 | // JSON & YAML 94 | { 95 | let data: Data = serde_yaml::from_slice(&*DATA_YAML).unwrap(); 96 | let data_json = serde_json::to_vec(&data).unwrap(); 97 | 98 | assert_eq!(data_json, *DATA_JSON); 99 | 100 | let data: Data = serde_json::from_slice(&*DATA_JSON).unwrap(); 101 | let data_yaml = serde_yaml::to_vec(&data).unwrap(); 102 | 103 | assert_eq!(data_yaml, *DATA_YAML); 104 | } 105 | 106 | // JSON & TOML 107 | { 108 | let data: Data = toml::from_slice(&*DATA_TOML).unwrap(); 109 | let data_json = serde_json::to_vec(&data).unwrap(); 110 | 111 | assert_eq!(data_json, *DATA_JSON); 112 | 113 | let data: Data = serde_json::from_slice(&*DATA_JSON).unwrap(); 114 | let data_toml = toml::to_vec(&data).unwrap(); 115 | 116 | assert_eq!(data_toml, *DATA_TOML); 117 | } 118 | 119 | // YAML & TOML 120 | { 121 | let data: Data = toml::from_slice(&*DATA_TOML).unwrap(); 122 | let data_yaml = serde_yaml::to_vec(&data).unwrap(); 123 | 124 | assert_eq!(data_yaml, *DATA_YAML); 125 | 126 | let data: Data = serde_yaml::from_slice(&*DATA_YAML).unwrap(); 127 | let data_toml = toml::to_vec(&data).unwrap(); 128 | 129 | assert_eq!(data_toml, *DATA_TOML); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /bench-suite/bench-nightly-test/benches/data_types.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | 4 | extern crate lipsum; 5 | extern crate rand; 6 | #[macro_use] 7 | extern crate serde_derive; 8 | extern crate serde_mtproto; 9 | #[macro_use] 10 | extern crate serde_mtproto_derive; 11 | extern crate test; 12 | 13 | 14 | use rand::Rng; 15 | use rand::distributions::{Distribution, Standard}; 16 | use serde_mtproto::{MtProtoSized, to_bytes, to_writer, from_bytes}; 17 | use test::Bencher; 18 | 19 | 20 | fn random_string(rng: &mut R, words_count: (usize, usize)) -> String { 21 | let lipsum_words_count: usize = rng.gen_range(words_count.0, words_count.1); 22 | 23 | lipsum::lipsum(lipsum_words_count) 24 | } 25 | 26 | 27 | #[derive(Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 28 | #[mtproto_identifiable(id = "0xd594ba98")] 29 | struct Struct { 30 | bar: bool, 31 | s: String, 32 | group: (i16, u64, i8), 33 | } 34 | 35 | impl Distribution for Standard { 36 | fn sample(&self, rng: &mut R) -> Struct { 37 | Struct { 38 | bar: rng.gen(), 39 | // Generate moderately long strings for reference 40 | s: random_string(rng, (2048, 4096)), 41 | group: rng.gen(), 42 | } 43 | } 44 | } 45 | 46 | #[bench] 47 | fn struct_serialize(b: &mut Bencher) { 48 | let struct_ = Struct { 49 | bar: false, 50 | s: "Hello, world!".to_owned(), 51 | group: (-500, 0xffff_ffff_ffff, -64), 52 | }; 53 | let mut v = vec![0; struct_.size_hint().unwrap()]; 54 | 55 | b.iter(|| { 56 | to_writer(v.as_mut_slice(), &struct_).unwrap(); 57 | }); 58 | } 59 | 60 | #[bench] 61 | fn struct_deserialize(b: &mut Bencher) { 62 | let struct_serialized = [ 63 | 55, 151, 121, 188, 64 | 13, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0, 0, 65 | 12, 254, 255, 255, 66 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 67 | 192, 255, 255, 255, 68 | ]; 69 | 70 | b.iter(|| { 71 | from_bytes::(&struct_serialized, &[]).unwrap(); 72 | }); 73 | } 74 | 75 | #[bench] 76 | fn random_struct_serialize(b: &mut Bencher) { 77 | let random_struct: Struct = rand::random(); 78 | let mut v = vec![0; random_struct.size_hint().unwrap()]; 79 | 80 | b.iter(|| { 81 | to_writer(v.as_mut_slice(), &random_struct).unwrap(); 82 | }); 83 | } 84 | 85 | #[bench] 86 | fn random_struct_deserialize(b: &mut Bencher) { 87 | let random_struct: Struct = rand::random(); 88 | let random_struct_serialized = to_bytes(&random_struct).unwrap(); 89 | 90 | b.iter(|| { 91 | from_bytes::(&random_struct_serialized, &[]).unwrap(); 92 | }); 93 | } 94 | 95 | 96 | #[derive(Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 97 | #[mtproto_identifiable(id = "0x200c5e59")] 98 | struct Nothing; 99 | 100 | impl Distribution for Standard { 101 | fn sample(&self, _rng: &mut R) -> Nothing { 102 | Nothing 103 | } 104 | } 105 | 106 | #[bench] 107 | fn nothing_serialize(b: &mut Bencher) { 108 | let nothing = Nothing; 109 | let mut v = vec![0; nothing.size_hint().unwrap()]; 110 | 111 | b.iter(|| { 112 | to_writer(v.as_mut_slice(), ¬hing).unwrap(); 113 | }); 114 | } 115 | 116 | #[bench] 117 | fn nothing_deserialize(b: &mut Bencher) { 118 | let nothing_serialized = []; 119 | 120 | b.iter(|| { 121 | from_bytes::(¬hing_serialized, &[]).unwrap(); 122 | }); 123 | } 124 | 125 | #[bench] 126 | fn random_nothing_serialize(b: &mut Bencher) { 127 | let random_nothing: Nothing = rand::random(); 128 | let mut v = vec![0; random_nothing.size_hint().unwrap()]; 129 | 130 | b.iter(|| { 131 | to_writer(v.as_mut_slice(), &random_nothing).unwrap(); 132 | }); 133 | } 134 | 135 | #[bench] 136 | fn random_nothing_deserialize(b: &mut Bencher) { 137 | let random_nothing: Nothing = rand::random(); 138 | let random_nothing_serialized = to_bytes(&random_nothing).unwrap(); 139 | 140 | b.iter(|| { 141 | from_bytes::(&random_nothing_serialized, &[]).unwrap(); 142 | }); 143 | } 144 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! ident { 2 | ($($format_args:tt)*) => { 3 | proc_macro2::Ident::new(&std::format!($($format_args)*), proc_macro2::Span::call_site()) 4 | }; 5 | } 6 | 7 | macro_rules! matches { 8 | ($expr:expr, $($pat:tt)+) => { 9 | match $expr { 10 | $($pat)+ => true, 11 | _ => false, 12 | } 13 | }; 14 | } 15 | 16 | macro_rules! quote_spanned_by { 17 | ($expr:expr=> ) => { proc_macro2::TokenStream::new() }; 18 | ($expr:expr=> $($tt:tt)+) => {{ 19 | use std::iter::FromIterator; 20 | 21 | let mut span_tokens = quote::ToTokens::into_token_stream($expr).into_iter(); 22 | let start_span = span_tokens.next().map_or_else(proc_macro2::Span::call_site, |t| t.span()); 23 | let end_span = span_tokens.last().map_or(start_span, |t| t.span()); 24 | 25 | let mut end_tokens = quote::quote_spanned!(end_span=> $($tt)*).into_iter(); 26 | let mut start_token = end_tokens.next().unwrap(); 27 | start_token.set_span(start_span); 28 | 29 | proc_macro2::TokenStream::from_iter(std::iter::once(start_token).chain(end_tokens)) 30 | }}; 31 | } 32 | 33 | // Adapted from `if_chain!` macro from `if_chain` 0.1.3 34 | macro_rules! control_flow_chain { 35 | ($($tt:tt)*) => { 36 | __control_flow_chain! { @init () $($tt)* } 37 | }; 38 | } 39 | 40 | macro_rules! __control_flow_chain { 41 | // Expand with both a successful case and a fallback 42 | (@init ($($tt:tt)*) then { $($then:tt)* } else { $($other:tt)* }) => { 43 | __control_flow_chain! { @expand { $($other)* } $($tt)* then { $($then)* } } 44 | }; 45 | // Expand with no fallback 46 | (@init ($($tt:tt)*) then { $($then:tt)* }) => { 47 | __control_flow_chain! { @expand {} $($tt)* then { $($then)* } } 48 | }; 49 | // Munch everything until either of the arms above can be matched. 50 | // Munched tokens are placed into `$($tt)*` 51 | (@init ($($tt:tt)*) $head:tt $($tail:tt)*) => { 52 | __control_flow_chain! { @init ($($tt)* $head) $($tail)* } 53 | }; 54 | 55 | // `let` with single pattern 56 | (@expand { $($other:tt)* } let $pat:pat = $expr:expr; $($tt:tt)+) => { 57 | { 58 | let $pat = $expr; 59 | __control_flow_chain! { @expand { $($other)* } $($tt)+ } 60 | } 61 | }; 62 | // `let` with multiple patterns 63 | (@expand { $($other:tt)* } let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+) => { 64 | match $expr { 65 | $pat1 | $($pat)|+ => __control_flow_chain! { @expand { $($other)* } $($tt)+ } 66 | } 67 | }; 68 | // `if let` with single pattern 69 | (@expand {} if let $pat:pat = $expr:expr; $($tt:tt)+) => { 70 | if let $pat = $expr { 71 | __control_flow_chain! { @expand {} $($tt)+ } 72 | } 73 | }; 74 | // `if let` with single pattern and a fallback 75 | (@expand { $($other:tt)+ } if let $pat:pat = $expr:expr; $($tt:tt)+) => { 76 | if let $pat = $expr { 77 | __control_flow_chain! { @expand { $($other)+ } $($tt)+ } 78 | } else { 79 | $($other)+ 80 | } 81 | }; 82 | // `if let` with multiple matterns and a fallback (if present) 83 | (@expand { $($other:tt)* } if let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+) => { 84 | match $expr { 85 | $pat1 | $($pat)|+ => { __control_flow_chain! { @expand { $($other)* } $($tt)+ } }, 86 | _ => { $($other)* } 87 | } 88 | }; 89 | // `if` with a successful case 90 | (@expand {} if $expr:expr; $($tt:tt)+) => { 91 | if $expr { 92 | __control_flow_chain! { @expand {} $($tt)+ } 93 | } 94 | }; 95 | // `if` with both a successful case and a fallback 96 | (@expand { $($other:tt)+ } if $expr:expr; $($tt:tt)+) => { 97 | if $expr { 98 | __control_flow_chain! { @expand { $($other)+ } $($tt)+ } 99 | } else { 100 | $($other)+ 101 | } 102 | }; 103 | // `for` loop 104 | // TODO: how do loops deal with fallbacks? 105 | (@expand { $($other:tt)* } for $elem:pat in $iter:expr; $($tt:tt)+) => { 106 | for $elem in $iter { 107 | __control_flow_chain! { @expand { $($other)* } $($tt)+ } 108 | } 109 | }; 110 | // Final macro call 111 | (@expand { $($other:tt)* } then { $($then:tt)* }) => { 112 | $($then)* 113 | }; 114 | } 115 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | cache: cargo 4 | 5 | env: 6 | global: 7 | - RUST_BACKTRACE=1 8 | 9 | matrix: 10 | include: 11 | - rust: 1.31.1 12 | env: DESCRIPTION="minimum supported Rust" 13 | script: 14 | - cargo test --verbose --all --lib 15 | - cargo test --verbose --all --tests 16 | 17 | - cargo test --verbose --all --lib --features "quickcheck" 18 | - cargo test --verbose --all --tests --features "quickcheck" 19 | 20 | - rust: stable 21 | env: DESCRIPTION="stable Rust, clippy" 22 | install: 23 | - rustup component add clippy-preview || echo "Could not install clippy" 24 | script: 25 | - cargo test --verbose --all --lib 26 | - cargo test --verbose --all --tests 27 | - which cargo-clippy && cargo clippy --verbose --all 28 | 29 | - cargo test --verbose --all --lib --features "quickcheck" 30 | - cargo test --verbose --all --tests --features "quickcheck" 31 | - which cargo-clippy && cargo clippy --verbose --all --features "quickcheck" 32 | 33 | - rust: beta 34 | env: DESCRIPTION="beta Rust, clippy" 35 | install: 36 | - rustup component add clippy-preview || echo "Could not install clippy" 37 | script: 38 | - cargo test --verbose --all --lib 39 | - cargo test --verbose --all --tests 40 | - which cargo-clippy && cargo clippy --verbose --all 41 | 42 | - cargo test --verbose --all --lib --features "quickcheck" 43 | - cargo test --verbose --all --tests --features "quickcheck" 44 | - which cargo-clippy && cargo clippy --verbose --all --features "quickcheck" 45 | 46 | - rust: nightly 47 | env: DESCRIPTION="nightly Rust, clippy" 48 | install: 49 | # `which cargo-clippy` always succeeds, resort to setting a boolean 50 | - if rustup component add clippy-preview; then HAS_CLIPPY=true; else HAS_CLIPPY=false; echo "Could not install clippy"; fi 51 | script: 52 | - cargo test --verbose --all --lib --features "nightly test-nightly-regressions" 53 | - cargo test --verbose --all --tests --features "nightly test-nightly-regressions" 54 | - if "${HAS_CLIPPY}"; then cargo clippy --verbose --all --features "nightly test-nightly-regressions"; fi 55 | 56 | - cargo test --verbose --all --lib --features "nightly quickcheck test-nightly-regressions" 57 | - cargo test --verbose --all --tests --features "nightly quickcheck test-nightly-regressions" 58 | - if "${HAS_CLIPPY}"; then cargo clippy --verbose --all --features "nightly quickcheck test-nightly-regressions"; fi 59 | 60 | - cargo test --verbose --manifest-path bench-suite/Cargo.toml --all --benches 61 | 62 | - cargo update -Z minimal-versions 63 | - cargo build --verbose --manifest-path serde_mtproto_derive/Cargo.toml --lib 64 | - if "${HAS_CLIPPY}"; then cargo clippy --verbose --manifest-path serde_mtproto_derive/Cargo.toml; fi 65 | 66 | # Host documentation on 67 | - rust: nightly 68 | env: DESCRIPTION="build and upload docs" 69 | install: 70 | - cargo install cargo-update || echo "cargo-update already installed" 71 | - cargo install cargo-travis || echo "cargo-travis already installed" 72 | - cargo install-update cargo-travis 73 | script: 74 | - cargo doc --manifest-path Cargo.toml --features "quickcheck" 75 | - cargo doc --manifest-path serde_mtproto_derive/Cargo.toml 76 | - git clone --depth=1 --branch gh-pages "https://github.com/${TRAVIS_REPO_SLUG}" target/gh-pages 77 | - | 78 | if [ -e "target/gh-pages/${TRAVIS_BRANCH}/index.html" ]; then 79 | rm -f target/doc/index.html 80 | else 81 | echo '' > target/doc/index.html 82 | echo '' >> target/doc/index.html 83 | echo 'Redirect' >> target/doc/index.html 84 | fi 85 | - rm -rf target/gh-pages 86 | after_success: 87 | - cargo doc-upload --message $'Automatic Travis documentation build\n\n'"${TRAVIS_COMMIT_MESSAGE}" 88 | 89 | after_success: 90 | - | 91 | # Run benchmarks against master and PR branch 92 | # Adapted from 93 | if [ "${TRAVIS_PULL_REQUEST}" = true ] && [ "${TRAVIS_RUST_VERSION}" = nightly ]; then 94 | cd "${TRAVIS_BUILD_DIR}"/.. && 95 | git clone "${REMOTE_URL}" "${TRAVIS_REPO_SLUG}-bench" && 96 | cd "${TRAVIS_REPO_SLUG}-bench" && 97 | # Bench master 98 | git checkout master && 99 | cargo bench > before && 100 | # Bench PR'ing branch 101 | git checkout "${TRAVIS_COMMIT}" && 102 | cargo bench > after && 103 | # Compare results 104 | cargo install --force cargo-benchcmp && 105 | cargo benchcmp --include-missing before after 106 | fi 107 | -------------------------------------------------------------------------------- /src/helpers.rs: -------------------------------------------------------------------------------- 1 | //! Helper types for assisting in some [de]serialization scenarios. 2 | 3 | use std::fmt; 4 | use std::mem; 5 | 6 | use byteorder::{ByteOrder, LittleEndian}; 7 | use serde::de::{self, Deserializer, DeserializeSeed, Error as DeError, Visitor}; 8 | use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; 9 | 10 | use crate::error::{self, DeErrorKind}; 11 | use crate::sized::MtProtoSized; 12 | use crate::utils::safe_uint_cast; 13 | 14 | 15 | const CHUNK_SIZE: usize = mem::size_of::() / mem::size_of::(); 16 | 17 | 18 | /// A byte buffer which doesn't write its length when serialized. 19 | #[derive(Clone, Debug, Eq, PartialEq)] 20 | pub struct UnsizedByteBuf { 21 | inner: Vec, 22 | } 23 | 24 | impl UnsizedByteBuf { 25 | /// Wrap a byte buffer. 26 | pub fn new(inner: Vec) -> error::Result { 27 | match inner.len() % 4 { 28 | 0 => Ok(UnsizedByteBuf { inner }), 29 | _ => unimplemented!(), // FIXME 30 | } 31 | } 32 | 33 | /// Create a new buffer and copy from `input` and pad so that the buffer 34 | /// length was divisible by 4. 35 | pub fn from_slice_pad(input: &[u8]) -> UnsizedByteBuf { 36 | let len = input.len(); 37 | let inner_len = len + (4 - len % 4) % 4; 38 | assert!(len <= inner_len); 39 | 40 | let mut inner = vec![0; inner_len]; 41 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::indexing_slicing))] 42 | inner[0..len].copy_from_slice(input); 43 | 44 | UnsizedByteBuf { inner } 45 | } 46 | 47 | /// Return an immutable reference to the underlying byte buffer. 48 | pub fn inner(&self) -> &Vec { 49 | &self.inner 50 | } 51 | 52 | /// Return a mutable reference to the underlying byte buffer. 53 | pub fn inner_mut(&mut self) -> &mut Vec { 54 | &mut self.inner 55 | } 56 | 57 | /// Consume the `UnsizedByteBuf` and return the underlying byte buffer. 58 | pub fn into_inner(self) -> Vec { 59 | self.inner 60 | } 61 | } 62 | 63 | impl Serialize for UnsizedByteBuf { 64 | fn serialize(&self, serializer: S) -> Result 65 | where S: Serializer 66 | { 67 | let chunks_count = self.inner.len() / CHUNK_SIZE; 68 | 69 | assert!(self.inner.len() % CHUNK_SIZE == 0); 70 | 71 | let mut serialize_tuple = serializer.serialize_tuple_struct("UnsizedByteBuf", chunks_count)?; 72 | 73 | for chunk_u32 in self.inner.chunks(CHUNK_SIZE).map(LittleEndian::read_u32) { 74 | serialize_tuple.serialize_field(&chunk_u32)?; 75 | } 76 | 77 | serialize_tuple.end() 78 | } 79 | } 80 | 81 | impl MtProtoSized for UnsizedByteBuf { 82 | fn size_hint(&self) -> error::Result { 83 | Ok(self.inner.len()) 84 | } 85 | } 86 | 87 | /// An unsized byte buffer seed with the length of the byte sequence to be deserialized. 88 | #[derive(Clone, Debug, Eq, PartialEq)] 89 | pub struct UnsizedByteBufSeed { 90 | inner_len: usize, 91 | } 92 | 93 | impl UnsizedByteBufSeed { 94 | /// Construct a new unsized byte buffer seed with the length of the byte sequence to be 95 | /// deserialized. 96 | pub fn new(inner_len: usize) -> error::Result { 97 | match inner_len % 4 { 98 | 0 => Ok(UnsizedByteBufSeed { inner_len }), 99 | _ => unimplemented!(), // FIXME 100 | } 101 | } 102 | } 103 | 104 | impl<'de> DeserializeSeed<'de> for UnsizedByteBufSeed { 105 | type Value = UnsizedByteBuf; 106 | 107 | fn deserialize(self, deserializer: D) -> Result 108 | where D: Deserializer<'de> 109 | { 110 | struct UnsizedByteBufVisitor { 111 | inner_len: usize, 112 | } 113 | 114 | impl<'de> Visitor<'de> for UnsizedByteBufVisitor { 115 | type Value = UnsizedByteBuf; 116 | 117 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 118 | f.write_str("a stream of bytes without prepended length and with a EOF") 119 | } 120 | 121 | fn visit_seq(self, mut seq: A) -> Result 122 | where A: de::SeqAccess<'de> 123 | { 124 | let mut inner = vec![0; self.inner_len]; 125 | 126 | assert!(self.inner_len % 4 == 0); 127 | let chunks_count = self.inner_len / CHUNK_SIZE; 128 | 129 | //TODO: add more info to error data 130 | let errconv = |kind: DeErrorKind| A::Error::custom(error::Error::from(kind)); 131 | 132 | for (i, chunk_mut) in inner.chunks_mut(CHUNK_SIZE).enumerate() { 133 | // FIXME: `usize` as `u32` 134 | let unexpected = safe_uint_cast::(i).map_err(A::Error::custom)?; 135 | let expected = safe_uint_cast::(chunks_count).map_err(A::Error::custom)?; 136 | 137 | let chunk_u32 = seq.next_element()? 138 | .ok_or_else(|| errconv(DeErrorKind::NotEnoughElements(unexpected, expected)))?; 139 | 140 | LittleEndian::write_u32(chunk_mut, chunk_u32); 141 | } 142 | 143 | assert!(seq.next_element::()?.is_none()); // FIXME 144 | 145 | Ok(UnsizedByteBuf { inner }) 146 | } 147 | } 148 | 149 | assert!(self.inner_len % 4 == 0); 150 | let chunks_count = self.inner_len / CHUNK_SIZE; 151 | 152 | deserializer.deserialize_tuple_struct( 153 | "UnsizedByteBuf", 154 | chunks_count, 155 | UnsizedByteBufVisitor { inner_len: self.inner_len }, 156 | ) 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use num_traits::cast::cast; 2 | use num_traits::float::Float; 3 | use num_traits::int::PrimInt; 4 | use num_traits::sign::{Signed, Unsigned}; 5 | 6 | use crate::error::{self, ErrorKind, ResultExt}; 7 | 8 | 9 | pub(crate) type IntMax = i128; 10 | pub(crate) type UIntMax = u128; 11 | 12 | 13 | pub(crate) fn safe_int_cast(n: T) -> error::Result 14 | where T: PrimInt + Signed, 15 | U: PrimInt + Signed, 16 | { 17 | cast(n).ok_or_else(|| { 18 | let upcasted = cast::(n).unwrap(); // Shouldn't panic 19 | ErrorKind::SignedIntegerCast(upcasted).into() 20 | }) 21 | } 22 | 23 | pub(crate) fn safe_uint_cast(n: T) -> error::Result 24 | where T: PrimInt + Unsigned, 25 | U: PrimInt + Unsigned, 26 | { 27 | cast(n).ok_or_else(|| { 28 | let upcasted = cast::(n).unwrap(); // Shouldn't panic 29 | ErrorKind::UnsignedIntegerCast(upcasted).into() 30 | }) 31 | } 32 | 33 | pub(crate) fn safe_float_cast(n: T) -> error::Result { 34 | cast(n).ok_or_else(|| { 35 | let upcasted = cast::(n).unwrap(); // Shouldn't panic 36 | ErrorKind::FloatCast(upcasted).into() 37 | }) 38 | } 39 | 40 | pub(crate) fn check_seq_len(len: usize) -> error::Result<()> { 41 | safe_uint_cast::(len) 42 | .map(|_| ()) 43 | .chain_err(|| ErrorKind::SeqTooLong(len)) 44 | } 45 | 46 | pub(crate) fn safe_uint_eq(x: T, y: U) -> bool 47 | where T: PrimInt + Unsigned, 48 | U: PrimInt + Unsigned, 49 | { 50 | if let Some(ux) = cast::(x) { // check if T \subseteq U ... 51 | ux == y 52 | } else if let Some(ty) = cast::(y) { // check above failed, then it must be U \subset T here 53 | x == ty 54 | } else { 55 | unreachable!("This kind of comparison always involves upcasting the narrower number \ 56 | to the wider representation since at least one of T \\subseteq U or \ 57 | U \\subseteq T must be true"); 58 | } 59 | } 60 | 61 | 62 | pub(crate) fn i128_from_parts(hi: i64, lo: u64) -> i128 { 63 | i128::from(hi) << 64 | i128::from(lo) 64 | } 65 | 66 | pub(crate) fn u128_from_parts(hi: u64, lo: u64) -> u128 { 67 | u128::from(hi) << 64 | u128::from(lo) 68 | } 69 | 70 | pub(crate) fn i128_to_parts(n: i128) -> (i64, u64) { 71 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_sign_loss, clippy::cast_possible_truncation))] 72 | let lo = n as u64; 73 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_possible_truncation))] 74 | let hi = (n >> 64) as i64; 75 | 76 | (hi, lo) 77 | } 78 | 79 | pub(crate) fn u128_to_parts(n: u128) -> (u64, u64) { 80 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_possible_truncation))] 81 | let lo = n as u64; 82 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_possible_truncation))] 83 | let hi = (n >> 64) as u64; 84 | 85 | (hi, lo) 86 | } 87 | 88 | 89 | #[cfg(test)] 90 | mod tests { 91 | const I128_PARTS: &[(i128, (i64, u64))] = &[ 92 | ( 0x0000_0000_0000_0000_0000_0000_0000_0000, ( 0x0000_0000_0000_0000, 0x0000_0000_0000_0000)), 93 | ( 0x0000_0000_0000_0000_FFFF_FFFF_FFFF_FFFF, ( 0x0000_0000_0000_0000, 0xFFFF_FFFF_FFFF_FFFF)), 94 | ( 0x7777_7777_7777_7777_FFFF_FFFF_FFFF_FFFF, ( 0x7777_7777_7777_7777, 0xFFFF_FFFF_FFFF_FFFF)), 95 | (-0x8000_0000_0000_0000_0000_0000_0000_0000, (-0x8000_0000_0000_0000, 0x0000_0000_0000_0000)), 96 | (-0x0000_0000_0000_0000_0000_0000_0000_0001, (-0x0000_0000_0000_0001, 0xFFFF_FFFF_FFFF_FFFF)), 97 | ]; 98 | 99 | #[test] 100 | fn i128_from_parts() { 101 | for &(n, (hi, lo)) in I128_PARTS { 102 | assert_eq!(crate::utils::i128_from_parts(hi, lo), n); 103 | } 104 | } 105 | 106 | #[test] 107 | fn i128_to_parts() { 108 | for &(n, (hi, lo)) in I128_PARTS { 109 | assert_eq!(crate::utils::i128_to_parts(n), (hi, lo)); 110 | } 111 | } 112 | 113 | 114 | const U128_PARTS: &[(u128, (u64, u64))] = &[ 115 | (0x0000_0000_0000_0000_0000_0000_0000_0000, (0x0000_0000_0000_0000, 0x0000_0000_0000_0000)), 116 | (0x0000_0000_0000_0000_FFFF_FFFF_FFFF_FFFF, (0x0000_0000_0000_0000, 0xFFFF_FFFF_FFFF_FFFF)), 117 | (0x7777_7777_7777_7777_FFFF_FFFF_FFFF_FFFF, (0x7777_7777_7777_7777, 0xFFFF_FFFF_FFFF_FFFF)), 118 | (0x8000_0000_0000_0000_0000_0000_0000_0000, (0x8000_0000_0000_0000, 0x0000_0000_0000_0000)), 119 | (0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF, (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF_FFFF_FFFF)), 120 | ]; 121 | 122 | #[test] 123 | fn u128_from_parts() { 124 | for &(n, (hi, lo)) in U128_PARTS { 125 | assert_eq!(crate::utils::u128_from_parts(hi, lo), n); 126 | } 127 | } 128 | 129 | #[test] 130 | fn u128_to_parts() { 131 | for &(n, (hi, lo)) in U128_PARTS { 132 | assert_eq!(crate::utils::u128_to_parts(n), (hi, lo)); 133 | } 134 | } 135 | 136 | #[cfg(feature = "quickcheck")] 137 | mod quickcheck { 138 | use quickcheck::quickcheck; 139 | 140 | quickcheck! { 141 | // Quickcheck doesn't have an `Arbitrary` impl for `i128`/`u128`, so we need a 142 | // workaround. 143 | fn i128_parts_roundtrip(parts: (i64, u64)) -> bool { 144 | let (hi, lo) = parts; 145 | let n = crate::utils::i128_from_parts(hi, lo); 146 | let (hi2, lo2) = crate::utils::i128_to_parts(n); 147 | 148 | (hi, lo) == (hi2, lo2) 149 | } 150 | 151 | fn u128_parts_roundtrip(parts: (u64, u64)) -> bool { 152 | let (hi, lo) = parts; 153 | let n = crate::utils::u128_from_parts(hi, lo); 154 | let (hi2, lo2) = crate::utils::u128_to_parts(n); 155 | 156 | (hi, lo) == (hi2, lo2) 157 | } 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | This project adheres to [Semantic Versioning](http://semver.org/). 5 | 6 | 7 | ## [Unreleased] 8 | 9 | ### Added 10 | 11 | - Add a new method to `Identifiable` trait: `all_type_ids()` which returns all possible ids of an identifiable type which are known at compile-time. 12 | - `quickcheck::Arbitrary` implementations for `Boxed`, `WithSize` and `BoxedWithSize`. 13 | - Helper functions for calculating size hints `size_hint_from_byte_seq_len` and `size_hint_from_unsized_byte_seq_len` are now exported for public usage. 14 | - You can skip taking a field into account for `#[derive(MtProtoSized)]` by placing `#[mtproto_sized(skip)]` before the field. 15 | - `Box` now is `Identifiable` for any `T: Identifiable`. 16 | - `impl Identifiable for Boxed` which returns id of the inner value. 17 | - Type aliases for `Boxed` (`WithId`) and `BoxedWithSize` (`WithIdAndSize`). 18 | - `WithSize` wrapper type which attaches size hint of a `T: MtProtoSized` type. 19 | - `BoxedWithSize` wrapper type which attaches id and size hint of a `T: Identifiable + MtProtoSized` type. 20 | - `MtProtoSized` implementation for arrays up to length 32 and `Box` where `T: MtProtoSized`. 21 | - Size hints for `de::SeqAccess` and `de::MapAccess`. 22 | - `UnsizedByteBuf` helper type and tests for it. 23 | - `unsized_bytes_pad_to_bytes` and `unsized_bytes_pad_to_writer` convenience serialization functions that write bytes sequence without its length and also pads the sequence so that the length be divisible by 16. 24 | - `from_bytes_reuse` and `from_reader_reuse` which return the derialized value coupled with the bytes reference/reader at the point where deserialization stopped respectively. This allows to use the leftover data afterwards. 25 | - `impl MtProtoSized` for `extprim::i128::u128`, `extprim::u128::u128` and tuples up to arity 12 (like standard library does) 26 | - Benchmarks for primitives, strings, custom types and `extprim` 128-bit types. 27 | - Doctests. 28 | - `ErrorKind::FloatCast` 29 | - `Serializer::into_writer` 30 | - `Deserializer::into_reader` 31 | - `Deserializer::remaining_bytes` 32 | - `Deserializer::remaining_length` 33 | 34 | ### Changed 35 | 36 | - `Deserialize` impl for `Boxed`, `WithSize` and `BoxedWithSize` - now they have custom implementations instead of derived ones to enforce type constraints such as id and size validity at deserialization time (otherwise this could introduce memory safety issues which lead to security holes). 37 | - `Identifiable::type_id()` now returns `u32` instead of `i32`. 38 | - Move `boxed` module to `wrappers`. 39 | - Use shorter method names in `Identifiable` and `MtProtoSized` traits. 40 | - Documentation covers all public items as enforced by `#[deny(missing_docs)]` 41 | - Make dependency on `extprim` an optional feature. 42 | - Now uses `error_chain` 0.11 (can be incompatible with other versions). 43 | 44 | ### Removed 45 | 46 | - `helpers` module along with `Bytes` and `ByteBuf` types. These are now provided by `serde_bytes` crate and we reexport them for convenience. 47 | 48 | ### Fixed 49 | 50 | - `#[derive(MtProtoSized)]` for tuple structs which produced suffixed integers for tuple field accessors. 51 | - Size prediction for strings and byte sequences. 52 | - A bug in `#[derive(MtProtoSized)]` 53 | - Size prediction for 2-tuples. 54 | - `ErrorKind::IntegerCast` now holds an `u64` value which failed to cast. 55 | - Float deserialization: both `f32` and `f64` must be [de]serialized as `f64`. 56 | 57 | 58 | ## [0.3.1] - 2017-08-12 59 | 60 | ### Added 61 | 62 | - `Bytes` and `ByteBuf` helper types to [de]serialize `&[u8]` and `Vec` using the `bytes` Serde data type instead of `seq`. Can be removed when specialization feature arrives to stable Rust. 63 | - Size prediction via `MtProtoSized` trait with respective `#[derive(MtProtoSized)]` 64 | - Documentation. 65 | - Logging via `log` crate. 66 | - `SerErrorKind::NotEnoughElements` 67 | - `ErrorKind::SeqTooLong` 68 | - `ErrorKind::ByteSeqTooLong` 69 | 70 | ### Changed 71 | 72 | - Add checks to `SerializerFixedLengthSeq` implementations of `end` methods from `Serialize*` traits. 73 | 74 | ### Fixed 75 | 76 | - Panics when serializing strings/byte sequences. 77 | 78 | 79 | ## [0.3.0] - 2017-08-09 80 | 81 | ### Added 82 | 83 | - Replace `Wrapper` by `Boxed` which is actually meant for public use (`Wrapper` being public was an accident). 84 | - Handle the edge case in bytes/string serialization when byte length is >= 2^24 == 16 MB because the serialized representation of bytes/string cannot hold more than 3 bytes of length info. 85 | - Better error messages. 86 | - Implement `Clone`, `Debug`, `Eq`, `Hash` and `PartialEq` for `Boxed`. 87 | - Implement `Identifiable` for primitives, strings and `Vec`. 88 | - Basic documentation. 89 | 90 | ### Changed 91 | 92 | - Rename `ser::SerializeMap` to `ser::SerializeFixedLengthMap` to reflect its nature. 93 | 94 | ### Removed 95 | 96 | - `from_*_identifiable` and `to_*_identifiable` functions. Instead use `from_*` and `to_*` combined with wrapping data in `Boxed`. 97 | - `error::DeErrorKind::ExpectedBool` 98 | - `error::DeErrorKind::InvalidFirstByte255` 99 | 100 | 101 | ## [0.2.0] - 2017-08-08 102 | 103 | ### Added 104 | 105 | - [De]serialization for `map` Serde data type. 106 | - `error::SerErrorKind` 107 | - `error::DeErrorKind` 108 | - `error::SerSerdeType` 109 | - `error::DeSerdeType` 110 | 111 | ### Changed 112 | 113 | - Replace panics via `unreachable!()` or `unimplemented!()` by explicit error return values. 114 | - Delegate the serialization of complex Serde data types (`seq`, `tuple`, `tuple_struct`, `tuple_variant`, `struct`, `struct_variant`) to the dedicated `ser::SerializedFixedLengthSeq` type. 115 | - Use type-based errors instead of string-based ones. 116 | 117 | ### Removed 118 | 119 | - `error::IntegerOverflowingCast` 120 | 121 | ### Fixed 122 | 123 | - Handle `serde_mtproto_derive` panic gracefully. 124 | - Properly support [de]serialization for `seq` Serde data type (only for those with length known ahead-of-time). 125 | - Mitigate potential panics in lossy integer castings by returning errors in those cases. 126 | 127 | 128 | ## [0.1.0] - 2017-08-07 129 | 130 | ### Added 131 | 132 | - [De]serialization data format for primitive and some complex Serde data types. 133 | - `Identifiable` trait for types that have an id in MtProto type system. 134 | - `from_bytes`, `from_reader`, `to_bytes` and `to_reader` convenience functions along with their `*_identifiable` counterparts. 135 | - `#[derive(MtProtoIdentifiable)]` for structs and enums. 136 | 137 | 138 | [Unreleased]: https://github.com/hcpl/serde_mtproto/compare/v0.3.1...HEAD 139 | [0.3.1]: https://github.com/hcpl/serde_mtproto/compare/v0.3.0...v0.3.1 140 | [0.3.0]: https://github.com/hcpl/serde_mtproto/compare/v0.2.0...v0.3.0 141 | [0.2.0]: https://github.com/hcpl/serde_mtproto/compare/v0.1.0...v0.2.0 142 | [0.1.0]: https://github.com/hcpl/serde_mtproto/tree/v0.1.0 143 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/sized.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | use crate::ast; 4 | 5 | 6 | pub(crate) fn impl_derive(mut container: ast::Container) -> proc_macro2::TokenStream { 7 | add_mt_proto_sized_trait_bound_if_missing(&mut container); 8 | let (item_impl_generics, item_ty_generics, item_where_clause) = 9 | container.generics.split_for_impl(); 10 | 11 | let item_name = &container.ident; 12 | let dummy_const = ident!("_IMPL_MT_PROTO_SIZED_FOR__{}", item_name); 13 | 14 | let size_hint_body = match container.data { 15 | ast::Data::Struct(ref data_struct) => { 16 | match data_struct.fields { 17 | syn::Fields::Named(ref fields) => { 18 | let size_hints = fields.named.iter().filter_map(|field| { 19 | if is_skippable_field(field) { 20 | return None; 21 | } 22 | 23 | let field_name = &field.ident; 24 | let func = quote_spanned_by! {field=> 25 | _serde_mtproto::MtProtoSized::size_hint 26 | }; 27 | 28 | Some(quote!(#func(&self.#field_name)?)) 29 | }); 30 | 31 | quote!(Ok(0 #(+ #size_hints)*)) 32 | }, 33 | syn::Fields::Unnamed(ref fields) => { 34 | let size_hints = fields.unnamed.iter().enumerate().filter_map(|(i, field)| { 35 | if is_skippable_field(field) { 36 | return None; 37 | } 38 | 39 | // Integers are rendered with type suffixes. We don't want this. 40 | let field_index = syn::Index::from(i); 41 | let func = quote_spanned_by! {field=> 42 | _serde_mtproto::MtProtoSized::size_hint 43 | }; 44 | 45 | Some(quote!(#func(&self.#field_index)?)) 46 | }); 47 | 48 | quote!(Ok(0 #(+ #size_hints)*)) 49 | }, 50 | syn::Fields::Unit => quote!(Ok(0)), 51 | } 52 | }, 53 | ast::Data::Enum(ref data_enum) => { 54 | let variants_quoted = data_enum.variants.iter().map(|variant| { 55 | let variant_name = &variant.ident; 56 | 57 | match variant.fields { 58 | syn::Fields::Named(ref fields) => { 59 | let (patterns, size_hints) = fields.named.iter().filter_map(|field| { 60 | if is_skippable_field(field) { 61 | return None; 62 | } 63 | 64 | let field_name = &field.ident; 65 | let func = quote_spanned_by! {field=> 66 | _serde_mtproto::MtProtoSized::size_hint 67 | }; 68 | 69 | let pattern = quote!(ref #field_name); 70 | let size_hint = quote!(#func(#field_name)?); 71 | 72 | Some((pattern, size_hint)) 73 | }).unzip::<_, _, Vec<_>, Vec<_>>(); 74 | 75 | quote! { 76 | #item_name::#variant_name { #(#patterns),* } => { 77 | Ok(0 #(+ #size_hints)*) 78 | } 79 | } 80 | }, 81 | syn::Fields::Unnamed(ref fields) => { 82 | let (patterns, size_hints) = fields.unnamed.iter().enumerate() 83 | .filter_map(|(i, field)| 84 | { 85 | if is_skippable_field(field) { 86 | return None; 87 | } 88 | 89 | let field_name = ident!("__field_{}", i); 90 | let func = quote_spanned_by! {field=> 91 | _serde_mtproto::MtProtoSized::size_hint 92 | }; 93 | 94 | let pattern = quote!(ref #field_name); 95 | let size_hint = quote!(#func(#field_name)?); 96 | 97 | Some((pattern, size_hint)) 98 | }).unzip::<_, _, Vec<_>, Vec<_>>(); 99 | 100 | quote! { 101 | #item_name::#variant_name(#(#patterns),*) => { 102 | Ok(0 #(+ #size_hints)*) 103 | } 104 | } 105 | }, 106 | syn::Fields::Unit => { 107 | quote! { 108 | #item_name::#variant_name => Ok(0), 109 | } 110 | }, 111 | } 112 | }); 113 | 114 | quote! { 115 | match *self { 116 | #(#variants_quoted)* 117 | } 118 | } 119 | }, 120 | }; 121 | 122 | quote! { 123 | #[allow(non_upper_case_globals)] 124 | const #dummy_const: () = { 125 | extern crate serde_mtproto as _serde_mtproto; 126 | 127 | impl #item_impl_generics _serde_mtproto::MtProtoSized for #item_name #item_ty_generics 128 | #item_where_clause 129 | { 130 | fn size_hint(&self) -> _serde_mtproto::Result { 131 | #size_hint_body 132 | } 133 | } 134 | }; 135 | } 136 | } 137 | 138 | 139 | fn add_mt_proto_sized_trait_bound_if_missing(container: &mut ast::Container) { 140 | 'param: for param in &mut container.generics.params { 141 | if let syn::GenericParam::Type(ref mut type_param) = *param { 142 | for bound in &type_param.bounds { 143 | if let syn::TypeParamBound::Trait(ref trait_bound) = *bound { 144 | if let syn::TraitBoundModifier::None = trait_bound.modifier { 145 | continue; 146 | } 147 | 148 | let path = &trait_bound.path; 149 | if path.leading_colon.is_some() { 150 | continue; 151 | } 152 | 153 | let trait_ref_segments = path.segments 154 | .iter() 155 | .map(|s| s.ident.to_string()); 156 | let mt_proto_sized_segments = vec!["_serde_mtproto", "MtProtoSized"].into_iter(); 157 | 158 | if trait_ref_segments.eq(mt_proto_sized_segments) { 159 | continue 'param; 160 | } 161 | } 162 | } 163 | 164 | type_param.bounds.push(syn::parse_quote!(_serde_mtproto::MtProtoSized)); 165 | } 166 | } 167 | } 168 | 169 | fn is_skippable_field(field: &syn::Field) -> bool { 170 | control_flow_chain! { 171 | for attr in &field.attrs; 172 | if let syn::AttrStyle::Outer = attr.style; 173 | if let Ok(syn::Meta::List(list)) = attr.parse_meta(); 174 | if list.ident == "mtproto_sized"; 175 | for nested_meta in list.nested; 176 | if let syn::NestedMeta::Meta(syn::Meta::Word(ident)) = nested_meta; 177 | if ident == "skip"; 178 | then { 179 | return true; 180 | } 181 | } 182 | 183 | false 184 | } 185 | -------------------------------------------------------------------------------- /serde_mtproto_derive/src/identifiable.rs: -------------------------------------------------------------------------------- 1 | use quote::{ToTokens, quote}; 2 | 3 | use crate::ast; 4 | use crate::ext::IteratorResultExt; 5 | 6 | 7 | pub(crate) fn impl_derive(container: ast::Container) -> proc_macro2::TokenStream { 8 | match impl_derive_or_error(container) { 9 | Ok(tokens) => tokens, 10 | Err(e) => e.iter().map(syn::Error::to_compile_error).collect(), 11 | } 12 | } 13 | 14 | fn impl_derive_or_error( 15 | container: ast::Container, 16 | ) -> Result> { 17 | let (item_impl_generics, item_ty_generics, item_where_clause) = 18 | container.generics.split_for_impl(); 19 | 20 | let item_name = &container.ident; 21 | 22 | let dummy_const = ident!("_IMPL_MT_PROTO_IDENTIFIABLE_FOR_{}", item_name); 23 | 24 | let all_type_ids_value = match container.data { 25 | ast::Data::Struct(_) => { 26 | let id = get_id_from_attrs(&container.attrs, (&container).into_token_stream()) 27 | .map_err(|e| vec![e])?; 28 | 29 | quote!(&[#id]) 30 | }, 31 | ast::Data::Enum(ref data_enum) => { 32 | let ids = data_enum.variants 33 | .iter() 34 | .map(|v| get_id_from_attrs(&v.attrs, v.into_token_stream())) 35 | .collect_results()?; 36 | 37 | quote!(&[#(#ids),*]) 38 | }, 39 | }; 40 | 41 | let all_enum_variant_names_value = match container.data { 42 | ast::Data::Struct(_) => { 43 | quote!(None) 44 | }, 45 | ast::Data::Enum(ref data_enum) => { 46 | let names = data_enum.variants 47 | .iter() 48 | .map(|v| proc_macro2::Literal::string(&v.ident.to_string())); 49 | 50 | quote!(Some(&[#(#names),*])) 51 | }, 52 | }; 53 | 54 | let type_id_body = match container.data { 55 | ast::Data::Struct(_) => { 56 | let id = get_asserted_id_from_attrs(&container.attrs, (&container).into_token_stream()) 57 | .map_err(|e| vec![e])?; 58 | 59 | quote!(#id) 60 | }, 61 | ast::Data::Enum(ref data_enum) => { 62 | let variants = data_enum.variants.iter().map(|variant| { 63 | let variant_name = &variant.ident; 64 | let id = get_asserted_id_from_attrs(&variant.attrs, variant.into_token_stream())?; 65 | 66 | Ok(quote! { 67 | #item_name::#variant_name { .. } => #id, 68 | }) 69 | }).collect_results()?; 70 | 71 | quote! { 72 | match *self { 73 | #(#variants)* 74 | } 75 | } 76 | }, 77 | }; 78 | 79 | let enum_variant_id_body = match container.data { 80 | ast::Data::Struct(_) => { 81 | quote! { None } 82 | }, 83 | ast::Data::Enum(ref data_enum) => { 84 | let variants = data_enum.variants.iter().map(|variant| { 85 | let variant_name = &variant.ident; 86 | let variant_name_string = proc_macro2::Literal::string(&variant_name.to_string()); 87 | 88 | quote! { 89 | #item_name::#variant_name { .. } => #variant_name_string, 90 | } 91 | }); 92 | 93 | quote! { 94 | let variant_id = match *self { 95 | #(#variants)* 96 | }; 97 | 98 | Some(variant_id) 99 | } 100 | }, 101 | }; 102 | 103 | Ok(quote! { 104 | #[allow(non_upper_case_globals)] 105 | const #dummy_const: () = { 106 | extern crate serde_mtproto as _serde_mtproto; 107 | 108 | impl #item_impl_generics _serde_mtproto::Identifiable for #item_name #item_ty_generics 109 | #item_where_clause 110 | { 111 | fn all_type_ids() -> &'static [u32] { 112 | #all_type_ids_value 113 | } 114 | 115 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 116 | #all_enum_variant_names_value 117 | } 118 | 119 | fn type_id(&self) -> u32 { 120 | #type_id_body 121 | } 122 | 123 | fn enum_variant_id(&self) -> Option<&'static str> { 124 | #enum_variant_id_body 125 | } 126 | } 127 | }; 128 | }) 129 | } 130 | 131 | 132 | fn get_asserted_id_from_attrs( 133 | attrs: &[syn::Attribute], 134 | input_tokens: proc_macro2::TokenStream, 135 | ) -> syn::Result { 136 | let id = get_id_from_attrs(attrs, input_tokens)?; 137 | let check_expr = quote!(Self::all_type_ids().contains(&#id)); 138 | 139 | control_flow_chain! { 140 | for attr in attrs; 141 | if let syn::AttrStyle::Outer = attr.style; 142 | if let Ok(syn::Meta::List(list)) = attr.parse_meta(); 143 | if list.ident == "mtproto_identifiable"; 144 | for nested_meta in list.nested; 145 | if let syn::NestedMeta::Meta(syn::Meta::List(nested_list)) = nested_meta; 146 | if nested_list.ident == "check_type_id"; 147 | then { 148 | if nested_list.nested.len() != 1 { 149 | return Err(syn::Error::new_spanned( 150 | nested_list, 151 | "`check_type_id(...)` must have exactly 1 parameter", 152 | )); 153 | } 154 | 155 | if let syn::NestedMeta::Meta(syn::Meta::Word(ref ident)) = nested_list.nested[0] { 156 | let res = match ident.to_string().as_ref() { 157 | "never" => quote!(#id), 158 | "debug_only" => quote!({ debug_assert!(#check_expr); #id }), 159 | "always" => quote!({ assert!(#check_expr); #id }), 160 | _ => continue, 161 | }; 162 | 163 | return Ok(res); 164 | } 165 | } 166 | } 167 | 168 | Ok(quote!({ assert!(#check_expr); #id })) 169 | } 170 | 171 | fn get_id_from_attrs( 172 | attrs: &[syn::Attribute], 173 | input_tokens: proc_macro2::TokenStream, 174 | ) -> syn::Result { 175 | control_flow_chain! { 176 | for attr in attrs; 177 | if let syn::AttrStyle::Outer = attr.style; 178 | if let Ok(syn::Meta::List(list)) = attr.parse_meta(); 179 | if list.ident == "mtproto_identifiable"; 180 | for nested_meta in list.nested; 181 | if let syn::NestedMeta::Meta(syn::Meta::NameValue(name_value)) = nested_meta; 182 | if name_value.ident == "id"; 183 | then { 184 | if let syn::Lit::Str(lit_str) = name_value.lit { 185 | // Found an identifier 186 | let str_value = lit_str.value(); 187 | 188 | if str_value.len() >= 2 { 189 | match str_value.split_at(2) { 190 | ("0x", hex) => return Ok(u32::from_str_radix(hex, 16).unwrap()), 191 | ("0b", bin) => return Ok(u32::from_str_radix(bin, 2).unwrap()), 192 | ("0o", oct) => return Ok(u32::from_str_radix(oct, 8).unwrap()), 193 | _ => (), 194 | } 195 | } 196 | 197 | return Ok(u32::from_str_radix(&str_value, 10).unwrap()); 198 | } else { 199 | return Err(syn::Error::new_spanned( 200 | name_value.lit, 201 | "expected mtproto id attribute to be a string: `id = \"...\"`", 202 | )); 203 | } 204 | } 205 | } 206 | 207 | const ERROR_MESSAGE: &str = "\ 208 | #[derive(MtProtoIdentifiable)] requires an #[mtproto_identifiable(id = \"...\")] attribute\n \ 209 | where id can can be either:\n \ 210 | - hexadecimal with 0x prefix,\n \ 211 | - binary with 0b,\n \ 212 | - octal with 0o\n \ 213 | - or decimal with no prefix."; 214 | 215 | Err(syn::Error::new_spanned(input_tokens, ERROR_MESSAGE)) 216 | } 217 | -------------------------------------------------------------------------------- /src/identifiable.rs: -------------------------------------------------------------------------------- 1 | //! `Identifiable` trait for any Rust data structure that can have an id. 2 | 3 | #![cfg_attr(feature = "cargo-clippy", allow(clippy::unreadable_literal))] // To match the look & feel from TL schema 4 | 5 | 6 | /// Type id of the bool true value. 7 | pub const BOOL_TRUE_ID: u32 = 0x997275b5; 8 | /// Type id of the bool false value. 9 | pub const BOOL_FALSE_ID: u32 = 0xbc799737; 10 | /// Type id of the int type. 11 | pub const INT_ID: u32 = 0xa8509bda; 12 | /// Type id of the long type. 13 | pub const LONG_ID: u32 = 0x22076cba; 14 | /// Type id of the double type. 15 | pub const DOUBLE_ID: u32 = 0x2210c154; 16 | /// Type id of the string type. 17 | pub const STRING_ID: u32 = 0xb5286e24; 18 | /// Type id of the vector type. 19 | pub const VECTOR_ID: u32 = 0x1cb5c415; 20 | 21 | 22 | const BOOL_IDS: &[u32] = &[BOOL_TRUE_ID, BOOL_FALSE_ID]; 23 | const INT_IDS: &[u32] = &[INT_ID]; 24 | const LONG_IDS: &[u32] = &[LONG_ID]; 25 | const DOUBLE_IDS: &[u32] = &[DOUBLE_ID]; 26 | const STRING_IDS: &[u32] = &[STRING_ID]; 27 | const VECTOR_IDS: &[u32] = &[VECTOR_ID]; 28 | 29 | const BOOL_VARIANT_NAMES: &[&str] = &["false", "true"]; 30 | 31 | 32 | /// A trait for a Rust data structure that can have an id. 33 | pub trait Identifiable { 34 | /// Get all possible ids (known at compile time) of an identifiable type. 35 | /// 36 | /// This is most useful for enums where each variant has its own id. 37 | /// 38 | /// # Implementation note 39 | /// 40 | /// This method **should** return a slice of **non-duplicate** values, i.e. 41 | /// the slice must effectively be a set with contents known at compile-time. 42 | /// Currently, there is no way to enforce this restriction using the 43 | /// language itself. 44 | /// 45 | /// This restriction is marked as **should** because it potentially only 46 | /// alters the behavior of counting all ids a type in question has, but not 47 | /// checking if an arbitrary id is in this set - in this case, a reliable 48 | /// counting routine must traverse the whole slice to eliminate duplicates. 49 | /// 50 | /// Unfortunately, this worsens the time complexity from O(*1*) to O(*n*), 51 | /// but for everyday use-case this is fine since product types we usually 52 | /// use are relatively small to make this a big concern. 53 | /// 54 | /// # Compatibility note 55 | /// 56 | /// Will probably be replaced by an associated constant 57 | /// after bumping minimum supported Rust version to 1.20. 58 | /// 59 | /// On the other hand, making static methods associated constants will 60 | /// prevent this trait from usage with dynamic dispatch. 61 | fn all_type_ids() -> &'static [u32] 62 | where Self: Sized; 63 | 64 | /// Get all enum variant names of an identifiable type. 65 | /// 66 | /// For structs this method must return `None` and for enums it must return 67 | /// `Some` with stringified variant names in the same order as the variants 68 | /// themselves. 69 | /// 70 | /// # Compatibility note 71 | /// 72 | /// Will probably be replaced by an associated constant 73 | /// after bumping minimum supported Rust version to 1.20. 74 | /// 75 | /// On the other hand, making static methods associated constants will 76 | /// prevent this trait from usage with dynamic dispatch. 77 | fn all_enum_variant_names() -> Option<&'static [&'static str]> 78 | where Self: Sized; 79 | 80 | /// Get id of a value of an identifiable type. 81 | /// 82 | /// Its signature is made `(&self) -> i32`, not `() -> i32` because of enum 83 | /// types where different enum variants can have different ids. 84 | /// 85 | /// # Implementation note 86 | /// 87 | /// This method **should** return a value contained in the slice returned by 88 | /// `all_type_ids()` method. 89 | /// Currently, there is no way to enforce this restriction using the 90 | /// language itself. 91 | fn type_id(&self) -> u32; 92 | 93 | /// Get enum variant_hint for a value of an identifiable type. 94 | /// 95 | /// This method is purely for assisting `de::Deserializer` to deserialize 96 | /// enum types because `Deserialize` implementations generated by 97 | /// `#[derive(Deserialize)]` call `Deserializer::deserialize_identifier()` 98 | /// to identify an enum variant. 99 | fn enum_variant_id(&self) -> Option<&'static str>; 100 | } 101 | 102 | 103 | impl<'a, T: Identifiable> Identifiable for &'a T { 104 | fn all_type_ids() -> &'static [u32] { 105 | T::all_type_ids() 106 | } 107 | 108 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 109 | T::all_enum_variant_names() 110 | } 111 | 112 | fn type_id(&self) -> u32 { 113 | (*self).type_id() 114 | } 115 | 116 | fn enum_variant_id(&self) -> Option<&'static str> { 117 | (*self).enum_variant_id() 118 | } 119 | } 120 | 121 | impl Identifiable for Box { 122 | fn all_type_ids() -> &'static [u32] { 123 | T::all_type_ids() 124 | } 125 | 126 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 127 | T::all_enum_variant_names() 128 | } 129 | 130 | fn type_id(&self) -> u32 { 131 | (**self).type_id() 132 | } 133 | 134 | fn enum_variant_id(&self) -> Option<&'static str> { 135 | (**self).enum_variant_id() 136 | } 137 | } 138 | 139 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::match_bool))] // match looks better here 140 | impl Identifiable for bool { 141 | fn all_type_ids() -> &'static [u32] { 142 | BOOL_IDS 143 | } 144 | 145 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 146 | Some(BOOL_VARIANT_NAMES) 147 | } 148 | 149 | fn type_id(&self) -> u32 { 150 | match *self { 151 | false => BOOL_FALSE_ID, 152 | true => BOOL_TRUE_ID, 153 | } 154 | } 155 | 156 | // Doesn't really serve any purpose here, but implement anyway for completeness 157 | fn enum_variant_id(&self) -> Option<&'static str> { 158 | match *self { 159 | false => Some("false"), 160 | true => Some("true"), 161 | } 162 | } 163 | } 164 | 165 | 166 | macro_rules! impl_identifiable_for_simple_types { 167 | ($($type:ty => ($all_ids:expr, $id_of_value:expr),)*) => { 168 | $( 169 | impl Identifiable for $type { 170 | fn all_type_ids() -> &'static [u32] { 171 | $all_ids 172 | } 173 | 174 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 175 | None 176 | } 177 | 178 | fn type_id(&self) -> u32 { 179 | $id_of_value 180 | } 181 | 182 | fn enum_variant_id(&self) -> Option<&'static str> { 183 | None 184 | } 185 | } 186 | )* 187 | }; 188 | } 189 | 190 | // Not implemented for `usize` and `isize` because of their machine-dependent nature: 191 | // on 32-bit machine they would have int id, but on 64-bit - long id. 192 | impl_identifiable_for_simple_types! { 193 | i8 => (INT_IDS, INT_ID), 194 | i16 => (INT_IDS, INT_ID), 195 | i32 => (INT_IDS, INT_ID), 196 | i64 => (LONG_IDS, LONG_ID), 197 | 198 | u8 => (INT_IDS, INT_ID), 199 | u16 => (INT_IDS, INT_ID), 200 | u32 => (INT_IDS, INT_ID), 201 | u64 => (LONG_IDS, LONG_ID), 202 | 203 | f32 => (DOUBLE_IDS, DOUBLE_ID), 204 | f64 => (DOUBLE_IDS, DOUBLE_ID), 205 | 206 | String => (STRING_IDS, STRING_ID), 207 | } 208 | 209 | impl<'a> Identifiable for &'a str { 210 | fn all_type_ids() -> &'static [u32] { 211 | STRING_IDS 212 | } 213 | 214 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 215 | None 216 | } 217 | 218 | fn type_id(&self) -> u32 { 219 | STRING_ID 220 | } 221 | 222 | fn enum_variant_id(&self) -> Option<&'static str> { 223 | None 224 | } 225 | } 226 | 227 | impl Identifiable for Vec { 228 | fn all_type_ids() -> &'static [u32] { 229 | VECTOR_IDS 230 | } 231 | 232 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 233 | None 234 | } 235 | 236 | fn type_id(&self) -> u32 { 237 | VECTOR_ID 238 | } 239 | 240 | fn enum_variant_id(&self) -> Option<&'static str> { 241 | None 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! When serializing or deserializing MTProto goes wrong. 2 | 3 | // Temporary fix for `std::error::Error::cause()` usage in `error_chain!`-generated code 4 | // Should be resolved upstream in 5 | #![allow(deprecated)] 6 | 7 | use std::fmt; 8 | 9 | use error_chain::error_chain; 10 | use serde::{ser, de}; 11 | 12 | 13 | error_chain! { 14 | foreign_links { 15 | Io(::std::io::Error) #[doc = "Wraps an `io::Error`"]; 16 | FromUtf8(::std::string::FromUtf8Error) #[doc = "Wraps a `FromUtf8Error`"]; 17 | } 18 | 19 | errors { 20 | /// An error during serialization. 21 | Ser(kind: SerErrorKind) { 22 | description("serialization error in serde_mtproto") 23 | display("serialization error in serde_mtproto: {}", kind) 24 | } 25 | 26 | /// An error during deserialization. 27 | De(kind: DeErrorKind) { 28 | description("deserialization error in serde_mtproto") 29 | display("deserialization error in serde_mtproto: {}", kind) 30 | } 31 | 32 | /// Error while casting a signed integer. 33 | SignedIntegerCast(num: crate::utils::IntMax) { 34 | description("error while casting a signed integer") 35 | display("error while casting a signed integer: {}", num) 36 | } 37 | 38 | /// Error while casting an unsigned integer. 39 | UnsignedIntegerCast(num: crate::utils::UIntMax) { 40 | description("error while casting an unsigned integer") 41 | display("error while casting an unsigned integer: {}", num) 42 | } 43 | 44 | /// Error while casting a floating-point number. 45 | FloatCast(num: f64) { 46 | description("error while casting a floating-point number") 47 | display("error while casting a floating-point number: {}", num) 48 | } 49 | 50 | /// A string that cannot be serialized because it exceeds a certain length limit. 51 | StringTooLong(len: usize) { 52 | description("string is too long to serialize") 53 | display("string of length {} is too long to serialize", len) 54 | } 55 | 56 | /// A byte sequence that cannot be serialized because it exceeds a certain length limit. 57 | ByteSeqTooLong(len: usize) { 58 | description("byte sequence is too long to serialize") 59 | display("byte sequence of length {} is too long to serialize", len) 60 | } 61 | 62 | /// A sequence that cannot be serialized because it exceeds a certain length limit. 63 | SeqTooLong(len: usize) { 64 | description("sequence is too long to serialize") 65 | display("sequence of length {} is too long to serialize", len) 66 | } 67 | } 68 | } 69 | 70 | 71 | /// Serialization error kinds. 72 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 73 | pub enum SerErrorKind { 74 | /// A convenient variant for String. 75 | Msg(String), 76 | /// Excess elements found, stores the needed count. 77 | ExcessElements(u32), 78 | /// Cannot serialize maps with unknown length. 79 | MapsWithUnknownLengthUnsupported, 80 | /// Not enough elements, stores the actual and needed count. 81 | NotEnoughElements(u32, u32), 82 | /// Cannot serialize sequences with unknown length. 83 | SeqsWithUnknownLengthUnsupported, 84 | /// A string that cannot be serialized because it exceeds a certain length limit. 85 | StringTooLong(usize), 86 | /// This `serde` data format doesn't support several types in the Serde data model. 87 | UnsupportedSerdeType(SerSerdeType), 88 | } 89 | 90 | impl fmt::Display for SerErrorKind { 91 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 92 | match *self { 93 | SerErrorKind::Msg(ref string) => { 94 | write!(f, "custom string: {}", string) 95 | }, 96 | SerErrorKind::ExcessElements(len) => { 97 | write!(f, "excess elements, need no more than {}", len) 98 | }, 99 | SerErrorKind::MapsWithUnknownLengthUnsupported => { 100 | write!(f, "maps with ahead-of-time unknown length are not supported") 101 | }, 102 | SerErrorKind::NotEnoughElements(unexpected_len, expected_len) => { 103 | write!(f, "not enough elements: have {}, need {}", unexpected_len, expected_len) 104 | }, 105 | SerErrorKind::SeqsWithUnknownLengthUnsupported => { 106 | write!(f, "seqs with ahead-of-time unknown length are not supported") 107 | }, 108 | SerErrorKind::StringTooLong(len) => { 109 | write!(f, "string of length {} is too long to serialize", len) 110 | }, 111 | SerErrorKind::UnsupportedSerdeType(ref type_) => { 112 | write!(f, "{} type is not supported for serialization", type_) 113 | }, 114 | } 115 | } 116 | } 117 | 118 | /// Serde serialization data types that are not supported by `serde_mtproto`. 119 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 120 | pub enum SerSerdeType { 121 | /// Single character type. 122 | Char, 123 | /// None value of Option type. 124 | None, 125 | /// Some value of Option type. 126 | Some, 127 | /// Unit `()` type. 128 | Unit, 129 | } 130 | 131 | impl fmt::Display for SerSerdeType { 132 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 133 | let repr = match *self { 134 | SerSerdeType::Char => "char", 135 | SerSerdeType::None => "none", 136 | SerSerdeType::Some => "some", 137 | SerSerdeType::Unit => "unit", 138 | }; 139 | 140 | f.write_str(repr) 141 | } 142 | } 143 | 144 | impl From for Error { 145 | fn from(kind: SerErrorKind) -> Error { 146 | ErrorKind::Ser(kind).into() 147 | } 148 | } 149 | 150 | 151 | /// Deserialization error kinds. 152 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 153 | pub enum DeErrorKind { 154 | /// A convenient variant for String. 155 | Msg(String), 156 | /// Bytes sequence with the 0xfe prefix, but with length less than 254. 157 | BytesLenPrefix254LessThan254(u32), 158 | /// Padding for a bytes sequence that has at least one non-zero byte. 159 | NonZeroBytesPadding, 160 | /// This `serde` data format doesn't support several types in the Serde data model. 161 | UnsupportedSerdeType(DeSerdeType), 162 | /// Not enough elements, stores the already deserialized and expected count. 163 | NotEnoughElements(u32, u32), 164 | /// A wrong map key found while deserializing. 165 | InvalidMapKey(String, &'static str), 166 | /// A wrong type id found while deserializing. 167 | InvalidTypeId(u32, &'static [u32]), 168 | /// The deserialized type id and the one known from value aren't the same. 169 | TypeIdMismatch(u32, u32), 170 | /// No enum variant id found in the deserializer to continue deserialization. 171 | NoEnumVariantId, 172 | /// The deserialized size and the predicted one aren't the same. 173 | SizeMismatch(u32, u32), 174 | } 175 | 176 | impl fmt::Display for DeErrorKind { 177 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 178 | match *self { 179 | DeErrorKind::Msg(ref string) => { 180 | write!(f, "custom string: {}", string) 181 | }, 182 | DeErrorKind::BytesLenPrefix254LessThan254(len) => { 183 | write!(f, "byte sequence has the 0xfe prefix with length less than 254 {}", len) 184 | }, 185 | DeErrorKind::NonZeroBytesPadding => { 186 | write!(f, "byte sequence has a padding with a non-zero byte") 187 | }, 188 | DeErrorKind::UnsupportedSerdeType(ref type_) => { 189 | write!(f, "{} type is not supported for deserialization", type_) 190 | }, 191 | DeErrorKind::NotEnoughElements(deserialized_count, expected_count) => { 192 | write!(f, "not enough elements: have {}, need {}", deserialized_count, expected_count) 193 | }, 194 | DeErrorKind::InvalidMapKey(ref found_key, expected_key) => { 195 | write!(f, "invalid map key {:?}, expected {:?}", found_key, expected_key) 196 | }, 197 | DeErrorKind::InvalidTypeId(found_type_id, valid_type_ids) => { 198 | write!(f, "invalid type id {}, expected {:?}", found_type_id, valid_type_ids) 199 | }, 200 | DeErrorKind::TypeIdMismatch(deserialized_type_id, static_type_id) => { 201 | write!(f, "type id mismatch: deserialized {}, but {} found from value", 202 | deserialized_type_id, static_type_id) 203 | }, 204 | DeErrorKind::NoEnumVariantId => { 205 | write!(f, "no enum variant id found in deserializer") 206 | }, 207 | DeErrorKind::SizeMismatch(deserialized_size, static_size_hint) => { 208 | write!(f, "size mismatch: deserialized {}, predicted {}", 209 | deserialized_size, static_size_hint) 210 | }, 211 | } 212 | } 213 | } 214 | 215 | /// Serde deserialization data types that are not supported by `serde_mtproto`. 216 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 217 | pub enum DeSerdeType { 218 | /// `serde_mtproto` doesn't support `*_any` hint. 219 | Any, 220 | /// Single character type. 221 | Char, 222 | /// Option type. 223 | Option, 224 | /// Unit `()` type. 225 | Unit, 226 | /// `serde_mtproto` doesn't support `*_ignored_any` hint. 227 | IgnoredAny, 228 | } 229 | 230 | impl fmt::Display for DeSerdeType { 231 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 232 | let repr = match *self { 233 | DeSerdeType::Any => "any", 234 | DeSerdeType::Char => "char", 235 | DeSerdeType::Option => "option", 236 | DeSerdeType::Unit => "unit", 237 | DeSerdeType::IgnoredAny => "ignored_any", 238 | }; 239 | 240 | f.write_str(repr) 241 | } 242 | } 243 | 244 | impl From for Error { 245 | fn from(kind: DeErrorKind) -> Error { 246 | ErrorKind::De(kind).into() 247 | } 248 | } 249 | 250 | 251 | impl ser::Error for Error { 252 | fn custom(msg: T) -> Error { 253 | SerErrorKind::Msg(msg.to_string()).into() 254 | } 255 | } 256 | 257 | impl de::Error for Error { 258 | fn custom(msg: T) -> Error { 259 | DeErrorKind::Msg(msg.to_string()).into() 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /src/sized.rs: -------------------------------------------------------------------------------- 1 | //! `MtProtoSized` trait for any Rust data structure a predictable size of its MTProto binary 2 | //! representation can be computed. 3 | //! 4 | //! # Examples 5 | //! 6 | //! ``` 7 | //! use serde_mtproto::{MtProtoSized, ByteBuf}; 8 | //! 9 | //! struct Something { 10 | //! name: String, 11 | //! small_num: u16, 12 | //! raw_data: ByteBuf, 13 | //! pair: (i8, u64), 14 | //! } 15 | //! 16 | //! // Implement manually 17 | //! 18 | //! impl MtProtoSized for Something { 19 | //! fn size_hint(&self) -> serde_mtproto::Result { 20 | //! let mut result = 0; 21 | //! 22 | //! result += self.name.size_hint()?; 23 | //! result += self.small_num.size_hint()?; 24 | //! result += self.raw_data.size_hint()?; 25 | //! result += self.pair.size_hint()?; 26 | //! 27 | //! Ok(result) 28 | //! } 29 | //! } 30 | //! 31 | //! # fn run() -> serde_mtproto::Result<()> { 32 | //! let smth = Something { 33 | //! name: "John Smith".to_owned(), 34 | //! small_num: 2000u16, 35 | //! raw_data: ByteBuf::from(vec![0xf4, 0x58, 0x2e, 0x33]), 36 | //! pair: (-50, 0xffff_ffff_ffff_ffff), 37 | //! }; 38 | //! 39 | //! // "John Smith" => 1 byte length, 10 bytes data, 1 byte padding; 40 | //! // 2000u16 => 4 bytes; 41 | //! // ByteBuf { ... } => 1 byte length, 4 bytes data, 3 bytes padding; 42 | //! // (-50, 0xffff_ffff_ffff_ffff) => 4 bytes + 8 bytes == 12 bytes; 43 | //! // 44 | //! // Total: 12 + 4 + 8 + 12 == 36 bytes 45 | //! 46 | //! assert_eq!(36, smth.size_hint()?); 47 | //! # Ok(()) 48 | //! # } 49 | //! 50 | //! # fn main() { run().unwrap(); } 51 | //! ``` 52 | //! 53 | //! Alternatively, `MtProtoSized` can be `#[derive]`d: 54 | //! 55 | //! ``` 56 | //! #[macro_use] 57 | //! extern crate serde_mtproto_derive; 58 | //! 59 | //! #[derive(MtProtoSized)] 60 | //! struct Something { 61 | //! name: String, 62 | //! small_num: u16, 63 | //! raw_data: Vec, 64 | //! pair: (i8, u64), 65 | //! } 66 | //! 67 | //! # fn main() {} 68 | //! ``` 69 | //! 70 | //! The derived implementation is the same as the one shown above. 71 | 72 | use std::collections::{HashMap, BTreeMap}; 73 | use std::hash::{BuildHasher, Hash}; 74 | 75 | use error_chain::bail; 76 | use serde_bytes::{ByteBuf, Bytes}; 77 | 78 | use crate::error::{self, ErrorKind}; 79 | use crate::utils::check_seq_len; 80 | 81 | 82 | /// Size of a bool MtProto value. 83 | pub const BOOL_SIZE: usize = 4; 84 | /// Size of an int MtProto value. 85 | pub const INT_SIZE: usize = 4; 86 | /// Size of a long MtProto value. 87 | pub const LONG_SIZE: usize = 8; 88 | /// Size of a double MtProto value. 89 | pub const DOUBLE_SIZE: usize = 8; 90 | /// Size of an int128 MtProto value. 91 | pub const INT128_SIZE: usize = 16; 92 | 93 | 94 | /// A trait for a Rust data structure a predictable size of its MTProto binary representation 95 | /// can be computed. 96 | pub trait MtProtoSized { 97 | /// Compute the size of MTProto binary representation of this value without actually 98 | /// serializing it. 99 | /// 100 | /// Returns an `error::Result` because not any value can be serialized (e.g. strings and 101 | /// sequences that are too long). 102 | fn size_hint(&self) -> error::Result; 103 | } 104 | 105 | 106 | macro_rules! impl_mt_proto_sized_for_primitives { 107 | ($($type:ty => $size:expr,)+) => { 108 | $( 109 | impl MtProtoSized for $type { 110 | fn size_hint(&self) -> error::Result { 111 | Ok($size) 112 | } 113 | } 114 | )+ 115 | }; 116 | } 117 | 118 | impl_mt_proto_sized_for_primitives! { 119 | bool => BOOL_SIZE, 120 | 121 | // Minimum MTProto integer size is 4 bytes 122 | i8 => INT_SIZE, 123 | i16 => INT_SIZE, 124 | i32 => INT_SIZE, 125 | i64 => LONG_SIZE, 126 | i128 => INT128_SIZE, 127 | 128 | // Same here 129 | u8 => INT_SIZE, 130 | u16 => INT_SIZE, 131 | u32 => INT_SIZE, 132 | u64 => LONG_SIZE, 133 | u128 => INT128_SIZE, 134 | 135 | f32 => DOUBLE_SIZE, 136 | f64 => DOUBLE_SIZE, 137 | } 138 | 139 | 140 | /// Helper function for everything naturally representable as a byte sequence. 141 | /// 142 | /// This version **does take** into account the byte sequence length, which is prepended to the 143 | /// serialized representation of the byte sequence. 144 | pub fn size_hint_from_byte_seq_len(len: usize) -> error::Result { 145 | let (len_info, data, padding) = if len <= 253 { 146 | (1, len, (4 - (len + 1) % 4) % 4) 147 | } else if len <= 0xff_ff_ff { 148 | (4, len, (4 - len % 4) % 4) 149 | } else { 150 | bail!(ErrorKind::StringTooLong(len)); 151 | }; 152 | 153 | let size = len_info + data + padding; 154 | assert!(size % 4 == 0); 155 | 156 | Ok(size) 157 | } 158 | 159 | impl<'a> MtProtoSized for &'a str { 160 | fn size_hint(&self) -> error::Result { 161 | size_hint_from_byte_seq_len(self.as_bytes().len()) 162 | } 163 | } 164 | 165 | impl MtProtoSized for String { 166 | fn size_hint(&self) -> error::Result { 167 | size_hint_from_byte_seq_len(self.as_bytes().len()) 168 | } 169 | } 170 | 171 | impl<'a, T: ?Sized + MtProtoSized> MtProtoSized for &'a T { 172 | fn size_hint(&self) -> error::Result { 173 | (*self).size_hint() 174 | } 175 | } 176 | 177 | impl MtProtoSized for Box { 178 | fn size_hint(&self) -> error::Result { 179 | (**self).size_hint() 180 | } 181 | } 182 | 183 | impl<'a, T: MtProtoSized> MtProtoSized for &'a [T] { 184 | fn size_hint(&self) -> error::Result { 185 | // If len >= 2 ** 32, it's not serializable at all. 186 | check_seq_len(self.len())?; 187 | 188 | let mut result = 4; // 4 for slice length 189 | 190 | for elem in self.iter() { 191 | result += elem.size_hint()?; 192 | } 193 | 194 | // Check again just to be sure 195 | check_seq_len(result)?; 196 | 197 | Ok(result) 198 | } 199 | } 200 | 201 | impl MtProtoSized for Vec { 202 | fn size_hint(&self) -> error::Result { 203 | self.as_slice().size_hint() 204 | } 205 | } 206 | 207 | impl MtProtoSized for HashMap 208 | where K: Eq + Hash + MtProtoSized, 209 | V: MtProtoSized, 210 | S: BuildHasher, 211 | { 212 | fn size_hint(&self) -> error::Result { 213 | // If len >= 2 ** 32, it's not serializable at all. 214 | check_seq_len(self.len())?; 215 | 216 | let mut result = 4; // 4 for map length 217 | 218 | for (k, v) in self.iter() { 219 | result += k.size_hint()?; 220 | result += v.size_hint()?; 221 | } 222 | 223 | // Check again just to be sure 224 | check_seq_len(result)?; 225 | 226 | Ok(result) 227 | } 228 | } 229 | 230 | impl MtProtoSized for BTreeMap 231 | where K: MtProtoSized, 232 | V: MtProtoSized, 233 | { 234 | fn size_hint(&self) -> error::Result { 235 | // If len >= 2 ** 32, it's not serializable at all. 236 | check_seq_len(self.len())?; 237 | 238 | let mut result = 4; // 4 for map length 239 | 240 | for (k, v) in self.iter() { 241 | result += k.size_hint()?; 242 | result += v.size_hint()?; 243 | } 244 | 245 | // Check again just to be sure 246 | check_seq_len(result)?; 247 | 248 | Ok(result) 249 | } 250 | } 251 | 252 | impl MtProtoSized for () { 253 | fn size_hint(&self) -> error::Result { 254 | Ok(0) 255 | } 256 | } 257 | 258 | impl<'a> MtProtoSized for &'a Bytes { 259 | fn size_hint(&self) -> error::Result { 260 | size_hint_from_byte_seq_len(self.len()) 261 | } 262 | } 263 | 264 | impl MtProtoSized for ByteBuf { 265 | fn size_hint(&self) -> error::Result { 266 | size_hint_from_byte_seq_len(self.len()) 267 | } 268 | } 269 | 270 | macro_rules! impl_mt_proto_sized_for_tuple { 271 | ($($ident:ident : $ty:ident ,)+) => { 272 | impl<$($ty),+> MtProtoSized for ($($ty,)+) 273 | where $($ty: MtProtoSized,)+ 274 | { 275 | fn size_hint(&self) -> error::Result { 276 | let mut result = 0; 277 | let ($(ref $ident,)+) = *self; 278 | $( result += $ident.size_hint()?; )+ 279 | Ok(result) 280 | } 281 | } 282 | }; 283 | } 284 | 285 | impl_mt_proto_sized_for_tuple! { x1: T1, } 286 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, } 287 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, } 288 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, } 289 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, } 290 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, } 291 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, } 292 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, } 293 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, 294 | x9: T9, } 295 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, 296 | x9: T9, x10: T10, } 297 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, 298 | x9: T9, x10: T10, x11: T11, } 299 | impl_mt_proto_sized_for_tuple! { x1: T1, x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, 300 | x9: T9, x10: T10, x11: T11, x12: T12, } 301 | 302 | macro_rules! impl_mt_proto_sized_for_arrays { 303 | (__impl 0) => { 304 | impl MtProtoSized for [T; 0] { 305 | fn size_hint(&self) -> error::Result { 306 | Ok(0) 307 | } 308 | } 309 | }; 310 | 311 | (__impl $size:expr) => { 312 | impl MtProtoSized for [T; $size] { 313 | fn size_hint(&self) -> error::Result { 314 | let mut result = 0; 315 | 316 | for elem in self { 317 | result += elem.size_hint()?; 318 | } 319 | 320 | Ok(result) 321 | } 322 | } 323 | }; 324 | 325 | ($($size:expr),+) => { 326 | $( impl_mt_proto_sized_for_arrays!(__impl $size); )+ 327 | }; 328 | } 329 | 330 | impl_mt_proto_sized_for_arrays!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 331 | 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32); 332 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /src/wrappers.rs: -------------------------------------------------------------------------------- 1 | //! Wrapper structs for attaching additional data to a type for 2 | //! [de]serialization purposes. 3 | //! 4 | //! ## Data and metadata layout 5 | //! 6 | //! | Wrapper type | Layout | 7 | //! |--------------|--------------| 8 | //! | [`Boxed`] | (id, data) | 9 | //! | [`WithSize`] | (size, data) | 10 | //! 11 | //! ## How does `Boxed>` differ from `WithSize>`? 12 | //! 13 | //! The first is laid out as (id, size, data) while the second — as 14 | //! (size, id, data). 15 | //! While the `id` value in both cases represent the type id of `data` 16 | //! the `size` value in two layouts above are not the same thing: in the 17 | //! first one it equals `data.size_hint()?`, but in the second one it 18 | //! equals `data.size_hint()? + 4` because it also includes the size of 19 | //! the `id` value. 20 | //! 21 | //! ## `Boxed` vs `WithId` 22 | //! 23 | //! `Boxed` type has an alias `WithId` to convey different meanings 24 | //! about it: 25 | //! 26 | //! * `Boxed` means "not a bare `T`" where boxed/bare types 27 | //! distinction is drawn from the MTProto official documentation about 28 | //! serialization: 29 | //! . 30 | //! * `WithId` means "`T` with an id" which explains *how* this type 31 | //! arranges data and metadata. 32 | //! 33 | //! This crate uses `Boxed` as the main naming scheme, whereas `WithId` 34 | //! is a type alias. 35 | 36 | use std::fmt; 37 | use std::marker::PhantomData; 38 | 39 | use error_chain::bail; 40 | #[cfg(feature = "quickcheck")] 41 | use quickcheck::{Arbitrary, Gen}; 42 | use serde::de::{Deserialize, DeserializeSeed, Deserializer, 43 | Error as DeError, MapAccess, SeqAccess, Visitor}; 44 | use serde::ser::{Error as SerError, Serialize, Serializer, SerializeStruct}; 45 | use serde_derive::Deserialize; 46 | 47 | use crate::error::{self, DeErrorKind}; 48 | use crate::identifiable::Identifiable; 49 | use crate::sized::MtProtoSized; 50 | use crate::utils::{safe_uint_cast, safe_uint_eq}; 51 | 52 | 53 | /// A struct that wraps an [`Identifiable`] type value to serialize and 54 | /// deserialize as a boxed MTProto data type. 55 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 56 | pub struct Boxed { 57 | inner: T, 58 | } 59 | 60 | /// An alias for [`Boxed`] that is similar to [`WithSize`]. 61 | pub type WithId = Boxed; 62 | 63 | impl Boxed { 64 | /// Wrap a value along with its id. 65 | pub fn new(inner: T) -> Boxed { 66 | Boxed { inner } 67 | } 68 | 69 | /// Return an immutable reference to the underlying data. 70 | pub fn inner(&self) -> &T { 71 | &self.inner 72 | } 73 | 74 | /// Return a mutable reference to the underlying data. 75 | pub fn inner_mut(&mut self) -> &mut T { 76 | &mut self.inner 77 | } 78 | 79 | /// Unwrap the box and return the wrapped value. 80 | pub fn into_inner(self) -> T { 81 | self.inner 82 | } 83 | } 84 | 85 | impl Serialize for Boxed 86 | where T: Serialize + Identifiable 87 | { 88 | fn serialize(&self, serializer: S) -> Result 89 | where S: Serializer, 90 | { 91 | let mut ser = serializer.serialize_struct("Boxed", 2)?; 92 | ser.serialize_field("id", &self.inner.type_id())?; 93 | ser.serialize_field("inner", &self.inner)?; 94 | ser.end() 95 | } 96 | } 97 | 98 | // Using a custom implementation instead of the derived one because we need to check validity 99 | // of the deserialized type id __before__ deserializing the value. 100 | impl<'de, T> Deserialize<'de> for Boxed 101 | where T: Deserialize<'de> + Identifiable 102 | { 103 | fn deserialize(deserializer: D) -> Result, D::Error> 104 | where D: Deserializer<'de> 105 | { 106 | struct BoxedVisitor(PhantomData); 107 | 108 | impl<'de, T> Visitor<'de> for BoxedVisitor 109 | where T: Deserialize<'de> + Identifiable 110 | { 111 | type Value = Boxed; 112 | 113 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 114 | f.write_str("type id and an `Identifiable` value") 115 | } 116 | 117 | fn visit_seq(self, mut seq: A) -> Result, A::Error> 118 | where A: SeqAccess<'de> 119 | { 120 | let type_id = next_seq_element(&mut seq, 0, 2)?; 121 | check_type_id::(type_id).map_err(A::Error::custom)?; 122 | 123 | let value = next_seq_element(&mut seq, 1, 2)?; 124 | checked_boxed_value::(type_id, value).map_err(A::Error::custom) 125 | } 126 | 127 | fn visit_map(self, mut map: A) -> Result, A::Error> 128 | where A: MapAccess<'de> 129 | { 130 | let type_id = next_struct_element(&mut map, "id", 0, 2)?; 131 | check_type_id::(type_id).map_err(A::Error::custom)?; 132 | 133 | let value = next_struct_element(&mut map, "inner", 1, 2)?; 134 | checked_boxed_value::(type_id, value).map_err(A::Error::custom) 135 | } 136 | } 137 | 138 | fn checked_boxed_value(type_id: u32, value: T) -> error::Result> { 139 | if type_id != value.type_id() { 140 | bail!(DeErrorKind::TypeIdMismatch(type_id, value.type_id())); 141 | } 142 | 143 | Ok(Boxed::new(value)) 144 | } 145 | 146 | deserializer.deserialize_struct("Boxed", &["id", "inner"], BoxedVisitor(PhantomData)) 147 | } 148 | } 149 | 150 | impl Identifiable for Boxed { 151 | fn all_type_ids() -> &'static [u32] { 152 | T::all_type_ids() 153 | } 154 | 155 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 156 | T::all_enum_variant_names() 157 | } 158 | 159 | fn type_id(&self) -> u32 { 160 | T::type_id(&self.inner) 161 | } 162 | 163 | fn enum_variant_id(&self) -> Option<&'static str> { 164 | T::enum_variant_id(&self.inner) 165 | } 166 | } 167 | 168 | impl MtProtoSized for Boxed { 169 | fn size_hint(&self) -> error::Result { 170 | // Just an u32 value to use for `::size_hint` 171 | let id_size_hint = 0_u32.size_hint()?; 172 | let inner_size_hint = self.inner.size_hint()?; 173 | 174 | Ok(id_size_hint + inner_size_hint) 175 | } 176 | } 177 | 178 | #[cfg(feature = "quickcheck")] 179 | impl Arbitrary for Boxed 180 | where T: Arbitrary + Identifiable 181 | { 182 | fn arbitrary(g: &mut G) -> Boxed { 183 | Boxed::new(T::arbitrary(g)) 184 | } 185 | 186 | fn shrink(&self) -> Box>> { 187 | Box::new(self.inner.shrink().map(Boxed::new)) 188 | } 189 | } 190 | 191 | 192 | /// A struct that wraps a [`MtProtoSized`] type value to serialize and 193 | /// deserialize as a MTProto data type with the size of its serialized 194 | /// value. 195 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 196 | pub struct WithSize { 197 | inner: T, 198 | } 199 | 200 | impl WithSize { 201 | /// Wrap a value along with its serialized size. 202 | pub fn new(inner: T) -> error::Result> { 203 | Ok(WithSize { inner }) 204 | } 205 | 206 | /// Return an immutable reference to the underlying data. 207 | pub fn inner(&self) -> &T { 208 | &self.inner 209 | } 210 | 211 | /// Return a mutable reference to the underlying data. 212 | pub fn inner_mut(&mut self) -> &mut T { 213 | &mut self.inner 214 | } 215 | 216 | /// Unwrap the box and return the wrapped value. 217 | pub fn into_inner(self) -> T { 218 | self.inner 219 | } 220 | } 221 | 222 | impl Serialize for WithSize 223 | where T: Serialize + MtProtoSized 224 | { 225 | fn serialize(&self, serializer: S) -> Result 226 | where S: Serializer, 227 | { 228 | let size_usize = self.inner.size_hint().map_err(S::Error::custom)?; 229 | let size_u32 = safe_uint_cast::(size_usize).map_err(S::Error::custom)?; 230 | 231 | let mut ser = serializer.serialize_struct("WithSize", 2)?; 232 | ser.serialize_field("size", &size_u32)?; 233 | ser.serialize_field("inner", &self.inner)?; 234 | ser.end() 235 | } 236 | } 237 | 238 | // Using a custom implementation instead of the derived one because we need to check validity 239 | // of the deserialized size against the size hint of a deserialized value. 240 | impl<'de, T> Deserialize<'de> for WithSize 241 | where T: Deserialize<'de> + MtProtoSized 242 | { 243 | fn deserialize(deserializer: D) -> Result, D::Error> 244 | where D: Deserializer<'de> 245 | { 246 | // Here we only implement through a helper struct because fully manual implementation 247 | // (like what is present for `Boxed`) won't provide us eny benefits over this solution - we 248 | // can obtain a deserialized size beforehand, but we can't apply it since neither Serde 249 | // deserializable types, nor Serde deserializers in general have any means to limit the 250 | // amount of raw data to be processed. 251 | #[derive(Deserialize)] 252 | #[serde(rename = "WithSize")] 253 | struct WithSizeHelper { 254 | size: u32, 255 | inner: T, 256 | } 257 | 258 | let helper = WithSizeHelper::::deserialize(deserializer)?; 259 | let helper_size_hint = helper.inner.size_hint().map_err(D::Error::custom)?; 260 | 261 | if !safe_uint_eq(helper.size, helper_size_hint) { 262 | bail!(errconv::(DeErrorKind::SizeMismatch( 263 | helper.size, 264 | safe_uint_cast(helper_size_hint).map_err(D::Error::custom)?, 265 | ))); 266 | } 267 | 268 | Ok(WithSize { 269 | inner: helper.inner, 270 | }) 271 | } 272 | } 273 | 274 | impl Identifiable for WithSize { 275 | fn all_type_ids() -> &'static [u32] { 276 | T::all_type_ids() 277 | } 278 | 279 | fn all_enum_variant_names() -> Option<&'static [&'static str]> { 280 | T::all_enum_variant_names() 281 | } 282 | 283 | fn type_id(&self) -> u32 { 284 | T::type_id(&self.inner) 285 | } 286 | 287 | fn enum_variant_id(&self) -> Option<&'static str> { 288 | T::enum_variant_id(&self.inner) 289 | } 290 | } 291 | 292 | impl MtProtoSized for WithSize { 293 | fn size_hint(&self) -> error::Result { 294 | // Just an u32 value to use for `::size_hint` 295 | let size_size_hint = 0_u32.size_hint()?; 296 | let inner_size_hint = self.inner.size_hint()?; 297 | 298 | Ok(size_size_hint + inner_size_hint) 299 | } 300 | } 301 | 302 | #[cfg(feature = "quickcheck")] 303 | impl Arbitrary for WithSize 304 | where T: Arbitrary + MtProtoSized 305 | { 306 | fn arbitrary(g: &mut G) -> WithSize { 307 | WithSize::new(T::arbitrary(g)) 308 | .expect("failed to wrap a generated random value using `WithSize`") 309 | } 310 | 311 | fn shrink(&self) -> Box>> { 312 | Box::new(self.inner.shrink().map(|x| WithSize::new(x) 313 | .expect("failed to wrap a shrinked value using `WithSize`"))) 314 | } 315 | } 316 | 317 | 318 | // ========== UTILS ========== // 319 | 320 | fn check_type_id(type_id: u32) -> error::Result<()> { 321 | let expected_type_ids = T::all_type_ids(); 322 | if expected_type_ids.iter().find(|&id| *id == type_id).is_none() { 323 | bail!(DeErrorKind::InvalidTypeId(type_id, expected_type_ids)); 324 | } 325 | 326 | Ok(()) 327 | } 328 | 329 | 330 | fn next_seq_element<'de, T, A>(seq: &mut A, 331 | deserialized_count: u32, 332 | expected_count: u32) 333 | -> Result 334 | where T: Deserialize<'de>, 335 | A: SeqAccess<'de>, 336 | { 337 | next_seq_element_seed(seq, PhantomData, deserialized_count, expected_count) 338 | } 339 | 340 | fn next_seq_element_seed<'de, S, A>(seq: &mut A, 341 | seed: S, 342 | deserialized_count: u32, 343 | expected_count: u32) 344 | -> Result 345 | where S: DeserializeSeed<'de>, 346 | A: SeqAccess<'de>, 347 | { 348 | seq.next_element_seed(seed)? 349 | .ok_or_else(|| errconv(DeErrorKind::NotEnoughElements(deserialized_count, expected_count))) 350 | } 351 | 352 | 353 | fn next_struct_element<'de, T, A>(map: &mut A, 354 | expected_key: &'static str, 355 | deserialized_count: u32, 356 | expected_count: u32) 357 | -> Result 358 | where T: Deserialize<'de>, 359 | A: MapAccess<'de>, 360 | { 361 | next_struct_element_seed( 362 | map, PhantomData, PhantomData, expected_key, deserialized_count, expected_count) 363 | } 364 | 365 | fn next_struct_element_seed<'de, K, V, A>(map: &mut A, 366 | string_key_seed: K, 367 | value_seed: V, 368 | expected_key: &'static str, 369 | deserialized_count: u32, 370 | expected_count: u32) 371 | -> Result 372 | where K: DeserializeSeed<'de, Value=String>, 373 | V: DeserializeSeed<'de>, 374 | A: MapAccess<'de>, 375 | { 376 | let next_key = map.next_key_seed(string_key_seed)? 377 | .ok_or_else(|| errconv(DeErrorKind::NotEnoughElements(deserialized_count, expected_count)))?; 378 | 379 | // Don't even try to deserialize value if keys don't match 380 | // (the reason behind not using `.next_entry_seed()`) 381 | if next_key != expected_key { 382 | bail!(errconv::(DeErrorKind::InvalidMapKey(next_key, expected_key))); 383 | } 384 | 385 | map.next_value_seed(value_seed) 386 | } 387 | 388 | 389 | fn errconv(kind: DeErrorKind) -> E 390 | where E: DeError 391 | { 392 | E::custom(error::Error::from(kind)) 393 | } 394 | -------------------------------------------------------------------------------- /src/ser.rs: -------------------------------------------------------------------------------- 1 | //! Serialize a Rust data structure into its MTProto binary representation. 2 | 3 | use std::io; 4 | 5 | use byteorder::{WriteBytesExt, LittleEndian}; 6 | use error_chain::bail; 7 | use log::debug; 8 | use serde::ser::{self, Serialize}; 9 | 10 | use crate::error::{self, SerErrorKind, SerSerdeType}; 11 | use crate::identifiable::Identifiable; 12 | use crate::utils::{i128_to_parts, safe_uint_cast, u128_to_parts}; 13 | 14 | 15 | /// A structure for serializing Rust values into MTProto binary representation. 16 | #[derive(Debug)] 17 | pub struct Serializer { 18 | writer: W, 19 | } 20 | 21 | impl Serializer { 22 | /// Create a MTProto serializer from an `io::Write`. 23 | pub fn new(writer: W) -> Serializer { 24 | Serializer { writer } 25 | } 26 | 27 | /// Unwraps the `Serializer` and returns the underlying `io::Write`. 28 | pub fn into_writer(self) -> W { 29 | self.writer 30 | } 31 | 32 | fn impl_serialize_bytes(&mut self, value: &[u8]) -> error::Result<()> { 33 | let len = value.len(); 34 | let rem; 35 | 36 | if len <= 253 { 37 | // If L <= 253, the serialization contains one byte with the value of L, 38 | // then L bytes of the string followed by 0 to 3 characters containing 0, 39 | // such that the overall length of the value be divisible by 4, 40 | // whereupon all of this is interpreted as a sequence 41 | // of int(L/4)+1 32-bit little-endian integers. 42 | 43 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_possible_truncation))] 44 | self.writer.write_u8(len as u8)?; // `as` is safe: [0..253] \subseteq [0..255] 45 | 46 | rem = (len + 1) % 4; 47 | } else if len <= 0xff_ff_ff { 48 | // If L >= 254, the serialization contains byte 254, followed by 3 49 | // bytes with the string length L in little-endian order, followed by L 50 | // bytes of the string, further followed by 0 to 3 null padding bytes. 51 | 52 | self.writer.write_u8(254)?; 53 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_possible_truncation))] 54 | self.writer.write_u24::(len as u32)?; // `as` is safe: [0..0xff_ff_ff] \subseteq [0..0xff_ff_ff_ff] 55 | 56 | rem = len % 4; 57 | } else { 58 | bail!(SerErrorKind::StringTooLong(len)); 59 | } 60 | 61 | // Write each character in the string 62 | self.writer.write_all(value)?; 63 | 64 | // [...] string followed by 0 to 3 characters containing 0, 65 | // such that the overall length of the value be divisible by 4 [...] 66 | if rem > 0 { 67 | assert!(rem < 4); 68 | let padding = 4 - rem; 69 | self.writer.write_uint::(0, padding)?; 70 | } 71 | 72 | Ok(()) 73 | } 74 | } 75 | 76 | 77 | macro_rules! impl_serialize_small_int { 78 | ($small_type:ty, $small_method:ident, $big_type:ident, $big_method:ident) => { 79 | fn $small_method(self, value: $small_type) -> error::Result<()> { 80 | self.$big_method($big_type::from(value))?; 81 | debug!("Serialized {} as {}: {:#x}", stringify!($small_type), stringify!($big_type), value); 82 | Ok(()) 83 | } 84 | } 85 | } 86 | 87 | macro_rules! impl_serialize_big_int { 88 | ($type:ty, $method:ident, $write:path) => { 89 | fn $method(self, value: $type) -> error::Result<()> { 90 | $write(&mut self.writer, value)?; 91 | debug!("Serialized {}: {:#x}", stringify!($type), value); 92 | Ok(()) 93 | } 94 | }; 95 | } 96 | 97 | impl<'a, W> ser::Serializer for &'a mut Serializer 98 | where W: io::Write 99 | { 100 | type Ok = (); 101 | type Error = error::Error; 102 | 103 | type SerializeSeq = SerializeFixedLengthSeq<'a, W>; 104 | type SerializeTuple = SerializeFixedLengthSeq<'a, W>; 105 | type SerializeTupleStruct = SerializeFixedLengthSeq<'a, W>; 106 | type SerializeTupleVariant = SerializeFixedLengthSeq<'a, W>; 107 | type SerializeMap = SerializeFixedLengthMap<'a, W>; 108 | type SerializeStruct = SerializeFixedLengthSeq<'a, W>; 109 | type SerializeStructVariant = SerializeFixedLengthSeq<'a, W>; 110 | 111 | 112 | fn serialize_bool(self, value: bool) -> error::Result<()> { 113 | self.writer.write_u32::(value.type_id())?; 114 | debug!("Serialized bool: {} => {:#x}", value, value.type_id()); 115 | Ok(()) 116 | } 117 | 118 | impl_serialize_small_int!(i8, serialize_i8, i32, serialize_i32); 119 | impl_serialize_small_int!(i16, serialize_i16, i32, serialize_i32); 120 | impl_serialize_big_int!(i32, serialize_i32, WriteBytesExt::write_i32); 121 | impl_serialize_big_int!(i64, serialize_i64, WriteBytesExt::write_i64); 122 | 123 | fn serialize_i128(self, value: i128) -> error::Result<()> { 124 | let (hi, lo) = i128_to_parts(value); 125 | WriteBytesExt::write_u64::(&mut self.writer, lo)?; 126 | WriteBytesExt::write_i64::(&mut self.writer, hi)?; 127 | debug!("Serialized i128: {:#x}", value); 128 | Ok(()) 129 | } 130 | 131 | impl_serialize_small_int!(u8, serialize_u8, u32, serialize_u32); 132 | impl_serialize_small_int!(u16, serialize_u16, u32, serialize_u32); 133 | impl_serialize_big_int!(u32, serialize_u32, WriteBytesExt::write_u32); 134 | impl_serialize_big_int!(u64, serialize_u64, WriteBytesExt::write_u64); 135 | 136 | fn serialize_u128(self, value: u128) -> error::Result<()> { 137 | let (hi, lo) = u128_to_parts(value); 138 | WriteBytesExt::write_u64::(&mut self.writer, lo)?; 139 | WriteBytesExt::write_u64::(&mut self.writer, hi)?; 140 | debug!("Serialized u128: {:#x}", value); 141 | Ok(()) 142 | } 143 | 144 | fn serialize_f32(self, value: f32) -> error::Result<()> { 145 | // There is only one floating-point type, and it's double precision 146 | WriteBytesExt::write_f64::(&mut self.writer, f64::from(value))?; 147 | debug!("Serialized f32 as f64: {}", value); 148 | Ok(()) 149 | } 150 | 151 | fn serialize_f64(self, value: f64) -> error::Result<()> { 152 | WriteBytesExt::write_f64::(&mut self.writer, value)?; 153 | debug!("Serialized f64: {}", value); 154 | Ok(()) 155 | } 156 | 157 | fn serialize_char(self, _value: char) -> error::Result<()> { 158 | bail!(SerErrorKind::UnsupportedSerdeType(SerSerdeType::Char)); 159 | } 160 | 161 | fn serialize_str(self, value: &str) -> error::Result<()> { 162 | self.impl_serialize_bytes(value.as_bytes())?; 163 | debug!("Serialized str: {:?}", value); 164 | Ok(()) 165 | } 166 | 167 | fn serialize_bytes(self, value: &[u8]) -> error::Result<()> { 168 | self.impl_serialize_bytes(value)?; 169 | debug!("Serialized bytes: {:?}", value); 170 | Ok(()) 171 | } 172 | 173 | fn serialize_none(self) -> error::Result<()> { 174 | bail!(SerErrorKind::UnsupportedSerdeType(SerSerdeType::None)); 175 | } 176 | 177 | fn serialize_some(self, _value: &T) -> error::Result<()> 178 | where T: ?Sized + Serialize 179 | { 180 | bail!(SerErrorKind::UnsupportedSerdeType(SerSerdeType::Some)); 181 | } 182 | 183 | fn serialize_unit(self) -> error::Result<()> { 184 | bail!(SerErrorKind::UnsupportedSerdeType(SerSerdeType::Unit)); 185 | } 186 | 187 | fn serialize_unit_struct(self, _name: &'static str) -> error::Result<()> { 188 | debug!("Serialized unit struct"); 189 | Ok(()) 190 | } 191 | 192 | fn serialize_unit_variant(self, 193 | _name: &'static str, 194 | _variant_index: u32, 195 | _variant: &'static str) 196 | -> error::Result<()> { 197 | debug!("Serialized unit variant"); 198 | Ok(()) 199 | } 200 | 201 | fn serialize_newtype_struct(self, name: &'static str, value: &T) -> error::Result<()> 202 | where T: ?Sized + Serialize 203 | { 204 | debug!("Serializing newtype variant {}", name); 205 | value.serialize(self) 206 | } 207 | 208 | fn serialize_newtype_variant(self, 209 | name: &'static str, 210 | variant_index: u32, 211 | variant: &'static str, 212 | value: &T) 213 | -> error::Result<()> 214 | where T: ?Sized + Serialize 215 | { 216 | debug!("Serializing newtype variant {}::{} (variant index {})", name, variant, variant_index); 217 | value.serialize(self) 218 | } 219 | 220 | fn serialize_seq(self, len: Option) -> error::Result { 221 | if let Some(len) = len { 222 | debug!("Serializing seq of len {}", len); 223 | SerializeFixedLengthSeq::with_serialize_len(self, safe_uint_cast(len)?) 224 | } else { 225 | bail!(SerErrorKind::SeqsWithUnknownLengthUnsupported); 226 | } 227 | } 228 | 229 | fn serialize_tuple(self, len: usize) -> error::Result { 230 | debug!("Serializing tuple of len {}", len); 231 | Ok(SerializeFixedLengthSeq::new(self, safe_uint_cast(len)?)) 232 | } 233 | 234 | fn serialize_tuple_struct(self, 235 | name: &'static str, 236 | len: usize) 237 | -> error::Result { 238 | debug!("Serializing tuple struct {} of len {}", name, len); 239 | Ok(SerializeFixedLengthSeq::new(self, safe_uint_cast(len)?)) 240 | } 241 | 242 | fn serialize_tuple_variant(self, 243 | name: &'static str, 244 | variant_index: u32, 245 | variant: &'static str, 246 | len: usize) 247 | -> error::Result { 248 | debug!("Serializing tuple variant {}::{} (variant index {}) of len {}", 249 | name, variant, variant_index, len); 250 | Ok(SerializeFixedLengthSeq::new(self, safe_uint_cast(len)?)) 251 | } 252 | 253 | fn serialize_map(self, len: Option) -> error::Result { 254 | if let Some(len) = len { 255 | debug!("Serializing map of len {}", len); 256 | SerializeFixedLengthMap::with_serialize_len(self, safe_uint_cast(len)?) 257 | } else { 258 | bail!(SerErrorKind::MapsWithUnknownLengthUnsupported); 259 | } 260 | } 261 | 262 | fn serialize_struct(self, name: &'static str, len: usize) -> error::Result { 263 | debug!("Serializing struct {} of len {}", name, len); 264 | Ok(SerializeFixedLengthSeq::new(self, safe_uint_cast(len)?)) 265 | } 266 | 267 | fn serialize_struct_variant(self, 268 | name: &'static str, 269 | variant_index: u32, 270 | variant: &'static str, 271 | len: usize) 272 | -> error::Result { 273 | debug!("Serializing struct variant {}::{} (variant index {}) of len {}", 274 | name, variant, variant_index, len); 275 | Ok(SerializeFixedLengthSeq::new(self, safe_uint_cast(len)?)) 276 | } 277 | } 278 | 279 | 280 | /// Helper structure for serializing fixed-length sequences. 281 | #[derive(Debug)] 282 | pub struct SerializeFixedLengthSeq<'a, W: io::Write> { 283 | ser: &'a mut Serializer, 284 | len: u32, 285 | next_index: u32, 286 | } 287 | 288 | impl<'a, W: io::Write> SerializeFixedLengthSeq<'a, W> { 289 | fn new(ser: &'a mut Serializer, len: u32) -> SerializeFixedLengthSeq<'a, W> { 290 | SerializeFixedLengthSeq { ser, len, next_index: 0 } 291 | } 292 | 293 | fn with_serialize_len(ser: &'a mut Serializer, len: u32) -> error::Result> { 294 | ser::Serializer::serialize_u32(&mut *ser, len)?; 295 | 296 | Ok(SerializeFixedLengthSeq::new(ser, len)) 297 | } 298 | 299 | fn impl_serialize_seq_value(&mut self, 300 | key: Option<&'static str>, 301 | value: &T, 302 | serializer_type: &'static str) 303 | -> error::Result<()> 304 | where T: ?Sized + Serialize 305 | { 306 | if self.next_index < self.len { 307 | self.next_index += 1; 308 | } else { 309 | debug!("{}::serialize_element() is called when no elements is left to serialize", 310 | serializer_type); 311 | 312 | bail!(SerErrorKind::ExcessElements(self.len)); 313 | } 314 | 315 | if let Some(key) = key { 316 | debug!("Serializing field {}", key); 317 | } else { 318 | debug!("Serializing element"); 319 | } 320 | 321 | value.serialize(&mut *self.ser) 322 | } 323 | 324 | fn impl_serialize_end(self, data_type: &'static str) -> error::Result<()> { 325 | if self.next_index < self.len { 326 | bail!(SerErrorKind::NotEnoughElements(self.next_index, self.len)) 327 | } 328 | 329 | // `self.index > self.len` here is a programming error 330 | assert_eq!(self.next_index, self.len); 331 | 332 | debug!("Finished serializing {}", data_type); 333 | 334 | Ok(()) 335 | } 336 | } 337 | 338 | impl<'a, W> ser::SerializeSeq for SerializeFixedLengthSeq<'a, W> 339 | where W: 'a + io::Write 340 | { 341 | type Ok = (); 342 | type Error = error::Error; 343 | 344 | fn serialize_element(&mut self, value: &T) -> error::Result<()> 345 | where T: ?Sized + Serialize 346 | { 347 | self.impl_serialize_seq_value(None, value, "SerializeSeq") 348 | } 349 | 350 | fn end(self) -> error::Result<()> { 351 | self.impl_serialize_end("seq") 352 | } 353 | } 354 | 355 | impl<'a, W> ser::SerializeTuple for SerializeFixedLengthSeq<'a, W> 356 | where W: 'a + io::Write 357 | { 358 | type Ok = (); 359 | type Error = error::Error; 360 | 361 | fn serialize_element(&mut self, value: &T) -> error::Result<()> 362 | where T: ?Sized + Serialize 363 | { 364 | self.impl_serialize_seq_value(None, value, "SerializeTuple") 365 | } 366 | 367 | fn end(self) -> error::Result<()> { 368 | self.impl_serialize_end("tuple") 369 | } 370 | } 371 | 372 | impl<'a, W> ser::SerializeTupleStruct for SerializeFixedLengthSeq<'a, W> 373 | where W: io::Write 374 | { 375 | type Ok = (); 376 | type Error = error::Error; 377 | 378 | fn serialize_field(&mut self, value: &T) -> error::Result<()> 379 | where T: ?Sized + Serialize 380 | { 381 | self.impl_serialize_seq_value(None, value, "SerializeTupleStruct") 382 | } 383 | 384 | fn end(self) -> error::Result<()> { 385 | self.impl_serialize_end("tuple struct") 386 | } 387 | } 388 | 389 | impl<'a, W> ser::SerializeTupleVariant for SerializeFixedLengthSeq<'a, W> 390 | where W: io::Write 391 | { 392 | type Ok = (); 393 | type Error = error::Error; 394 | 395 | fn serialize_field(&mut self, value: &T) -> error::Result<()> 396 | where T: ?Sized + Serialize 397 | { 398 | self.impl_serialize_seq_value(None, value, "SerializeTupleVariant") 399 | } 400 | 401 | fn end(self) -> error::Result<()> { 402 | self.impl_serialize_end("tuple variant") 403 | } 404 | } 405 | 406 | impl<'a, W> ser::SerializeStruct for SerializeFixedLengthSeq<'a, W> 407 | where W: io::Write 408 | { 409 | type Ok = (); 410 | type Error = error::Error; 411 | 412 | fn serialize_field(&mut self, key: &'static str, value: &T) -> error::Result<()> 413 | where T: ?Sized + Serialize 414 | { 415 | self.impl_serialize_seq_value(Some(key), value, "SerializeStruct") 416 | } 417 | 418 | fn end(self) -> error::Result<()> { 419 | self.impl_serialize_end("struct") 420 | } 421 | } 422 | 423 | impl<'a, W> ser::SerializeStructVariant for SerializeFixedLengthSeq<'a, W> 424 | where W: io::Write 425 | { 426 | type Ok = (); 427 | type Error = error::Error; 428 | 429 | fn serialize_field(&mut self, key: &'static str, value: &T) -> error::Result<()> 430 | where T: ?Sized + Serialize 431 | { 432 | self.impl_serialize_seq_value(Some(key), value, "SerializeStructVariant") 433 | } 434 | 435 | fn end(self) -> error::Result<()> { 436 | self.impl_serialize_end("struct variant") 437 | } 438 | } 439 | 440 | 441 | /// Helper structure for serializing maps. 442 | #[derive(Debug)] 443 | pub struct SerializeFixedLengthMap<'a, W: io::Write> { 444 | ser: &'a mut Serializer, 445 | len: u32, 446 | next_index: u32, 447 | } 448 | 449 | impl<'a, W: io::Write> SerializeFixedLengthMap<'a, W> { 450 | fn with_serialize_len(ser: &'a mut Serializer, 451 | len: u32) 452 | -> error::Result> { 453 | ser::Serializer::serialize_u32(&mut *ser, len)?; 454 | 455 | Ok(SerializeFixedLengthMap { ser, len, next_index: 0 }) 456 | } 457 | } 458 | 459 | impl<'a, W> ser::SerializeMap for SerializeFixedLengthMap<'a, W> 460 | where W: io::Write 461 | { 462 | type Ok = (); 463 | type Error = error::Error; 464 | 465 | fn serialize_key(&mut self, key: &T) -> error::Result<()> 466 | where T: ?Sized + Serialize 467 | { 468 | if self.next_index < self.len { 469 | self.next_index += 1; 470 | } else { 471 | debug!("SerializeMap::serialize_key() is called when no elements is left to serialize"); 472 | 473 | bail!(SerErrorKind::ExcessElements(self.len)); 474 | } 475 | 476 | debug!("Serializing key"); 477 | key.serialize(&mut *self.ser) 478 | } 479 | 480 | fn serialize_value(&mut self, value: &T) -> error::Result<()> 481 | where T: ?Sized + Serialize 482 | { 483 | debug!("Serializing value"); 484 | value.serialize(&mut *self.ser) 485 | } 486 | 487 | fn end(self) -> error::Result<()> { 488 | debug!("Finished serializing map"); 489 | Ok(()) 490 | } 491 | } 492 | 493 | 494 | /// Serialize the given data structure as a byte vector of binary MTProto. 495 | pub fn to_bytes(value: &T) -> error::Result> 496 | where T: Serialize 497 | { 498 | let mut ser = Serializer::new(Vec::new()); 499 | value.serialize(&mut ser)?; 500 | 501 | Ok(ser.writer) 502 | } 503 | 504 | /// Serialize bytes with padding to 16 bytes as a byte vector of binary MTProto. 505 | pub fn unsized_bytes_pad_to_bytes(value: &[u8]) -> error::Result> { 506 | let padding = (16 - value.len() % 16) % 16; 507 | let mut result = Vec::with_capacity(value.len() + padding); 508 | 509 | result.extend(value); 510 | for _ in 0..padding { 511 | result.push(0); 512 | } 513 | 514 | Ok(result) 515 | } 516 | 517 | /// Serialize the given data structure as binary MTProto into the IO stream. 518 | pub fn to_writer(writer: W, value: &T) -> error::Result<()> 519 | where W: io::Write, 520 | T: Serialize, 521 | { 522 | let mut ser = Serializer::new(writer); 523 | value.serialize(&mut ser)?; 524 | 525 | Ok(()) 526 | } 527 | 528 | /// Serialize bytes with padding to 16 bytes into the IO stream. 529 | pub fn unsized_bytes_pad_to_writer(mut writer: W, value: &[u8]) -> error::Result<()> 530 | where W: io::Write 531 | { 532 | let padding = (16 - value.len() % 16) % 16; 533 | 534 | writer.write_all(value)?; 535 | for _ in 0..padding { 536 | writer.write_u8(0)?; 537 | } 538 | 539 | Ok(()) 540 | } 541 | -------------------------------------------------------------------------------- /src/de.rs: -------------------------------------------------------------------------------- 1 | //! Deserialize MTProto binary representation to a Rust data structure. 2 | 3 | use std::io; 4 | 5 | use byteorder::{ReadBytesExt, LittleEndian}; 6 | use error_chain::bail; 7 | use log::debug; 8 | use serde::de::{self, Deserialize, DeserializeOwned, DeserializeSeed, Visitor}; 9 | 10 | use crate::error::{self, DeErrorKind, DeSerdeType}; 11 | use crate::identifiable::{BOOL_FALSE_ID, BOOL_TRUE_ID}; 12 | use crate::utils::{i128_from_parts, safe_float_cast, safe_int_cast, safe_uint_cast, u128_from_parts}; 13 | 14 | 15 | /// A structure that deserializes MTProto binary representation into Rust values. 16 | #[derive(Debug)] 17 | pub struct Deserializer<'ids, R: io::Read> { 18 | reader: R, 19 | enum_variant_ids: &'ids [&'static str], 20 | } 21 | 22 | impl<'ids, R: io::Read> Deserializer<'ids, R> { 23 | /// Create a MTProto deserializer from an `io::Read` and enum variant hint. 24 | pub fn new(reader: R, enum_variant_ids: &'ids [&'static str]) -> Deserializer<'ids, R> { 25 | Deserializer { reader, enum_variant_ids } 26 | } 27 | 28 | /// Unwraps the `Deserializer` and returns the underlying `io::Read`. 29 | pub fn into_reader(self) -> R { 30 | self.reader 31 | } 32 | 33 | /// Consumes the `Deserializer` and returns remaining unprocessed bytes. 34 | pub fn remaining_bytes(mut self) -> error::Result> { 35 | let mut buf = Vec::new(); 36 | let bytes_read = self.reader.read_to_end(&mut buf)?; 37 | 38 | debug!("Remaining bytes read of length {}: {:?}", bytes_read, buf); 39 | 40 | Ok(buf) 41 | } 42 | 43 | fn get_str_info(&mut self) -> error::Result<(usize, usize)> { 44 | let first_byte = self.reader.read_u8()?; 45 | let len; 46 | let rem; 47 | 48 | match first_byte { 49 | 0 ..= 253 => { 50 | len = usize::from(first_byte); 51 | rem = (len + 1) % 4; 52 | }, 53 | 254 => { 54 | let uncasted = self.reader.read_u24::()?; 55 | if uncasted <= 253 { 56 | bail!(DeErrorKind::BytesLenPrefix254LessThan254(uncasted)); 57 | } 58 | 59 | len = safe_uint_cast::(uncasted)?; 60 | rem = len % 4; 61 | }, 62 | 255 => { 63 | return Err(de::Error::invalid_value( 64 | de::Unexpected::Unsigned(255), 65 | &"a byte in [0..254] range")); 66 | }, 67 | #[cfg(not(stable_exhaustive_integer_patterns))] 68 | _ => unreachable!("other match arms should have exhaustively covered every value"), 69 | } 70 | 71 | let padding = (4 - rem) % 4; 72 | 73 | Ok((len, padding)) 74 | } 75 | 76 | fn read_string(&mut self) -> error::Result { 77 | let s_bytes = self.read_byte_buf()?; 78 | let s = String::from_utf8(s_bytes)?; 79 | 80 | Ok(s) 81 | } 82 | 83 | fn read_byte_buf(&mut self) -> error::Result> { 84 | let (len, padding) = self.get_str_info()?; 85 | 86 | let mut b = vec![0; len]; 87 | self.reader.read_exact(&mut b)?; 88 | 89 | let mut p = [0; 3]; 90 | let ps = p.get_mut(0..padding) 91 | .unwrap_or_else(|| unreachable!("padding must be of length 3 or less")); 92 | self.reader.read_exact(ps)?; 93 | 94 | if ps.iter().any(|b| *b != 0) { 95 | bail!(DeErrorKind::NonZeroBytesPadding); 96 | } 97 | 98 | Ok(b) 99 | } 100 | } 101 | 102 | impl<'ids, 'a> Deserializer<'ids, &'a [u8]> { 103 | /// Length of unprocessed data in the byte buffer. 104 | pub fn remaining_length(&self) -> usize { 105 | self.reader.len() 106 | } 107 | } 108 | 109 | 110 | macro_rules! impl_deserialize_small_int { 111 | ($small_type:ty, $small_deserialize:ident, $cast:ident, 112 | $big_read:ident::<$big_endianness:ident>, $small_visit:ident 113 | ) => { 114 | fn $small_deserialize(self, visitor: V) -> error::Result 115 | where V: Visitor<'de> 116 | { 117 | let value = self.reader.$big_read::<$big_endianness>()?; 118 | debug!("Deserialized big int: {:#x}", value); 119 | let casted = $cast(value)?; 120 | debug!("Casted to {}: {:#x}", stringify!($small_type), casted); 121 | 122 | visitor.$small_visit(casted) 123 | } 124 | }; 125 | } 126 | 127 | macro_rules! impl_deserialize_big_int { 128 | ($type:ty, $deserialize:ident, $read:ident::<$endianness:ident>, $visit:ident) => { 129 | fn $deserialize(self, visitor: V) -> error::Result 130 | where V: Visitor<'de> 131 | { 132 | let value = self.reader.$read::<$endianness>()?; 133 | debug!("Deserialized {}: {:#x}", stringify!($type), value); 134 | 135 | visitor.$visit(value) 136 | } 137 | }; 138 | } 139 | 140 | impl<'de, 'a, 'ids, R> de::Deserializer<'de> for &'a mut Deserializer<'ids, R> 141 | where R: io::Read 142 | { 143 | type Error = error::Error; 144 | 145 | fn deserialize_any(self, _visitor: V) -> error::Result 146 | where V: Visitor<'de> 147 | { 148 | bail!(DeErrorKind::UnsupportedSerdeType(DeSerdeType::Any)); 149 | } 150 | 151 | fn deserialize_bool(self, visitor: V) -> error::Result 152 | where V: Visitor<'de> 153 | { 154 | let id_value = self.reader.read_u32::()?; 155 | 156 | let value = match id_value { 157 | BOOL_FALSE_ID => false, 158 | BOOL_TRUE_ID => true, 159 | _ => { 160 | return Err(de::Error::invalid_value( 161 | de::Unexpected::Signed(i64::from(id_value)), 162 | &format!("either {} for false or {} for true", BOOL_FALSE_ID, BOOL_TRUE_ID).as_str())); 163 | } 164 | }; 165 | 166 | debug!("Deserialized bool: {}", value); 167 | 168 | visitor.visit_bool(value) 169 | } 170 | 171 | impl_deserialize_small_int!(i8, deserialize_i8, safe_int_cast, read_i32::, visit_i8); 172 | impl_deserialize_small_int!(i16, deserialize_i16, safe_int_cast, read_i32::, visit_i16); 173 | impl_deserialize_big_int!(i32, deserialize_i32, read_i32::, visit_i32); 174 | impl_deserialize_big_int!(i64, deserialize_i64, read_i64::, visit_i64); 175 | 176 | fn deserialize_i128(self, visitor: V) -> error::Result 177 | where V: Visitor<'de> 178 | { 179 | let lo = self.reader.read_u64::()?; 180 | let hi = self.reader.read_i64::()?; 181 | let value = i128_from_parts(hi, lo); 182 | debug!("Deserialized i128: {:#x}", value); 183 | 184 | visitor.visit_i128(value) 185 | } 186 | 187 | impl_deserialize_small_int!(u8, deserialize_u8, safe_uint_cast, read_u32::, visit_u8); 188 | impl_deserialize_small_int!(u16, deserialize_u16, safe_uint_cast, read_u32::, visit_u16); 189 | impl_deserialize_big_int!(u32, deserialize_u32, read_u32::, visit_u32); 190 | impl_deserialize_big_int!(u64, deserialize_u64, read_u64::, visit_u64); 191 | 192 | fn deserialize_u128(self, visitor: V) -> error::Result 193 | where V: Visitor<'de> 194 | { 195 | let lo = self.reader.read_u64::()?; 196 | let hi = self.reader.read_u64::()?; 197 | let value = u128_from_parts(hi, lo); 198 | debug!("Deserialized u128: {:#x}", value); 199 | 200 | visitor.visit_u128(value) 201 | } 202 | 203 | fn deserialize_f32(self, visitor: V) -> error::Result 204 | where V: Visitor<'de> 205 | { 206 | let value = self.reader.read_f64::()?; 207 | debug!("Deserialized big float: {}", value); 208 | 209 | let casted = safe_float_cast(value)?; 210 | debug!("Casted to f32: {}", casted); 211 | 212 | visitor.visit_f32(casted) 213 | } 214 | 215 | fn deserialize_f64(self, visitor: V) -> error::Result 216 | where V: Visitor<'de> 217 | { 218 | let value = self.reader.read_f64::()?; 219 | debug!("Deserialized f64: {}", value); 220 | 221 | visitor.visit_f64(value) 222 | } 223 | 224 | fn deserialize_char(self, _visitor: V) -> error::Result 225 | where V: Visitor<'de> 226 | { 227 | bail!(DeErrorKind::UnsupportedSerdeType(DeSerdeType::Char)); 228 | } 229 | 230 | fn deserialize_str(self, visitor: V) -> error::Result 231 | where V: Visitor<'de> 232 | { 233 | let s = self.read_string()?; 234 | debug!("Deserialized str: {:?}", s); 235 | visitor.visit_str(&s) 236 | } 237 | 238 | fn deserialize_string(self, visitor: V) -> error::Result 239 | where V: Visitor<'de> 240 | { 241 | let s = self.read_string()?; 242 | debug!("Deserialized string: {:?}", s); 243 | visitor.visit_string(s) 244 | } 245 | 246 | fn deserialize_bytes(self, visitor: V) -> error::Result 247 | where V: Visitor<'de> 248 | { 249 | let b = self.read_byte_buf()?; 250 | debug!("Deserialized bytes: {:?}", b); 251 | visitor.visit_bytes(&b) 252 | } 253 | 254 | fn deserialize_byte_buf(self, visitor: V) -> error::Result 255 | where V: Visitor<'de> 256 | { 257 | let b = self.read_byte_buf()?; 258 | debug!("Deserialized byte buffer: {:?}", b); 259 | visitor.visit_byte_buf(b) 260 | } 261 | 262 | fn deserialize_option(self, _visitor: V) -> error::Result 263 | where V: Visitor<'de> 264 | { 265 | bail!(DeErrorKind::UnsupportedSerdeType(DeSerdeType::Option)); 266 | } 267 | 268 | fn deserialize_unit(self, _visitor: V) -> error::Result 269 | where V: Visitor<'de> 270 | { 271 | bail!(DeErrorKind::UnsupportedSerdeType(DeSerdeType::Unit)); 272 | } 273 | 274 | fn deserialize_unit_struct(self, name: &'static str, visitor: V) -> error::Result 275 | where V: Visitor<'de> 276 | { 277 | debug!("Deserialized unit struct {}", name); 278 | visitor.visit_unit() 279 | } 280 | 281 | fn deserialize_newtype_struct(self, name: &'static str, visitor: V) -> error::Result 282 | where V: Visitor<'de> 283 | { 284 | debug!("Deserializing newtype struct {}", name); 285 | visitor.visit_newtype_struct(self) 286 | } 287 | 288 | fn deserialize_seq(self, visitor: V) -> error::Result 289 | where V: Visitor<'de> 290 | { 291 | let len = self.reader.read_u32::()?; 292 | debug!("Deserializing seq of len {}", len); 293 | 294 | visitor.visit_seq(SeqAccess::new(self, len)) 295 | } 296 | 297 | fn deserialize_tuple(self, len: usize, visitor: V) -> error::Result 298 | where V: Visitor<'de> 299 | { 300 | debug!("Deserializing tuple of len {}", len); 301 | visitor.visit_seq(SeqAccess::new(self, safe_uint_cast(len)?)) 302 | } 303 | 304 | fn deserialize_tuple_struct(self, name: &'static str, len: usize, visitor: V) -> error::Result 305 | where V: Visitor<'de> 306 | { 307 | debug!("Deserializing tuple struct {} of len {}", name, len); 308 | visitor.visit_seq(SeqAccess::new(self, safe_uint_cast(len)?)) 309 | } 310 | 311 | fn deserialize_map(self, visitor: V) -> error::Result 312 | where V: Visitor<'de> 313 | { 314 | let len = self.reader.read_u32::()?; 315 | debug!("Deserializing map of len {}", len); 316 | 317 | visitor.visit_map(MapAccess::new(self, len)) 318 | } 319 | 320 | fn deserialize_struct(self, name: &'static str, fields: &'static [&'static str], visitor: V) -> error::Result 321 | where V: Visitor<'de> 322 | { 323 | debug!("Deserializing struct {} with fields {:?}", name, fields); 324 | visitor.visit_seq(SeqAccess::new(self, safe_uint_cast(fields.len())?)) 325 | } 326 | 327 | fn deserialize_enum(self, name: &'static str, variants: &'static [&'static str], visitor: V) -> error::Result 328 | where V: Visitor<'de> 329 | { 330 | debug!("Deserializing enum {} with variants {:?}", name, variants); 331 | visitor.visit_enum(EnumVariantAccess::new(self)) 332 | } 333 | 334 | fn deserialize_identifier(self, visitor: V) -> error::Result 335 | where V: Visitor<'de> 336 | { 337 | debug!("Deserializing identifier"); 338 | let (variant_id, rest) = self.enum_variant_ids.split_first() 339 | .ok_or_else(|| error::Error::from(DeErrorKind::NoEnumVariantId))?; 340 | 341 | debug!("Deserialized variant_id {}", variant_id); 342 | self.enum_variant_ids = rest; 343 | 344 | visitor.visit_str(variant_id) 345 | } 346 | 347 | fn deserialize_ignored_any(self, _visitor: V) -> error::Result 348 | where V: Visitor<'de> 349 | { 350 | bail!(DeErrorKind::UnsupportedSerdeType(DeSerdeType::IgnoredAny)); 351 | } 352 | } 353 | 354 | 355 | #[derive(Debug)] 356 | struct SeqAccess<'a, 'ids: 'a, R: io::Read> { 357 | de: &'a mut Deserializer<'ids, R>, 358 | len: u32, 359 | next_index: u32, 360 | } 361 | 362 | impl<'a, 'ids, R: io::Read> SeqAccess<'a, 'ids, R> { 363 | fn new(de: &'a mut Deserializer<'ids, R>, len: u32) -> SeqAccess<'a, 'ids, R> { 364 | SeqAccess { de, len, next_index: 0 } 365 | } 366 | } 367 | 368 | impl<'de, 'a, 'ids, R> de::SeqAccess<'de> for SeqAccess<'a, 'ids, R> 369 | where R: 'a + io::Read 370 | { 371 | type Error = error::Error; 372 | 373 | fn next_element_seed(&mut self, seed: T) -> error::Result> 374 | where T: DeserializeSeed<'de> 375 | { 376 | if self.next_index < self.len { 377 | self.next_index += 1; 378 | } else { 379 | debug!("SeqAccess::next_element_seed() is called when no elements is left to deserialize"); 380 | return Ok(None); 381 | } 382 | 383 | debug!("Deserializing sequence element"); 384 | seed.deserialize(&mut *self.de).map(Some) 385 | } 386 | 387 | fn size_hint(&self) -> Option { 388 | safe_uint_cast(self.len - self.next_index).ok() 389 | } 390 | } 391 | 392 | 393 | #[derive(Debug)] 394 | struct MapAccess<'a, 'ids: 'a, R: io::Read> { 395 | de: &'a mut Deserializer<'ids, R>, 396 | len: u32, 397 | next_index: u32, 398 | } 399 | 400 | impl<'a, 'ids, R: io::Read> MapAccess<'a, 'ids, R> { 401 | fn new(de: &'a mut Deserializer<'ids, R>, len: u32) -> MapAccess<'a, 'ids, R> { 402 | MapAccess { de, len, next_index: 0 } 403 | } 404 | } 405 | 406 | impl<'de, 'a, 'ids, R> de::MapAccess<'de> for MapAccess<'a, 'ids, R> 407 | where R: 'a + io::Read 408 | { 409 | type Error = error::Error; 410 | 411 | fn next_key_seed(&mut self, seed: K) -> error::Result> 412 | where K: DeserializeSeed<'de> 413 | { 414 | if self.next_index < self.len { 415 | self.next_index += 1; 416 | } else { 417 | debug!("MapAccess::next_key_seed() is called when no elements is left to deserialize"); 418 | return Ok(None); 419 | } 420 | 421 | debug!("Deserializing map key"); 422 | seed.deserialize(&mut *self.de).map(Some) 423 | } 424 | 425 | fn next_value_seed(&mut self, seed: V) -> error::Result 426 | where V: DeserializeSeed<'de> 427 | { 428 | debug!("Deserializing map value"); 429 | seed.deserialize(&mut *self.de) 430 | } 431 | 432 | fn size_hint(&self) -> Option { 433 | safe_uint_cast(self.len - self.next_index).ok() 434 | } 435 | } 436 | 437 | 438 | #[derive(Debug)] 439 | struct EnumVariantAccess<'a, 'ids: 'a, R: io::Read> { 440 | de: &'a mut Deserializer<'ids, R>, 441 | } 442 | 443 | impl<'a, 'ids, R: io::Read> EnumVariantAccess<'a, 'ids, R> { 444 | fn new(de: &'a mut Deserializer<'ids, R>) -> EnumVariantAccess<'a, 'ids, R> { 445 | EnumVariantAccess { de } 446 | } 447 | } 448 | 449 | impl<'de, 'a, 'ids, R> de::EnumAccess<'de> for EnumVariantAccess<'a, 'ids, R> 450 | where R: 'a + io::Read 451 | { 452 | type Error = error::Error; 453 | type Variant = Self; 454 | 455 | fn variant_seed(self, seed: V) -> error::Result<(V::Value, Self::Variant)> 456 | where V: DeserializeSeed<'de> 457 | { 458 | debug!("Deserializing enum variant"); 459 | let value = seed.deserialize(&mut *self.de)?; 460 | 461 | Ok((value, self)) 462 | } 463 | } 464 | 465 | impl<'de, 'a, 'ids, R> de::VariantAccess<'de> for EnumVariantAccess<'a, 'ids, R> 466 | where R: 'a + io::Read 467 | { 468 | type Error = error::Error; 469 | 470 | fn unit_variant(self) -> error::Result<()> { 471 | debug!("Deserialized unit variant"); 472 | Ok(()) 473 | } 474 | 475 | fn newtype_variant_seed(self, seed: T) -> error::Result 476 | where T: DeserializeSeed<'de> 477 | { 478 | debug!("Deserializing newtype variant"); 479 | seed.deserialize(self.de) 480 | } 481 | 482 | fn tuple_variant(self, len: usize, visitor: V) -> error::Result 483 | where V: Visitor<'de> 484 | { 485 | debug!("Deserializing tuple variant"); 486 | de::Deserializer::deserialize_tuple_struct(self.de, "", len, visitor) 487 | } 488 | 489 | fn struct_variant(self, fields: &'static [&'static str], visitor: V) -> error::Result 490 | where V: Visitor<'de> 491 | { 492 | debug!("Deserializing struct variant"); 493 | de::Deserializer::deserialize_struct(self.de, "", fields, visitor) 494 | } 495 | } 496 | 497 | 498 | /// Deserialize an instance of type `T` from bytes of binary MTProto. 499 | pub fn from_bytes<'de, T>(bytes: &'de [u8], enum_variant_ids: &[&'static str]) -> error::Result 500 | where T: Deserialize<'de> 501 | { 502 | let mut de = Deserializer::new(bytes, enum_variant_ids); 503 | let value: T = Deserialize::deserialize(&mut de)?; 504 | 505 | Ok(value) 506 | } 507 | 508 | /// Deserialize an instance of type `T` from bytes of binary MTProto and return unused bytes. 509 | pub fn from_bytes_reuse<'de, T>(bytes: &'de [u8], 510 | enum_variant_ids: &[&'static str]) 511 | -> error::Result<(T, &'de [u8])> 512 | where T: Deserialize<'de> 513 | { 514 | let mut de = Deserializer::new(bytes, enum_variant_ids); 515 | let value: T = Deserialize::deserialize(&mut de)?; 516 | 517 | Ok((value, de.reader)) 518 | } 519 | 520 | /// Deserialize an instance of type `T` from bytes of binary MTProto using a seed. 521 | pub fn from_bytes_seed<'de, S, T>( 522 | seed: S, 523 | bytes: &'de [u8], 524 | enum_variant_ids: &[&'static str], 525 | ) -> error::Result 526 | where S: DeserializeSeed<'de, Value = T> 527 | { 528 | let mut de = Deserializer::new(bytes, enum_variant_ids); 529 | let value: T = DeserializeSeed::deserialize(seed, &mut de)?; 530 | 531 | Ok(value) 532 | } 533 | 534 | /// Deserialize an instance of type `T` from an IO stream of binary MTProto. 535 | pub fn from_reader(reader: R, enum_variant_ids: &[&'static str]) -> error::Result 536 | where R: io::Read, 537 | T: DeserializeOwned, 538 | { 539 | let mut de = Deserializer::new(reader, enum_variant_ids); 540 | let value: T = Deserialize::deserialize(&mut de)?; 541 | 542 | Ok(value) 543 | } 544 | 545 | /// Deserialize an instance of type `T` from an IO stream of binary MTProto and return unused part 546 | /// of IO stream. 547 | pub fn from_reader_reuse(reader: R, 548 | enum_variant_ids: &[&'static str]) 549 | -> error::Result<(T, R)> 550 | where R: io::Read, 551 | T: DeserializeOwned, 552 | { 553 | let mut de = Deserializer::new(reader, enum_variant_ids); 554 | let value: T = Deserialize::deserialize(&mut de)?; 555 | 556 | Ok((value, de.reader)) 557 | } 558 | 559 | /// Deserialize an instance of type `T` from an IO stream of binary MTProto using a seed. 560 | pub fn from_reader_seed( 561 | seed: S, 562 | reader: R, 563 | enum_variant_ids: &[&'static str], 564 | ) -> error::Result 565 | where S: for<'de> DeserializeSeed<'de, Value = T>, 566 | R: io::Read, 567 | { 568 | let mut de = Deserializer::new(reader, enum_variant_ids); 569 | let value: T = DeserializeSeed::deserialize(seed, &mut de)?; 570 | 571 | Ok(value) 572 | } 573 | -------------------------------------------------------------------------------- /tests/regression_tests.rs: -------------------------------------------------------------------------------- 1 | //! Integration & regression tests. 2 | 3 | 4 | use std::collections::BTreeMap; 5 | 6 | use derivative::Derivative; 7 | use lazy_static::lazy_static; 8 | use maplit::btreemap; 9 | use pretty_assertions::assert_eq; 10 | use serde::de::{Deserializer, DeserializeSeed, Error as DeError}; 11 | use serde_derive::{Serialize, Deserialize}; 12 | use serde_mtproto_derive::{MtProtoIdentifiable, MtProtoSized}; 13 | use serde_bytes::ByteBuf; 14 | use serde_mtproto::{ 15 | Boxed, MtProtoSized, UnsizedByteBuf, UnsizedByteBufSeed, 16 | to_bytes, to_writer, from_bytes, from_reader, 17 | }; 18 | 19 | 20 | #[derive(Debug, Derivative, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 21 | #[derivative(PartialEq)] 22 | #[mtproto_identifiable(id = "0xdeadbeef")] 23 | struct Foo { 24 | has_receiver: bool, 25 | size: u64, 26 | raw_info: ByteBuf, 27 | 28 | #[derivative(PartialEq = "ignore")] 29 | #[serde(skip)] 30 | #[mtproto_sized(skip)] 31 | to_be_skipped: i8, 32 | } 33 | 34 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 35 | #[mtproto_identifiable(id = "0x80808080")] 36 | struct Message { 37 | auth_key_id: i64, 38 | msg_key: [u32; 4], 39 | #[serde(deserialize_with = "deserialize_message")] 40 | encrypted_data: UnsizedByteBuf, 41 | } 42 | 43 | fn deserialize_message<'de, D>(deserializer: D) -> Result 44 | where D: Deserializer<'de> 45 | { 46 | UnsizedByteBufSeed::new(32).map_err(D::Error::custom)?.deserialize(deserializer) 47 | } 48 | 49 | fn pad(bytes: &[u8]) -> Vec { 50 | let padding = (16 - bytes.len() % 16) % 16; 51 | let mut byte_buf = Vec::with_capacity(bytes.len() + padding); 52 | byte_buf.extend_from_slice(bytes); 53 | 54 | for _ in 0..padding { 55 | byte_buf.push(0); 56 | } 57 | 58 | byte_buf 59 | } 60 | 61 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 62 | #[mtproto_identifiable(id = "0xb01dface")] 63 | struct Point3I(i32, i32, i32); 64 | 65 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 66 | #[mtproto_identifiable(id = "0xca11ab1e")] 67 | struct Wrapper(i16); 68 | 69 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 70 | #[mtproto_identifiable(id = "0xd15ea5e0")] 71 | struct Nothing; 72 | 73 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 74 | enum CLike { 75 | #[mtproto_identifiable(id = "0x5ca1ab1e")] 76 | A, 77 | #[mtproto_identifiable(id = "0xca55e77e")] 78 | B, 79 | #[mtproto_identifiable(id = "0xf007ba11")] 80 | C, 81 | } 82 | 83 | #[derive(Debug, PartialEq, Serialize, Deserialize, MtProtoIdentifiable, MtProtoSized)] 84 | enum Cafebabe { 85 | #[mtproto_identifiable(id = "0x0badf00d")] 86 | Bar { 87 | byte_id: i8, 88 | position: (u64, u32), 89 | #[serde(bound = "T: serde_mtproto::Identifiable")] 90 | data: Boxed, 91 | bignum: i128, 92 | ratio: f32, 93 | }, 94 | #[mtproto_identifiable(id = "0xbaaaaaad")] 95 | Baz { 96 | id: u64, 97 | name: String, 98 | payload: T, 99 | // not HashMap, because we need deterministic ordering for testing purposes 100 | mapping: BTreeMap, 101 | }, 102 | #[mtproto_identifiable(id = "0x0d00d1e0")] 103 | Blob, 104 | #[mtproto_identifiable(id = "0x7e1eca57")] 105 | Quux(CLike), 106 | #[mtproto_identifiable(id = "0xf01dab1e")] 107 | Spam(Boxed), 108 | } 109 | 110 | 111 | lazy_static! { 112 | static ref BUILTIN_I128: i128 = 100000000000000000000000000000000000000; 113 | 114 | static ref BUILTIN_I128_SERIALIZED_BARE: Vec = vec![ 115 | 0, 0, 0, 0, 64, 34, 138, 9, // 100000000000000000000000000000000000000 as \ 116 | 122, 196, 134, 90, 168, 76, 59, 75, // 128-bit int 117 | ]; 118 | 119 | static ref FOO: Foo = Foo { 120 | has_receiver: true, 121 | size: 57, 122 | raw_info: ByteBuf::from(vec![56, 114, 200, 1]), 123 | to_be_skipped: -117, 124 | }; 125 | 126 | static ref FOO_SERIALIZED_BARE: Vec = vec![ 127 | 181, 117, 114, 153, // id of true in little-endian 128 | 57, 0, 0, 0, 0, 0, 0, 0, // 57 as little-endian 64-bit int 129 | 4, 56, 114, 200, 1, 0, 0, 0, // byte buffer containing 4 bytes 130 | ]; 131 | 132 | static ref FOO_SERIALIZED_BOXED: Vec = vec![ 133 | 0xef, 0xbe, 0xad, 0xde, // id of Foo in little-endian 134 | 181, 117, 114, 153, // id of true in little-endian 135 | 57, 0, 0, 0, 0, 0, 0, 0, // 57 as little-endian 64-bit int 136 | 4, 56, 114, 200, 1, 0, 0, 0, // byte buffer containing 4 bytes 137 | ]; 138 | 139 | static ref MESSAGE: Message = Message { 140 | #![cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))] // We need to seamlessly test ser/de for large decimal numbers in any form 141 | 142 | auth_key_id: -0x7edc_ba98_7654_3210, 143 | msg_key: [3230999370, 1546177172, 3106848747, 2091612143], 144 | encrypted_data: UnsizedByteBuf::new(pad(&[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18])).unwrap(), 145 | }; 146 | 147 | static ref MESSAGE_SERIALIZED_BARE: Vec = vec![ 148 | 0xf0, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x81, 149 | 0x4a, 0x23, 0x95, 0xc0, 0x94, 0xca, 0x28, 0x5c, 150 | 0xeb, 0xbf, 0x2e, 0xb9, 0xef, 0x77, 0xab, 0x7c, 151 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 152 | 16, 17, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 153 | ]; 154 | 155 | static ref MESSAGE_SERIALIZED_BOXED: Vec = vec![ 156 | 0x80, 0x80, 0x80, 0x80, 157 | 0xf0, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x81, 158 | 0x4a, 0x23, 0x95, 0xc0, 0x94, 0xca, 0x28, 0x5c, 159 | 0xeb, 0xbf, 0x2e, 0xb9, 0xef, 0x77, 0xab, 0x7c, 160 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 161 | 16, 17, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 162 | ]; 163 | 164 | static ref POINT_3I: Point3I = Point3I(-35_000, 846, 1_029_748); 165 | 166 | static ref POINT_3I_SERIALIZED_BARE: Vec = vec![ 167 | 72, 119, 255, 255, // -35000 as little-endian 32-bit int 168 | 78, 3, 0, 0, // 846 as little-endian 32-bit int 169 | 116, 182, 15, 0, // 1029748 as little-endian 32-bit int 170 | ]; 171 | 172 | static ref POINT_3I_SERIALIZED_BOXED: Vec = vec![ 173 | 0xce, 0xfa, 0x1d, 0xb0, // id of Point3I in little-endian 174 | 72, 119, 255, 255, // -35000 as little-endian 32-bit int 175 | 78, 3, 0, 0, // 846 as little-endian 32-bit int 176 | 116, 182, 15, 0, // 1029748 as little-endian 32-bit int 177 | ]; 178 | 179 | static ref WRAPPER: Wrapper = Wrapper(-32_768); 180 | 181 | static ref WRAPPER_SERIALIZED_BARE: Vec = vec![ 182 | 0, 128, 255, 255, // -32768 as 32-bit int (MTProto doesn't support less than 32-bit) 183 | ]; 184 | 185 | static ref WRAPPER_SERIALIZED_BOXED: Vec = vec![ 186 | 0x1e, 0xab, 0x11, 0xca, // id of Wrapper in little-endian 187 | 0, 128, 255, 255, // -32768 as 32-bit int (MTProto doesn't support less than 32-bit) 188 | ]; 189 | 190 | static ref NOTHING: Nothing = Nothing; 191 | 192 | static ref NOTHING_SERIALIZED_BARE: Vec = vec![]; 193 | 194 | static ref NOTHING_SERIALIZED_BOXED: Vec = vec![ 195 | 0xe0, 0xa5, 0x5e, 0xd1, // id of Nothing in little-endian 196 | ]; 197 | 198 | static ref C_LIKE_B: CLike = CLike::B; 199 | 200 | static ref C_LIKE_B_SERIALIZED_BOXED: Vec = vec![ 201 | 0x7e, 0xe7, 0x55, 0xca, // id of CLike::B in little-endian 202 | ]; 203 | 204 | static ref CAFEBABE_BAR: Cafebabe = Cafebabe::Bar { 205 | byte_id: -20, 206 | position: (350, 142_857), 207 | data: Boxed::new(4096), 208 | bignum: 100000000000000000000000000000000000000, 209 | ratio: ::std::f32::consts::E, 210 | }; 211 | 212 | static ref CAFEBABE_BAR_SERIALIZED_BOXED: Vec = vec![ 213 | 0x0d, 0xf0, 0xad, 0x0b, // id of Cafebabe::Bar in little-endian 214 | 236, 255, 255, 255, // -20 as 32-bit int (MTProto doesn't support \ 215 | // less than 32-bit) 216 | 94, 1, 0, 0, 0, 0, 0, 0, // 350 as little-endian 64-bit int 217 | 9, 46, 2, 0, // 142857 as little-endian 32-bit int 218 | 218, 155, 80, 168, // id of int built-in MTProto type 219 | 0, 16, 0, 0, // 4096 as little-endian 32-bit int 220 | 0, 0, 0, 0, 64, 34, 138, 9, // 100000000000000000000000000000000000000 as \ 221 | 122, 196, 134, 90, 168, 76, 59, 75, // 128-bit int 222 | 0, 0, 0, 128, 10, 191, 5, 64, // 2.718281828 as little-endian 32-bit \ 223 | // floating point 224 | ]; 225 | 226 | static ref CAFEBABE_BAZ: Cafebabe> = Cafebabe::Baz { 227 | id: u64::max_value(), 228 | name: "bee".to_owned(), 229 | payload: vec![false, true, false], 230 | mapping: btreemap!{ 231 | "QWERTY".to_owned() => -1_048_576, 232 | "something".to_owned() => 0, 233 | "OtHeR".to_owned() => 0x7fff_ffff_ffff_ffff, 234 | "こんにちは".to_owned() => 0b0111_0100_1100_0110_0111_1000_0100_0101_1100_0100_1011, 235 | "".to_owned() => -1, 236 | }, 237 | }; 238 | 239 | static ref CAFEBABE_BAZ_SERIALIZED_BOXED: Vec = vec![ 240 | 0xad, 0xaa, 0xaa, 0xba, // id of Cafebabe::Baz in little-endian 241 | 255, 255, 255, 255, 255, 255, 255, 255, // u64::max_value() == 2 ** 64 - 1 242 | 3, 98, 101, 101, // string "bee" of length 4 and no padding 243 | 244 | 3, 0, 0, 0, // vec has 3 elements, len as 32-bit int 245 | 55, 151, 121, 188, // id of false in little-endian 246 | 181, 117, 114, 153, // id of true in little-endian 247 | 55, 151, 121, 188, // id of false in little-endian 248 | 249 | 5, 0, 0, 0, // hashmap has 5 elements, len as 32-bit int 250 | 0, 0, 0, 0, // "" 251 | 255, 255, 255, 255, 255, 255, 255, 255, // -1 as little-endian 64-bit int 252 | 5, 79, 116, 72, 101, 82, 0, 0, // "OtHeR" 253 | 255, 255, 255, 255, 255, 255, 255, 127, // 0x7fff_ffff_ffff_ffff as little-endian 64-bit int 254 | 6, 81, 87, 69, 82, 84, 89, 0, // "QWERTY" 255 | 0, 0, 240, 255, 255, 255, 255, 255, // -1048576 as little-endian 64-bit int 256 | 9, 115, 111, 109, 101, 116, 104, 105, 110, 103, 0, 0, // "something" 257 | 0, 0, 0, 0, 0, 0, 0, 0, // 0 as little-endian 64-bit int 258 | 15, 227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175, // "こんにちは" 259 | 75, 92, 132, 103, 76, 7, 0, 0, // 8024735636555 as little-endian 64-bit int 260 | ]; 261 | 262 | static ref CAFEBABE_BLOB: Cafebabe = Cafebabe::Blob; 263 | 264 | static ref CAFEBABE_BLOB_SERIALIZED_BOXED: Vec = vec![ 265 | 0xe0, 0xd1, 0x00, 0x0d, // id of Cafebabe::Blob in little-endian 266 | ]; 267 | 268 | static ref CAFEBABE_QUUX: Cafebabe = Cafebabe::Quux(CLike::C); 269 | 270 | static ref CAFEBABE_QUUX_SERIALIZED_BOXED: Vec = vec![ 271 | 0x57, 0xca, 0x1e, 0x7e, // id of Cafebabe::Quux in little-endian 272 | ]; 273 | 274 | static ref CAFEBABE_SPAM: Cafebabe> = Cafebabe::Spam(Boxed::new(CLike::A)); 275 | 276 | static ref CAFEBABE_SPAM_SERIALIZED_BOXED: Vec = vec![ 277 | 0x1e, 0xab, 0x1d, 0xf0, // id of Cafebabe::Spam in little-endian 278 | 0x1e, 0xab, 0xa1, 0x5c, // id of CLike::A in little-endian 279 | ]; 280 | } 281 | 282 | 283 | macro_rules! test_suite { 284 | ($to_bytes:ident, $to_writer:ident, $from_bytes:ident, $from_reader:ident, $size_prediction:ident => 285 | $Type:ty: ($SER_VAR:expr, $DE_VAR:expr, $VAR_SERIALIZED:expr, 286 | $var_deserialized:ident, $enum_variant_hint:expr, $var_deserialized_assert:expr) 287 | ) => { 288 | #[test] 289 | fn $to_bytes() { 290 | let vec = to_bytes(&$SER_VAR).unwrap(); 291 | 292 | assert_eq!(vec, *$VAR_SERIALIZED); 293 | } 294 | 295 | #[test] 296 | fn $to_writer() { 297 | let mut vec = Vec::new(); 298 | to_writer(&mut vec, &$SER_VAR).unwrap(); 299 | 300 | assert_eq!(vec, *$VAR_SERIALIZED); 301 | } 302 | 303 | #[test] 304 | fn $from_bytes() { 305 | let $var_deserialized: $Type = from_bytes(&*$VAR_SERIALIZED, $enum_variant_hint).unwrap(); 306 | 307 | assert_eq!($var_deserialized_assert, $DE_VAR); 308 | } 309 | 310 | #[test] 311 | fn $from_reader() { 312 | let $var_deserialized: $Type = from_reader($VAR_SERIALIZED.as_slice(), $enum_variant_hint).unwrap(); 313 | 314 | assert_eq!($var_deserialized_assert, $DE_VAR); 315 | } 316 | 317 | #[test] 318 | fn $size_prediction() { 319 | let predicted_len = $SER_VAR.size_hint().unwrap(); 320 | 321 | assert_eq!(predicted_len, $VAR_SERIALIZED.len()); 322 | } 323 | }; 324 | } 325 | 326 | macro_rules! test_suite_bare { 327 | ($to_bytes:ident, $to_writer:ident, $from_bytes:ident, $from_reader:ident, $size_prediction:ident => 328 | $Type:ty: ($VAR:expr, $VAR_SERIALIZED_BARE:expr, $var_deserialized:ident, $enum_variant_hint:expr) 329 | ) => { 330 | test_suite!{ 331 | $to_bytes, $to_writer, $from_bytes, $from_reader, $size_prediction => 332 | $Type: (*$VAR, *$VAR, $VAR_SERIALIZED_BARE, $var_deserialized, 333 | $enum_variant_hint, $var_deserialized) 334 | } 335 | }; 336 | } 337 | 338 | macro_rules! test_suite_boxed { 339 | ($to_bytes:ident, $to_writer:ident, $from_bytes:ident, $from_reader:ident, $size_prediction:ident => 340 | $Type:ty: ($VAR:expr, $VAR_SERIALIZED_BOXED:expr, $var_deserialized:ident, $enum_variant_hint:expr) 341 | ) => { 342 | test_suite!{ 343 | $to_bytes, $to_writer, $from_bytes, $from_reader, $size_prediction => 344 | Boxed<$Type>: (Boxed::new(&*$VAR), *$VAR, $VAR_SERIALIZED_BOXED, 345 | $var_deserialized, $enum_variant_hint, $var_deserialized.into_inner()) 346 | } 347 | }; 348 | } 349 | 350 | 351 | test_suite_bare! { 352 | test_builtin_i128_to_bytes_bare, 353 | test_builtin_i128_to_writer_bare, 354 | test_builtin_i128_from_bytes_bare, 355 | test_builtin_i128_from_reader_bare, 356 | test_builtin_i128_size_prediction_bare => 357 | i128: (BUILTIN_I128, BUILTIN_I128_SERIALIZED_BARE, builin_i128_deserialized_bare, &[]) 358 | } 359 | 360 | test_suite_bare! { 361 | test_struct_to_bytes_bare, 362 | test_struct_to_writer_bare, 363 | test_struct_from_bytes_bare, 364 | test_struct_from_reader_bare, 365 | test_struct_size_prediction_bare => 366 | Foo: (FOO, FOO_SERIALIZED_BARE, foo_deserialized_bare, &[]) 367 | } 368 | 369 | test_suite_boxed! { 370 | test_struct_to_bytes_boxed, 371 | test_struct_to_writer_boxed, 372 | test_struct_from_bytes_boxed, 373 | test_struct_from_reader_boxed, 374 | test_struct_size_prediction_boxed => 375 | Foo: (FOO, FOO_SERIALIZED_BOXED, foo_deserialized_boxed, &[]) 376 | } 377 | 378 | 379 | test_suite_bare! { 380 | test_struct_to_bytes_bare2, 381 | test_struct_to_writer_bare2, 382 | test_struct_from_bytes_bare2, 383 | test_struct_from_reader_bare2, 384 | test_struct_size_prediction_bare2 => 385 | Message: (MESSAGE, MESSAGE_SERIALIZED_BARE, message_deserialized_bare, &[]) 386 | } 387 | 388 | test_suite_boxed! { 389 | test_struct_to_bytes_boxed2, 390 | test_struct_to_writer_boxed2, 391 | test_struct_from_bytes_boxed2, 392 | test_struct_from_reader_boxed2, 393 | test_struct_size_prediction_boxed2 => 394 | Message: (MESSAGE, MESSAGE_SERIALIZED_BOXED, message_deserialized_boxed, &[]) 395 | } 396 | 397 | 398 | test_suite_bare! { 399 | test_tuple_struct_to_bytes_bare, 400 | test_tuple_struct_to_writer_bare, 401 | test_tuple_struct_from_bytes_bare, 402 | test_tuple_struct_from_reader_bare, 403 | test_tuple_struct_size_prediction_bare => 404 | Point3I: (POINT_3I, POINT_3I_SERIALIZED_BARE, point_3i_deserialized_bare, &[]) 405 | } 406 | 407 | test_suite_boxed! { 408 | test_tuple_struct_to_bytes_boxed, 409 | test_tuple_struct_to_writer_boxed, 410 | test_tuple_struct_from_bytes_boxed, 411 | test_tuple_struct_from_reader_boxed, 412 | test_tuple_struct_size_prediction_boxed => 413 | Point3I: (POINT_3I, POINT_3I_SERIALIZED_BOXED, point_3i_deserialized_boxed, &[]) 414 | } 415 | 416 | 417 | test_suite_bare! { 418 | test_newtype_struct_to_bytes_bare, 419 | test_newtype_struct_to_writer_bare, 420 | test_newtype_struct_from_bytes_bare, 421 | test_newtype_struct_from_reader_bare, 422 | test_newtype_struct_size_prediction_bare => 423 | Wrapper: (WRAPPER, WRAPPER_SERIALIZED_BARE, wrapper_deserialized_bare, &[]) 424 | } 425 | 426 | test_suite_boxed! { 427 | test_newtype_struct_to_bytes_boxed, 428 | test_newtype_struct_to_writer_boxed, 429 | test_newtype_struct_from_bytes_boxed, 430 | test_newtype_struct_from_reader_boxed, 431 | test_newtype_struct_size_prediction_boxed => 432 | Wrapper: (WRAPPER, WRAPPER_SERIALIZED_BOXED, wrapper_deserialized_boxed, &[]) 433 | } 434 | 435 | 436 | test_suite_bare! { 437 | test_unit_struct_to_bytes_bare, 438 | test_unit_struct_to_writer_bare, 439 | test_unit_struct_from_bytes_bare, 440 | test_unit_struct_from_reader_bare, 441 | test_unit_struct_size_prediction_bare => 442 | Nothing: (NOTHING, NOTHING_SERIALIZED_BARE, nothing_deserialized_bare, &[]) 443 | } 444 | 445 | test_suite_boxed! { 446 | test_unit_struct_to_bytes_boxed, 447 | test_unit_struct_to_writer_boxed, 448 | test_unit_struct_from_bytes_boxed, 449 | test_unit_struct_from_reader_boxed, 450 | test_unit_struct_size_prediction_boxed => 451 | Nothing: (NOTHING, NOTHING_SERIALIZED_BOXED, nothing_deserialized_boxed, &[]) 452 | } 453 | 454 | 455 | test_suite_boxed! { 456 | test_c_like_enum_variant_to_bytes_boxed, 457 | test_c_like_enum_variant_to_writer_boxed, 458 | test_c_like_enum_variant_from_bytes_boxed, 459 | test_c_like_enum_variant_from_reader_boxed, 460 | test_c_like_enum_variant_size_prediction_boxed => 461 | CLike: (C_LIKE_B, C_LIKE_B_SERIALIZED_BOXED, c_like_b_deserialized_boxed, &["B"]) 462 | } 463 | 464 | 465 | test_suite_boxed! { 466 | test_enum_variant_to_bytes_boxed, 467 | test_enum_variant_to_writer_boxed, 468 | test_enum_variant_from_bytes_boxed, 469 | test_enum_variant_from_reader_boxed, 470 | test_enum_variant_size_prediction_boxed => 471 | Cafebabe: (CAFEBABE_BAR, CAFEBABE_BAR_SERIALIZED_BOXED, cafebabe_bar_deserialized_boxed, &["Bar"]) 472 | } 473 | 474 | 475 | test_suite_boxed! { 476 | test_enum_variant_to_bytes_boxed2, 477 | test_enum_variant_to_writer_boxed2, 478 | test_enum_variant_from_bytes_boxed2, 479 | test_enum_variant_from_reader_boxed2, 480 | test_enum_variant_size_prediction_boxed2 => 481 | Cafebabe>: (CAFEBABE_BAZ, CAFEBABE_BAZ_SERIALIZED_BOXED, cafebabe_baz_deserialized_boxed, &["Baz"]) 482 | } 483 | 484 | 485 | test_suite_boxed! { 486 | test_unit_enum_variant_to_bytes_boxed, 487 | test_unit_enum_variant_to_writer_boxed, 488 | test_unit_enum_variant_from_bytes_boxed, 489 | test_unit_enum_variant_from_reader_boxed, 490 | test_unit_enum_variant_size_prediction_boxed => 491 | Cafebabe: (CAFEBABE_BLOB, CAFEBABE_BLOB_SERIALIZED_BOXED, cafebabe_blob_deserialized_boxed, &["Blob"]) 492 | } 493 | 494 | 495 | test_suite_boxed! { 496 | test_newtype_enum_variant_with_bare_to_bytes_boxed, 497 | test_newtype_enum_variant_with_bare_to_writer_boxed, 498 | test_newtype_enum_variant_with_bare_from_bytes_boxed, 499 | test_newtype_enum_variant_with_bare_from_reader_boxed, 500 | test_newtype_enum_variant_with_bare_size_prediction_boxed => 501 | Cafebabe: (CAFEBABE_QUUX, CAFEBABE_QUUX_SERIALIZED_BOXED, cafebabe_quux_deserialized_boxed, &["Quux", "C"]) 502 | } 503 | 504 | 505 | test_suite_boxed! { 506 | test_newtype_enum_variant_with_boxed_to_bytes_boxed, 507 | test_newtype_enum_variant_with_boxed_to_writer_boxed, 508 | test_newtype_enum_variant_with_boxed_from_bytes_boxed, 509 | test_newtype_enum_variant_with_boxed_from_reader_boxed, 510 | test_newtype_enum_variant_with_boxed_size_prediction_boxed => 511 | Cafebabe>: (CAFEBABE_SPAM, CAFEBABE_SPAM_SERIALIZED_BOXED, cafebabe_spam_deserialized_boxed, &["Spam", "A"]) 512 | } 513 | 514 | 515 | /// MTProto-serialized data must be aligned by 4 bytes. 516 | #[test] 517 | fn test_serialization_alignment() { 518 | assert!(FOO_SERIALIZED_BARE.len() % 4 == 0); 519 | assert!(FOO_SERIALIZED_BOXED.len() % 4 == 0); 520 | assert!(MESSAGE_SERIALIZED_BARE.len() % 4 == 0); 521 | assert!(MESSAGE_SERIALIZED_BOXED.len() % 4 == 0); 522 | assert!(POINT_3I_SERIALIZED_BARE.len() % 4 == 0); 523 | assert!(POINT_3I_SERIALIZED_BOXED.len() % 4 == 0); 524 | assert!(WRAPPER_SERIALIZED_BARE.len() % 4 == 0); 525 | assert!(WRAPPER_SERIALIZED_BOXED.len() % 4 == 0); 526 | assert!(NOTHING_SERIALIZED_BARE.len() % 4 == 0); 527 | assert!(NOTHING_SERIALIZED_BOXED.len() % 4 == 0); 528 | assert!(C_LIKE_B_SERIALIZED_BOXED.len() % 4 == 0); 529 | assert!(CAFEBABE_BAR_SERIALIZED_BOXED.len() % 4 == 0); 530 | assert!(CAFEBABE_BAZ_SERIALIZED_BOXED.len() % 4 == 0); 531 | assert!(CAFEBABE_BLOB_SERIALIZED_BOXED.len() % 4 == 0); 532 | assert!(CAFEBABE_QUUX_SERIALIZED_BOXED.len() % 4 == 0); 533 | assert!(CAFEBABE_SPAM_SERIALIZED_BOXED.len() % 4 == 0); 534 | } 535 | --------------------------------------------------------------------------------