versionize_derive-0.1.5/.cargo_vcs_info.json0000644000000001360000000000100145720ustar { "git": { "sha1": "f0a7194791c5cbeeb55aecfa6e60cca6f2c4168a" }, "path_in_vcs": "" }versionize_derive-0.1.5/.github/pull_request_template.md000064400000000000000000000014661046102023000216720ustar 00000000000000## Reason for This PR `[Author TODO: add issue # or explain reasoning.]` ## Description of Changes `[Author TODO: add description of changes.]` ## License Acceptance By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. ## PR Checklist `[Author TODO: Meet these criteria.]` `[Reviewer TODO: Verify that these criteria are met. Request changes if not]` - [ ] All commits in this PR are signed (`git commit -s`). - [ ] The reason for this PR is clearly provided (issue no. or explanation). - [ ] The description of changes is clear and encompassing. - [ ] Any required documentation changes (code and docs) are included in this PR. - [ ] Any newly added `unsafe` code is properly documented. - [ ] Any user-facing changes are mentioned in `CHANGELOG.md`. versionize_derive-0.1.5/.gitignore000064400000000000000000000005001046102023000153450ustar 00000000000000# Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk versionize_derive-0.1.5/.gitmodules000064400000000000000000000001411046102023000155330ustar 00000000000000[submodule "rust-vmm-ci"] path = rust-vmm-ci url = https://github.com/rust-vmm/rust-vmm-ci.git versionize_derive-0.1.5/CHANGELOG.md000064400000000000000000000006341046102023000151760ustar 00000000000000# v0.1.5 - Ping dependency versions - Fix clippy errors and warnings - Bump rust-vmm-ci version # v0.1.4 - Added more documentation and examples. # v0.1.3 - Updated documentation. # v0.1.2 - Removed union serialization support. # v0.1.1 - Removed "versionize" dependency. - Added support for (de)serializing enum variants with zero or more fields. # v0.1.0 - "versionize_derive" v0.1.0 first release. versionize_derive-0.1.5/CONTRIBUTING.md000064400000000000000000000052521046102023000156170ustar 00000000000000# Contributing to versionize_derive ## Contribution Workflow The versionize_derive repository uses the “fork-and-pull” development model. Follow these steps if you want to merge your changes: 1. Within your fork of [versionize_derive](https://github.com/firecracker-microvm/versionize_derive), create a branch for your contribution. Use a meaningful name. 1. Create your contribution, meeting all [contribution quality standards](#contribution-quality-standards) 1. [Create a pull request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/) against the master branch of the versionize_derive repository. 1. Work with your reviewers to address any comments and obtain a minimum of 2 approvals, at least one of which must be provided by [a maintainer](MAINTAINERS.md). To update your pull request amend existing commits whenever applicable and then push the new changes to your pull request branch. 1. Once the pull request is approved, one of the maintainers will merge it. ## Request for Comments If you just want to receive feedback for a contribution proposal, open an “RFC” (“Request for Comments”) pull request: 1. On your fork of [versionize_derive](https://github.com/firecracker-microvm/versionize_derive), create a branch for the contribution you want feedback on. Use a meaningful name. 1. Create your proposal based on the existing codebase. 1. [Create a draft pull request](https://github.blog/2019-02-14-introducing-draft-pull-requests/) against the master branch of the versionize_derive repository. 1. Discuss your proposal with the community on the pull request page (or on any other channel). Add the conclusion(s) of this discussion to the pull request page. ## Contribution Quality Standards Most quality and style standards are enforced automatically during integration testing. Your contribution needs to meet the following standards: - Separate each **logical change** into its own commit. - Each commit must pass all unit & code style tests, and the full pull request must pass all integration tests. - Unit test coverage must _increase_ the overall project code coverage. - Document all your public functions. - Add a descriptive message for each commit. Follow [commit message best practices](https://github.com/erlang/otp/wiki/writing-good-commit-messages). - Document your pull requests. Include the reasoning behind each change. - Acknowledge versionize_derive's [Apache 2.0 license](LICENSE) and certify that no part of your contribution contravenes this license by signing off on all your commits with `git -s`. Ensure that every file in your pull request has a header referring to the repository license file. versionize_derive-0.1.5/Cargo.toml0000644000000020500000000000100125650ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "versionize_derive" version = "0.1.5" authors = ["Amazon Firecracker team "] description = "Implements the Versionize derive proc macro." readme = "README.md" keywords = [ "serialization", "version", ] license = "Apache-2.0" repository = "https://github.com/firecracker-microvm/versionize_derive" [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0.47" [dependencies.quote] version = "1.0.21" [dependencies.syn] version = "1.0.13" features = [ "full", "extra-traits", ] [badges.maintenance] status = "experimental" versionize_derive-0.1.5/Cargo.toml.orig000064400000000000000000000010311046102023000162440ustar 00000000000000[package] name = "versionize_derive" version = "0.1.5" license = "Apache-2.0" authors = ["Amazon Firecracker team "] description = "Implements the Versionize derive proc macro." readme = "README.md" repository = "https://github.com/firecracker-microvm/versionize_derive" keywords = ["serialization", "version"] [dependencies] proc-macro2 = "1.0.47" quote = "1.0.21" syn = { version = "1.0.13", features=["full", "extra-traits"]} [lib] proc-macro = true [badges] maintenance = { status = "experimental" } versionize_derive-0.1.5/LICENSE000064400000000000000000000261351046102023000143760ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. versionize_derive-0.1.5/README.md000064400000000000000000000053071046102023000146460ustar 00000000000000**Versionize is a framework for version tolerant serializion/deserialization of Rust data structures, designed for usecases that need fast deserialization times and minimal size overhead. It does not aim to be a generic serialization framework and only the [bincode](https://crates.io/crates/bincode) backend is supported.** #### You may be looking for: - [Versionize documentation](https://docs.rs/versionize/) - [Releases](https://github.com/firecracker-microvm/versionize_derive/releases) ## Important note This crate is currently used for cross-version serialization with the [Firecracker snapshot-restore dev preview][1], but has not been tested for other use cases. It should be considered **experimental software** outside the Firecracker context. It’s likely that this crate will see both interface and implementation changes in the future. ## Versionize in action ```rust extern crate versionize; extern crate versionize_derive; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; // The test structure is at version 3. #[derive(Debug, PartialEq, Versionize)] pub struct Test { a: u32, #[version(start = 2, end = 3)] b: u8, #[version(start = 3, default_fn = "default_c")] c: String, } impl Test { // Default value for field `c`. // The callback is invoked when deserialization from and older version // where the field did not exist. fn default_c(_source_version: u16) -> String { "test_string".to_owned() } } // Memory to hold the serialization output. let mut mem = vec![0u8; 512]; // Create a new version map - it will start at version 1. let mut version_map = VersionMap::new(); // Add new version and mark changes for Test struct: Set the current version // to point to Test struct version 2. version_map .new_version() .set_type_version(Test::type_id(), 2) .new_version() .set_type_version(Test::type_id(), 3); let test_struct = Test { a: 1337, b: 0xFF, c: "c_value".to_owned(), }; // Serialize to version 2 - field c will not be serialized. test_struct .serialize(&mut mem.as_mut_slice(), &version_map, 2) .unwrap(); // Deserialize from version 2 - c should contain the default_fn() return value. let restored_test_struct = Test::deserialize(&mut mem.as_slice(), &version_map, 2).unwrap(); assert_eq!( restored_test_struct, Test { a: 1337, b: 255, c: "test_string".to_owned() } ); ``` [1]: https://github.com/firecracker-microvm/firecracker/tree/v0.24.0versionize_derive-0.1.5/SECURITY-POLICY.md000064400000000000000000000022301046102023000161450ustar 00000000000000# Security Issue Policy If you uncover a security issue with versionize_derive, please write to us on . Once the Firecracker [maintainers](MAINTAINERS.md) become aware (or are made aware) of a security issue, they will immediately assess it. Based on impact and complexity, they will determine an embargo period (if externally reported, the period will be agreed upon with the external party). During the embargo period, maintainers will prioritize developing a fix over other activities. Within this period, maintainers may also notify a limited number of trusted parties via a pre-disclosure list, providing them with technical information, a risk assessment, and early access to a fix. The external customers are included in this group based on the scale of their versionize_derive usage in production. The pre-disclosure list may also contain significant external security contributors that can join the effort to fix the issue during the embargo period. At the end of the embargo period, maintainers will publicly release information about the security issue together with the versionize_derive patches that mitigate it. versionize_derive-0.1.5/coverage_config_aarch64.json000064400000000000000000000001021046102023000206760ustar 00000000000000{"coverage_score": 1.3, "exclude_path": "", "crate_features": ""} versionize_derive-0.1.5/coverage_config_x86_64.json000064400000000000000000000001021046102023000204040ustar 00000000000000{"coverage_score": 1.7, "exclude_path": "", "crate_features": ""} versionize_derive-0.1.5/src/common.rs000064400000000000000000000036221046102023000160120ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /// An interface for generating serialzer and deserializers based on /// field descriptions. pub trait Descriptor { /// Returns the serializer code block as a token stream. fn generate_serializer(&self) -> proc_macro2::TokenStream; /// Returns the deserializer code block as a token stream. fn generate_deserializer(&self) -> proc_macro2::TokenStream; /// Returns the curent version. fn version(&self) -> u16; /// Returns the type name as string. fn ty(&self) -> String; } /// Describes a structure and it's fields. pub(crate) struct GenericDescriptor { // The structure type identifier. pub ty: syn::Ident, pub version: u16, pub fields: Vec, } // A trait that defines an interface to check if a certain field // exists at a specified version. pub(crate) trait Exists { fn exists_at(&self, version: u16) -> bool { // All fields have a start version. // Some field do not have an end version specified. version >= self.start_version() && (0 == self.end_version() || (self.end_version() > 0 && version < self.end_version())) } fn start_version(&self) -> u16; fn end_version(&self) -> u16; } // A trait that defines an interface for exposing a field type. pub(crate) trait FieldType { fn ty(&self) -> syn::Type; } #[cfg(test)] mod tests { use super::Exists; #[test] fn test_exists_at() { impl Exists for u32 { fn start_version(&self) -> u16 { 3 } fn end_version(&self) -> u16 { 5 } } let test = 1234; assert!(!test.exists_at(2)); assert!(test.exists_at(3)); assert!(test.exists_at(4)); assert!(!test.exists_at(5)); assert!(!test.exists_at(6)); } } versionize_derive-0.1.5/src/descriptors/enum_desc.rs000064400000000000000000000047361046102023000210340ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use common::{Descriptor, GenericDescriptor}; use fields::enum_variant::*; use helpers::compute_version; use quote::quote; pub(crate) type EnumDescriptor = GenericDescriptor; impl Descriptor for EnumDescriptor { fn generate_serializer(&self) -> proc_macro2::TokenStream { let mut versioned_serializers = proc_macro2::TokenStream::new(); for i in 1..=self.version { let mut versioned_serializer = proc_macro2::TokenStream::new(); for field in &self.fields { versioned_serializer.extend(field.generate_serializer(i)); } // Generate the match arm for version `i` serializer. versioned_serializers.extend(quote! { #i => { match self { #versioned_serializer } } }); } versioned_serializers } // Versioned/semantic deserialization is not implemented for enums. fn generate_deserializer(&self) -> proc_macro2::TokenStream { let mut versioned_deserializers = proc_macro2::TokenStream::new(); for field in &self.fields { versioned_deserializers.extend(field.generate_deserializer()); } quote! { let variant_index = ::deserialize(&mut reader, version_map, app_version)?; match variant_index { #versioned_deserializers x => return Err(VersionizeError::Deserialize(format!("Unknown variant_index {}", x))) } } } fn version(&self) -> u16 { self.version } fn ty(&self) -> String { self.ty.to_string() } } impl EnumDescriptor { pub fn new(input: &syn::DataEnum, ident: syn::Ident) -> Self { let mut descriptor = EnumDescriptor { ty: ident, version: 1, fields: vec![], }; descriptor.parse_enum_variants(&input.variants); descriptor.version = compute_version(&descriptor.fields); descriptor } fn parse_enum_variants( &mut self, variants: &syn::punctuated::Punctuated, ) { for (index, variant) in variants.iter().enumerate() { self.fields .push(EnumVariant::new(self.version, variant, index as u32)); } } } versionize_derive-0.1.5/src/descriptors/mod.rs000064400000000000000000000002331046102023000176350ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 pub mod enum_desc; pub mod struct_desc; versionize_derive-0.1.5/src/descriptors/struct_desc.rs000064400000000000000000000105401046102023000214020ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use common::{Descriptor, GenericDescriptor}; use fields::struct_field::*; use helpers::compute_version; use quote::{format_ident, quote}; pub(crate) type StructDescriptor = GenericDescriptor; impl Descriptor for StructDescriptor { fn generate_serializer(&self) -> proc_macro2::TokenStream { let mut versioned_serializers = proc_macro2::TokenStream::new(); for i in 1..=self.version { let mut versioned_serializer = proc_macro2::TokenStream::new(); let mut semantic_serializer = proc_macro2::TokenStream::new(); // Generate field and semantic serializers for all fields. // Not all fields have semantic serializers defined and some fields // might be missing in version `i`. In these cases the generate_serializer() and // generate_semantic_serializer() will return an empty token stream. for field in &self.fields { versioned_serializer.extend(field.generate_serializer(i)); semantic_serializer.extend(field.generate_semantic_serializer(i)); } // Generate the match arm for version `i`. versioned_serializers.extend(quote! { #i => { #semantic_serializer #versioned_serializer } }); } versioned_serializers } fn generate_deserializer(&self) -> proc_macro2::TokenStream { let mut versioned_deserializers = proc_macro2::TokenStream::new(); let struct_ident = format_ident!("{}", self.ty); for i in 1..=self.version { let mut versioned_deserializer = proc_macro2::TokenStream::new(); let mut semantic_deserializer = proc_macro2::TokenStream::new(); // Generate field and semantic deserializers for all fields. // Not all fields have semantic deserializers defined and some fields // might be missing in version `i`. In these cases the generate_deserializer() and // generate_semantic_deserializer() will return an empty token stream. for field in &self.fields { versioned_deserializer.extend(field.generate_deserializer(i)); semantic_deserializer.extend(field.generate_semantic_deserializer(i)); } // Generate the match arm for version `i`. // // The semantic deserialization functions will be called after the object is constructed // using the previously generated field deserializers. versioned_deserializers.extend(quote! { #i => { let mut object = #struct_ident { #versioned_deserializer }; #semantic_deserializer Ok(object) } }); } // Generate code to map the app version to struct version and wrap the // deserializers with the `version` match. quote! { let version = version_map.get_type_version(app_version, ::type_id()); match version { #versioned_deserializers _ => panic!("Unknown {:?} version {}.", ::type_id(), version) } } } fn version(&self) -> u16 { self.version } fn ty(&self) -> String { self.ty.to_string() } } impl StructDescriptor { pub fn new(input: &syn::DataStruct, ident: syn::Ident) -> Self { let mut descriptor = StructDescriptor { ty: ident, version: 1, // struct start at version 1. fields: vec![], }; // Fills self.fields. descriptor.parse_struct_fields(&input.fields); descriptor.version = compute_version(&descriptor.fields); descriptor } fn parse_struct_fields(&mut self, fields: &syn::Fields) { match fields { syn::Fields::Named(ref named_fields) => { let pairs = named_fields.named.pairs(); for field in pairs { self.fields.push(StructField::new(self.version, field)); } } _ => panic!("Only named fields are supported."), } } } versionize_derive-0.1.5/src/fields/enum_variant.rs000064400000000000000000000120601046102023000204540ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use super::super::DEFAULT_FN; use common::Exists; use helpers::{get_end_version, get_ident_attr, get_start_version, parse_field_attributes}; use quote::{format_ident, quote}; use std::collections::hash_map::HashMap; #[derive(Debug, Eq, PartialEq, Clone)] pub(crate) struct EnumVariant { ident: syn::Ident, ty: Vec, start_version: u16, // Bincode uses u32 instead of usize also. variant_index: u32, end_version: u16, attrs: HashMap, } impl Exists for EnumVariant { fn start_version(&self) -> u16 { self.start_version } fn end_version(&self) -> u16 { self.end_version } } impl EnumVariant { pub fn new(base_version: u16, ast_variant: &syn::Variant, variant_index: u32) -> Self { let attrs = parse_field_attributes(&ast_variant.attrs); let ty = match &ast_variant.fields { syn::Fields::Unnamed(fields) => fields .unnamed .iter() .map(|field| field.ty.clone()) .collect(), _ => Vec::new(), }; EnumVariant { ident: ast_variant.ident.clone(), ty, variant_index, // Set base version. start_version: get_start_version(&attrs).unwrap_or(base_version), end_version: get_end_version(&attrs).unwrap_or_default(), attrs, } } // Emits code that serializes an enum variant. pub fn generate_serializer(&self, target_version: u16) -> proc_macro2::TokenStream { let field_ident = &self.ident; let variant_index = self.variant_index; if !self.exists_at(target_version) { if let Some(default_fn_ident) = get_ident_attr(&self.attrs, DEFAULT_FN) { let field_type_ident = if self.ty.is_empty() { quote! { Self::#field_ident => } } else { quote! { Self::#field_ident(..) => } }; let mut serializer = proc_macro2::TokenStream::new(); serializer.extend(field_type_ident); serializer.extend(self.default_fn_serializer(default_fn_ident)); return serializer; } else { panic!("Variant {} does not exist in version {}, please implement a default_fn function that provides a default value for this variant.", field_ident, target_version); } } let mut serialize_data = proc_macro2::TokenStream::new(); let mut data_tuple = proc_macro2::TokenStream::new(); for (index, _) in self.ty.iter().enumerate() { let data_ident = format_ident!("data_{}", index); data_tuple.extend(quote!(#data_ident,)); serialize_data.extend(quote! { Versionize::serialize(#data_ident, writer, version_map, app_version)?; }); } if self.ty.is_empty() { quote! { Self::#field_ident => { let index: u32 = #variant_index; Versionize::serialize(&index, writer, version_map, app_version)?; }, } } else { quote! { Self::#field_ident(#data_tuple) => { let index: u32 = #variant_index; Versionize::serialize(&index, writer, version_map, app_version)?; #serialize_data }, } } } pub fn generate_deserializer(&self) -> proc_macro2::TokenStream { let variant_index = self.variant_index; let ident = &self.ident; // Enum variant with no data. if self.ty.is_empty() { return quote! { #variant_index => { return Ok(Self::#ident); }, }; } let mut deserialize_data = proc_macro2::TokenStream::new(); let mut data_tuple = proc_macro2::TokenStream::new(); for (index, data_type) in self.ty.iter().enumerate() { let data_ident = format_ident!("data_{}", index); data_tuple.extend(quote!(#data_ident,)); deserialize_data.extend( quote! { let #data_ident = <#data_type as Versionize>::deserialize(&mut reader, version_map, app_version)?; } ); } quote! { #variant_index => { #deserialize_data return Ok(Self::#ident(#data_tuple)); }, } } fn default_fn_serializer(&self, default_fn_ident: syn::Ident) -> proc_macro2::TokenStream { quote! { { // Call user defined fn to provide a variant that exists in target version. let new_variant = self.#default_fn_ident(version)?; // The new_variant will serialize its index and data. new_variant.serialize(writer, version_map, app_version)?; }, } } } versionize_derive-0.1.5/src/fields/mod.rs000064400000000000000000000002371046102023000165460ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 pub mod enum_variant; pub mod struct_field; versionize_derive-0.1.5/src/fields/struct_field.rs000064400000000000000000000143351046102023000204620ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use super::super::{DEFAULT_FN, SEMANTIC_DE_FN, SEMANTIC_SER_FN}; use common::{Exists, FieldType}; use helpers::{get_end_version, get_ident_attr, get_start_version, parse_field_attributes}; use quote::{format_ident, quote}; use std::collections::hash_map::HashMap; #[derive(Debug, Eq, PartialEq, Clone)] pub(crate) struct StructField { ty: syn::Type, name: String, start_version: u16, end_version: u16, attrs: HashMap, } impl Exists for StructField { fn start_version(&self) -> u16 { self.start_version } fn end_version(&self) -> u16 { self.end_version } } impl FieldType for StructField { fn ty(&self) -> syn::Type { self.ty.clone() } } impl StructField { pub fn new( base_version: u16, ast_field: syn::punctuated::Pair<&syn::Field, &syn::token::Comma>, ) -> Self { let attrs = parse_field_attributes(&ast_field.value().attrs); StructField { ty: ast_field.value().ty.clone(), name: ast_field.value().ident.as_ref().unwrap().to_string(), start_version: get_start_version(&attrs).unwrap_or(base_version), end_version: get_end_version(&attrs).unwrap_or_default(), attrs, } } pub fn generate_semantic_serializer(&self, target_version: u16) -> proc_macro2::TokenStream { // Generate semantic serializer for this field only if it does not exist in target_version. if !self.exists_at(target_version) { if let Some(semantic_ser_fn) = get_ident_attr(&self.attrs, SEMANTIC_SER_FN) { return quote! { copy_of_self.#semantic_ser_fn(version)?; }; } } quote! {} } pub fn generate_semantic_deserializer(&self, source_version: u16) -> proc_macro2::TokenStream { // Generate semantic deserializer for this field only if it does not exist in source_version. if !self.exists_at(source_version) { if let Some(semantic_de_fn) = get_ident_attr(&self.attrs, SEMANTIC_DE_FN) { // Object is an instance of the structure. return quote! { object.#semantic_de_fn(version)?; }; } } quote! {} } pub fn generate_serializer(&self, target_version: u16) -> proc_macro2::TokenStream { let field_ident = format_ident!("{}", self.name); // Generate serializer for this field only if it exists in target_version. if !self.exists_at(target_version) { return proc_macro2::TokenStream::new(); } match &self.ty { syn::Type::Array(_) => quote! { for element in copy_of_self.#field_ident.iter() { Versionize::serialize(element, writer, version_map, app_version)?; } }, syn::Type::Path(_) => quote! { Versionize::serialize(©_of_self.#field_ident, writer, version_map, app_version)?; }, syn::Type::Reference(_) => quote! { copy_of_self.#field_ident.serialize(writer, version_map, app_version)?; }, _ => panic!("Unsupported field type {:?}", self.ty), } } pub fn generate_deserializer(&self, source_version: u16) -> proc_macro2::TokenStream { let field_ident = format_ident!("{}", self.name); // If the field does not exist in source version, use default annotation or Default trait. if !self.exists_at(source_version) { if let Some(default_fn) = get_ident_attr(&self.attrs, DEFAULT_FN) { return quote! { // The default_fn is called with source version of the struct: // - `version` is set to version_map.get_type_version(app_version, Self::type_id()); // - `app_version` is source application version. #field_ident: Self::#default_fn(version), }; } else { return quote! { #field_ident: Default::default(), }; } } let ty = &self.ty; match ty { syn::Type::Array(array) => { let array_type_token; match *array.elem.clone() { syn::Type::Path(token) => { array_type_token = token; } _ => panic!("Unsupported array type."), } match &array.len { syn::Expr::Lit(expr_lit) => match &expr_lit.lit { syn::Lit::Int(lit_int) => { let array_len: usize = lit_int.base10_parse().unwrap(); self.generate_array_deserializer(array_type_token, array_len) } _ => panic!("Unsupported array len literal."), }, syn::Expr::Path(expr_path) => { self.generate_array_deserializer(array_type_token, &expr_path.path) } _ => panic!("Unsupported array len expression."), } } syn::Type::Path(_) => quote! { #field_ident: <#ty as Versionize>::deserialize(&mut reader, version_map, app_version)?, }, syn::Type::Reference(_) => quote! { #field_ident: <#ty as Versionize>::deserialize(&mut reader, version_map, app_version)?, }, _ => panic!("Unsupported field type {:?}", self.ty), } } fn generate_array_deserializer( &self, array_type_token: syn::TypePath, array_len: T, ) -> proc_macro2::TokenStream { let field_ident = format_ident!("{}", self.name); quote! { #field_ident: { let mut array = [#array_type_token::default() ; #array_len]; for i in 0..#array_len { array[i] = <#array_type_token as Versionize>::deserialize(&mut reader, version_map, app_version)?; } array }, } } } versionize_derive-0.1.5/src/helpers.rs000064400000000000000000000051171046102023000161650ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use super::{ATTRIBUTE_NAME, END_VERSION, START_VERSION}; use common::Exists; use quote::format_ident; use std::cmp::max; use std::collections::hash_map::HashMap; // Returns a string literal attribute as an Ident. pub(crate) fn get_ident_attr( attrs: &HashMap, attr_name: &str, ) -> Option { attrs.get(attr_name).map(|default_fn| match default_fn { syn::Lit::Str(lit_str) => { format_ident!("{}", lit_str.value()) } _ => panic!("default_fn must be the function name as a String."), }) } pub(crate) fn get_start_version(attrs: &HashMap) -> Option { if let Some(start_version) = attrs.get(START_VERSION) { return Some(match start_version { syn::Lit::Int(lit_int) => lit_int.base10_parse().unwrap(), _ => panic!("Field start/end version number must be an integer"), }); } None } pub(crate) fn get_end_version(attrs: &HashMap) -> Option { if let Some(start_version) = attrs.get(END_VERSION) { return Some(match start_version { syn::Lit::Int(lit_int) => lit_int.base10_parse().unwrap(), _ => panic!("Field start/end version number must be an integer"), }); } None } // Returns an attribute hash_map constructed by processing a vector of syn::Attribute. pub(crate) fn parse_field_attributes(attributes: &[syn::Attribute]) -> HashMap { let mut attrs = HashMap::new(); for nested_attr in attributes .iter() .flat_map(|attr| -> Result, ()> { if !attr.path.is_ident(ATTRIBUTE_NAME) { return Ok(Vec::new()); } if let Ok(syn::Meta::List(meta)) = attr.parse_meta() { return Ok(meta.nested.into_iter().collect()); } Ok(Vec::new()) }) .flatten() { if let syn::NestedMeta::Meta(syn::Meta::NameValue(attr_name_value)) = nested_attr { attrs.insert( attr_name_value.path.get_ident().unwrap().to_string(), attr_name_value.lit, ); } } attrs } // Compute current struct version by finding the latest field change version. pub(crate) fn compute_version(fields: &[T]) -> u16 where T: Exists, { let mut version = 0; for field in fields { version = max(version, max(field.start_version(), field.end_version())); } version } versionize_derive-0.1.5/src/lib.rs000064400000000000000000000224071046102023000152720ustar 00000000000000// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! Exports the `Versionize` derive proc macro that generates the Versionize //! trait implementation. //! //! Versionize generates serialization and deserialization code only for //! structures and enums. //! //! Supported primitives: u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, //! char, f32, f64, String, Vec, Arrays up to 32 elements, Box, //! Wrapping, Option, FamStructWrapper, and (T, U). //! //! Known issues and limitations: //! - Union serialization is not supported via the `Versionize` proc macro. //! - Implementing Versionize for non-repr(C) unions can result in undefined //! behaviour and MUST be avoided. //! - Versionize trait implementations for repr(C) unions must be backed by //! extensive testing. //! - Semantic serialization and deserialization is available only for structures. extern crate proc_macro; extern crate proc_macro2; extern crate quote; extern crate syn; mod common; mod descriptors; mod fields; mod helpers; use common::Descriptor; use descriptors::{enum_desc::EnumDescriptor, struct_desc::StructDescriptor}; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; pub(crate) const ATTRIBUTE_NAME: &str = "version"; /// Struct annotation constants. pub(crate) const DEFAULT_FN: &str = "default_fn"; pub(crate) const SEMANTIC_SER_FN: &str = "ser_fn"; pub(crate) const SEMANTIC_DE_FN: &str = "de_fn"; pub(crate) const START_VERSION: &str = "start"; pub(crate) const END_VERSION: &str = "end"; /// Generates serialization and deserialization code as an implementation of /// the `Versionize` trait. /// /// Different code paths are generated for each version of the structure or /// enum. There is no limit enforced on the maximum number of structure /// versions. /// /// ### Struct and enum requirements /// - all members or enum variants need to implement the `Versionize` trait /// - no generics are being used (this is currenly a limitation) /// /// ## Annotations /// /// To facilitate version tolerant serialization "history metadata" is attached /// to the structure or enum. This is done by using the `version` attribute in /// their definition. In the below example a new field is added to the /// structure starting with version 2: `#[version(start = 2)]`. /// /// ```ignore /// extern crate versionize; /// extern crate versionize_derive; /// use versionize::{Versionize, VersionizeError, VersionizeResult}; /// use versionize_derive::Versionize; /// /// #[derive(Versionize)] /// struct Test { /// a: u32, /// #[version(start = 2)] /// b: u8, /// } /// ``` /// /// Multiple version annotations can be defined for a field, like for example: /// `#[version(start = 2, end = 3)]`. Field was added in structure version 2 /// and removed in version 3. The generated code will attempt to (de)serialize /// this field only for version 2 of the structure. /// /// ### Supported field attributes and usage /// /// The `version` attribute accepts multiple key/value pairs to be specified in /// order to support versioning, semantic serialization and default values for /// fields. All of these are optional and a default behaviour is provided in /// their absence. /// /// #### default_fn /// /// Provides an initialization value for a field when deserializing from an /// older structure version which does not contain this field. If not specified /// the `Default` trait isused to initialize the field. /// /// ```ignore /// extern crate versionize; /// extern crate versionize_derive; /// use versionize::{Versionize, VersionizeError, VersionizeResult}; /// use versionize_derive::Versionize; /// /// #[derive(Versionize)] /// struct TestStruct { /// a: u32, /// #[version(start = 2, default_fn = "default_b")] /// b: u8, /// } /// /// impl TestStruct { /// fn default_b(_source_version: u16) -> u8 { /// 12u8 /// } /// } /// ``` /// /// The function name needs to be specified as a string and its prototype must /// take an u16 source version parameter and return a value of the same type as /// as the field. /// /// #### start/end /// /// Defines the field version lifetime. Fields can be added by specifing the /// start version of the structure when first defining them and can be later /// on removed from serialization logic by adding and end version. /// /// For example: `#[version(start = 2, end = 4)]`. The field would be present /// in the structure v2 and v3, but starting with v4 it would no longer be /// serialized or deserialized. /// /// Once a field is removed, it can never be added again in a future version. /// /// #### ser_fn /// * Not supported for enums. * /// /// Defines a semantic serialization function for a field. The function needs /// to be specified as a string and implemented as a method attached to /// the structure. The prototype of the function is /// `fn(&mut self, u16) -> VersionizeResult<()>`. /// /// If defined, the method is called when the field is skipped from /// serialization because it does not exist in the target version of the /// structure. Its implementation can perform any mutation of `self` or return /// an error to stop serialization. Intended usage is to implement semantic /// translation or semantic validations. /// /// ```ignore /// extern crate versionize; /// extern crate versionize_derive; /// use versionize::{Versionize, VersionizeError, VersionizeResult}; /// use versionize_derive::Versionize; /// /// #[derive(Versionize)] /// struct SomeStruct { /// some_u32: u32, /// #[version(start = 2, ser_fn = "ser_u16")] /// some_u16: u16, /// } /// /// impl SomeStruct { /// fn ser_u16(&mut self, target_version: u16) -> VersionizeResult<()> { /// self.some_u32 = self.some_u32 & self.some_u16 as u32; /// Ok(()) /// } /// } /// ``` /// /// #### de_fn /// * Not supported for enums. * /// /// Defines a semantic deserialization function for a field. The function needs /// to be specified as a string and implemented as a method attached to /// the structure. The prototype of the function is /// `fn(&mut self, u16) -> VersionizeResult<()>`. /// /// If defined, the method is called if the field is skipped from /// deserialization because it does not exist in the source version of the /// serialized structure. Its implementation can perform any mutation of `self` /// or return an error to stop deserialization. Intended usage is to implement /// semantic translation or semantic validations. /// /// Both `default_fn` and `de_fn` can be specified for a field. `default_fn` is /// always called first and `de_fn` last. /// /// ```ignore /// extern crate versionize; /// extern crate versionize_derive; /// use versionize::{Versionize, VersionizeError, VersionizeResult}; /// use versionize_derive::Versionize; /// /// #[derive(Clone, Versionize)] /// struct SomeStruct { /// some_u32: u32, /// #[version(start = 2, ser_fn = "ser_u16", de_fn = "de_u16")] /// some_u16: u16, /// } /// /// impl SomeStruct { /// fn ser_u16(&mut self, target_version: u16) -> VersionizeResult<()> { /// self.some_u32 = self.some_u32 & self.some_u16 as u32; /// Ok(()) /// } /// fn de_u16(&mut self, source_version: u16) -> VersionizeResult<()> { /// if source_version < 2 { /// self.some_u16 = (self.some_u32 & 0xFF) as u16; /// } /// Ok(()) /// } /// } /// ``` #[proc_macro_derive(Versionize, attributes(version))] pub fn impl_versionize(input: TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let ident = input.ident.clone(); let generics = input.generics.clone(); let descriptor: Box = match &input.data { syn::Data::Struct(data_struct) => { Box::new(StructDescriptor::new(data_struct, ident.clone())) } syn::Data::Enum(data_enum) => Box::new(EnumDescriptor::new(data_enum, ident.clone())), syn::Data::Union(_) => { return (quote! { compile_error!("Union serialization is not supported."); }) .into() } }; let version = descriptor.version(); let versioned_serializer = descriptor.generate_serializer(); let deserializer = descriptor.generate_deserializer(); let serializer = quote! { // Get the struct version for the input app_version. let version = version_map.get_type_version(app_version, ::type_id()); // We will use this copy to perform semantic serialization. let mut copy_of_self = self.clone(); match version { #versioned_serializer _ => panic!("Unknown {:?} version {}.", &::type_id(), version) } }; (quote! { impl Versionize for #ident #generics { fn serialize(&self, writer: &mut W, version_map: &VersionMap, app_version: u16) -> VersionizeResult<()> { #serializer Ok(()) } fn deserialize(mut reader: &mut R, version_map: &VersionMap, app_version: u16) -> VersionizeResult { #deserializer } // Returns struct current version. fn version() -> u16 { #version } } }).into() }