bytemuck_derive-1.10.2/.cargo_vcs_info.json0000644000000001440000000000100142750ustar { "git": { "sha1": "abbebe597e02ac0828bb987c73a3f037cd8d62b5" }, "path_in_vcs": "derive" }bytemuck_derive-1.10.2/Cargo.lock0000644000000021400000000000100122460ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "bytemuck_derive" version = "1.10.2" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "proc-macro2" version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "2.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" bytemuck_derive-1.10.2/Cargo.toml0000644000000023240000000000100122750ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.61" name = "bytemuck_derive" version = "1.10.2" authors = ["Lokathor "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "derive proc-macros for `bytemuck`" readme = "README.md" keywords = [ "transmute", "bytes", "casting", ] categories = [ "encoding", "no-std", ] license = "Zlib OR Apache-2.0 OR MIT" repository = "https://github.com/Lokathor/bytemuck" [lib] name = "bytemuck_derive" path = "src/lib.rs" proc-macro = true [[test]] name = "basic" path = "tests/basic.rs" [dependencies.proc-macro2] version = "1.0.60" [dependencies.quote] version = "1" [dependencies.syn] version = "2.0.1" [dev-dependencies] bytemuck_derive-1.10.2/Cargo.toml.orig000064400000000000000000000013371046102023000157610ustar 00000000000000[package] name = "bytemuck_derive" description = "derive proc-macros for `bytemuck`" version = "1.10.2" authors = ["Lokathor "] repository = "https://github.com/Lokathor/bytemuck" readme = "README.md" keywords = ["transmute", "bytes", "casting"] categories = ["encoding", "no-std"] edition = "2018" license = "Zlib OR Apache-2.0 OR MIT" rust-version = "1.61" #note(lokathor): do not publish with this set #resolver = "3" [lib] name = "bytemuck_derive" proc-macro = true [dependencies] # syn seems to have broken backwards compatibility in this version https://github.com/dtolnay/syn/issues/1194 syn = "2.0.1" quote = "1" proc-macro2 = "1.0.60" [dev-dependencies] bytemuck = { path = "../", features = ["derive"] } bytemuck_derive-1.10.2/LICENSE-APACHE000064400000000000000000000242361046102023000150210ustar 00000000000000Apache 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. bytemuck_derive-1.10.2/LICENSE-MIT000064400000000000000000000021261046102023000145230ustar 00000000000000MIT License Copyright (c) 2019 Daniel "Lokathor" Gee. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bytemuck_derive-1.10.2/LICENSE-ZLIB000064400000000000000000000015231046102023000146320ustar 00000000000000Copyright (c) 2019 Daniel "Lokathor" Gee. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. bytemuck_derive-1.10.2/README.md000064400000000000000000000001231046102023000143410ustar 00000000000000 # bytemuck_derive Derive macros for [bytemuck](https://docs.rs/bytemuck) traits. bytemuck_derive-1.10.2/changelog.md000064400000000000000000000065711046102023000153500ustar 00000000000000 ## `bytemuck_derive` changelog ## 1.10.2 * [Extend #[derive(TransparentWrapper)](https://github.com/Lokathor/bytemuck/pull/147) ## 1.10.1 * changes the derive macros to not use `transmute` size matching when checking fof padding in a type. instead, an actual assert is used in a const block. ## 1.10.0 * add support for deriving NoUninit on enums with fields. ## 1.9.2 * Removes the `resolver` key from the manifest. This breaks the build with cryptic error messages despite current docs vaguely saying otherwise. ## 1.9.1 * Fix the derive of CheckedBitPattern when used with a packed struct. The Debug impl did not account for possibly-unaligned fields. ## 1.9.0 * The crate now declares an MSRV, so updates going forward should be simpler. ## 1.8.1 * https://github.com/Lokathor/bytemuck/pull/287 ## 1.8 * [#257](https://github.com/Lokathor/bytemuck/pull/257): Allows deriving Zeroable on some enums. ## 1.7.1 * Adds the `bytemuck` attribute to the `NoUninit` derive, allowing it to be used when re-exported. ## 1.7.0 * Allow generics in `derive(ByteEq, ByteHash)` https://github.com/Lokathor/bytemuck/pull/219 ## 1.6.0 * This allows `CheckedBitPattern` to be derived for enums with fields. The repr must be one of the following: * `#[repr(C)]` * `#[repr(C, int)]` * `#[repr(int)]` * `#[repr(transparent)]` ## 1.5.0 * The `Zeroable` derive now allows custom bounds. See the rustdoc for an explanation. ## 1.4.1 * Move the `syn` dependency to use version 2. This should not affect the public API in any way. ## 1.4.0 * `ByteEq` and `ByteHash` derives will make `Eq` and `Hash` impls that treat the value as a `&[u8]` during equality checks and hashing. This provides a large codegen improvement for some types. * Derives of `repr(int)` enums should now accept byte literal values as the discriminant. ## 1.3.0 * Allow `repr(transparent)` to be used generically in `derive(Pod)`. ## 1.2.1 * Fixed a regression of the `align(N)` attribute that occurred during otherwise routine cleanup. ## 1.2.0 * Apparently our minimum required version of `syn` went up without anyone noticing for a while. Because of a bump in our `syn` requirements, we're also issuing this minor version bump in the `bytemuck_derive` crate. Because it's possible to *reduce* the minimum required version of a dep in only a patch release, I'm going to ratchet the required version of `syn` all the way up to "current" (1.0.99). If absolutely necessary we could probably reduce the minimum `syn` version again in a patch release for 1.2, but I don't want to play this dance too much so I'd rather make each jump as big as can possibly be. [Issue 122](https://github.com/Lokathor/bytemuck/issues/122). **Note:** While the core `bytemuck` crate continues to keep building on rustc-1.34.0, the `bytemuck_derive` crate is considered an opt-in bonus feature (which doesn't do anything you couldn't trivially do yourself) and so it does not support a specific MSRV. ## 1.1.1 * Adjusted the license files to use full files rather than symlinks. [PR](https://github.com/Lokathor/bytemuck/pull/118) The license is unchanged, just no more symlinks. ## 1.1.0 * Updated to work with `bytemuck-1.9.0` ## 1.0.1 * [yanchith](https://github.com/yanchith) fixed the derive checks code to make clippy more happy. [PR 45](https://github.com/Lokathor/bytemuck/pull/45) ## 1.0.0 * Initial stable release. bytemuck_derive-1.10.2/src/lib.rs000064400000000000000000000517671046102023000150110ustar 00000000000000//! Derive macros for [bytemuck](https://docs.rs/bytemuck) traits. extern crate proc_macro; mod traits; use proc_macro2::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput, Result}; use crate::traits::{ bytemuck_crate_name, AnyBitPattern, CheckedBitPattern, Contiguous, Derivable, NoUninit, Pod, TransparentWrapper, Zeroable, }; /// Derive the `Pod` trait for a struct /// /// The macro ensures that the struct follows all the the safety requirements /// for the `Pod` trait. /// /// The following constraints need to be satisfied for the macro to succeed /// /// - All fields in the struct must implement `Pod` /// - The struct must be `#[repr(C)]` or `#[repr(transparent)]` /// - The struct must not contain any padding bytes /// - The struct contains no generic parameters, if it is not /// `#[repr(transparent)]` /// /// ## Examples /// /// ```rust /// # use std::marker::PhantomData; /// # use bytemuck_derive::{Pod, Zeroable}; /// #[derive(Copy, Clone, Pod, Zeroable)] /// #[repr(C)] /// struct Test { /// a: u16, /// b: u16, /// } /// /// #[derive(Copy, Clone, Pod, Zeroable)] /// #[repr(transparent)] /// struct Generic { /// a: A, /// b: PhantomData, /// } /// ``` /// /// If the struct is generic, it must be `#[repr(transparent)]` also. /// /// ```compile_fail /// # use bytemuck::{Pod, Zeroable}; /// # use std::marker::PhantomData; /// #[derive(Copy, Clone, Pod, Zeroable)] /// #[repr(C)] // must be `#[repr(transparent)]` /// struct Generic { /// a: A, /// } /// ``` /// /// If the struct is generic and `#[repr(transparent)]`, then it is only `Pod` /// when all of its generics are `Pod`, not just its fields. /// /// ``` /// # use bytemuck::{Pod, Zeroable}; /// # use std::marker::PhantomData; /// #[derive(Copy, Clone, Pod, Zeroable)] /// #[repr(transparent)] /// struct Generic { /// a: A, /// b: PhantomData, /// } /// /// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData:: }); /// ``` /// /// ```compile_fail /// # use bytemuck::{Pod, Zeroable}; /// # use std::marker::PhantomData; /// # #[derive(Copy, Clone, Pod, Zeroable)] /// # #[repr(transparent)] /// # struct Generic { /// # a: A, /// # b: PhantomData, /// # } /// struct NotPod; /// /// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData:: }); /// ``` #[proc_macro_derive(Pod, attributes(bytemuck))] pub fn derive_pod(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!(input as DeriveInput)); proc_macro::TokenStream::from(expanded) } /// Derive the `AnyBitPattern` trait for a struct /// /// The macro ensures that the struct follows all the the safety requirements /// for the `AnyBitPattern` trait. /// /// The following constraints need to be satisfied for the macro to succeed /// /// - All fields in the struct must to implement `AnyBitPattern` #[proc_macro_derive(AnyBitPattern, attributes(bytemuck))] pub fn derive_anybitpattern( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!( input as DeriveInput )); proc_macro::TokenStream::from(expanded) } /// Derive the `Zeroable` trait for a type. /// /// The macro ensures that the type follows all the the safety requirements /// for the `Zeroable` trait. /// /// The following constraints need to be satisfied for the macro to succeed on a /// struct: /// /// - All fields in the struct must implement `Zeroable` /// /// The following constraints need to be satisfied for the macro to succeed on /// an enum: /// /// - The enum has an explicit `#[repr(Int)]`, `#[repr(C)]`, or `#[repr(C, /// Int)]`. /// - The enum has a variant with discriminant 0 (explicitly or implicitly). /// - All fields in the variant with discriminant 0 (if any) must implement /// `Zeroable` /// /// The macro always succeeds on unions. /// /// ## Example /// /// ```rust /// # use bytemuck_derive::{Zeroable}; /// #[derive(Copy, Clone, Zeroable)] /// #[repr(C)] /// struct Test { /// a: u16, /// b: u16, /// } /// ``` /// ```rust /// # use bytemuck_derive::{Zeroable}; /// #[derive(Copy, Clone, Zeroable)] /// #[repr(i32)] /// enum Values { /// A = 0, /// B = 1, /// C = 2, /// } /// #[derive(Clone, Zeroable)] /// #[repr(C)] /// enum Implicit { /// A(bool, u8, char), /// B(String), /// C(std::num::NonZeroU8), /// } /// ``` /// /// # Custom bounds /// /// Custom bounds for the derived `Zeroable` impl can be given using the /// `#[zeroable(bound = "")]` helper attribute. /// /// Using this attribute additionally opts-in to "perfect derive" semantics, /// where instead of adding bounds for each generic type parameter, bounds are /// added for each field's type. /// /// ## Examples /// /// ```rust /// # use bytemuck::Zeroable; /// # use std::marker::PhantomData; /// #[derive(Clone, Zeroable)] /// #[zeroable(bound = "")] /// struct AlwaysZeroable { /// a: PhantomData, /// } /// /// AlwaysZeroable::::zeroed(); /// ``` /// ```rust /// # use bytemuck::{Zeroable}; /// #[derive(Copy, Clone, Zeroable)] /// #[repr(u8)] /// #[zeroable(bound = "")] /// enum MyOption { /// None, /// Some(T), /// } /// /// assert!(matches!(MyOption::::zeroed(), MyOption::None)); /// ``` /// /// ```rust,compile_fail /// # use bytemuck::Zeroable; /// # use std::marker::PhantomData; /// #[derive(Clone, Zeroable)] /// #[zeroable(bound = "T: Copy")] /// struct ZeroableWhenTIsCopy { /// a: PhantomData, /// } /// /// ZeroableWhenTIsCopy::::zeroed(); /// ``` /// /// The restriction that all fields must be Zeroable is still applied, and this /// is enforced using the mentioned "perfect derive" semantics. /// /// ```rust /// # use bytemuck::Zeroable; /// #[derive(Clone, Zeroable)] /// #[zeroable(bound = "")] /// struct ZeroableWhenTIsZeroable { /// a: T, /// } /// ZeroableWhenTIsZeroable::::zeroed(); /// ``` /// /// ```rust,compile_fail /// # use bytemuck::Zeroable; /// # #[derive(Clone, Zeroable)] /// # #[zeroable(bound = "")] /// # struct ZeroableWhenTIsZeroable { /// # a: T, /// # } /// ZeroableWhenTIsZeroable::::zeroed(); /// ``` #[proc_macro_derive(Zeroable, attributes(bytemuck, zeroable))] pub fn derive_zeroable( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!(input as DeriveInput)); proc_macro::TokenStream::from(expanded) } /// Derive the `NoUninit` trait for a struct or enum /// /// The macro ensures that the type follows all the the safety requirements /// for the `NoUninit` trait. /// /// The following constraints need to be satisfied for the macro to succeed /// (the rest of the constraints are guaranteed by the `NoUninit` subtrait /// bounds, i.e. the type must be `Sized + Copy + 'static`): /// /// If applied to a struct: /// - All fields in the struct must implement `NoUninit` /// - The struct must be `#[repr(C)]` or `#[repr(transparent)]` /// - The struct must not contain any padding bytes /// - The struct must contain no generic parameters /// /// If applied to an enum: /// - The enum must be explicit `#[repr(Int)]`, `#[repr(C)]`, or both /// - If the enum has fields: /// - All fields must implement `NoUninit` /// - All variants must not contain any padding bytes /// - All variants must be of the the same size /// - There must be no padding bytes between the discriminant and any of the /// variant fields /// - The enum must contain no generic parameters #[proc_macro_derive(NoUninit, attributes(bytemuck))] pub fn derive_no_uninit( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!(input as DeriveInput)); proc_macro::TokenStream::from(expanded) } /// Derive the `CheckedBitPattern` trait for a struct or enum. /// /// The macro ensures that the type follows all the the safety requirements /// for the `CheckedBitPattern` trait and derives the required `Bits` type /// definition and `is_valid_bit_pattern` method for the type automatically. /// /// The following constraints need to be satisfied for the macro to succeed: /// /// If applied to a struct: /// - All fields must implement `CheckedBitPattern` /// - The struct must be `#[repr(C)]` or `#[repr(transparent)]` /// - The struct must contain no generic parameters /// /// If applied to an enum: /// - The enum must be explicit `#[repr(Int)]` /// - All fields in variants must implement `CheckedBitPattern` /// - The enum must contain no generic parameters #[proc_macro_derive(CheckedBitPattern)] pub fn derive_maybe_pod( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!( input as DeriveInput )); proc_macro::TokenStream::from(expanded) } /// Derive the `TransparentWrapper` trait for a struct /// /// The macro ensures that the struct follows all the the safety requirements /// for the `TransparentWrapper` trait. /// /// The following constraints need to be satisfied for the macro to succeed /// /// - The struct must be `#[repr(transparent)]` /// - The struct must contain the `Wrapped` type /// - Any ZST fields must be [`Zeroable`][derive@Zeroable]. /// /// If the struct only contains a single field, the `Wrapped` type will /// automatically be determined. If there is more then one field in the struct, /// you need to specify the `Wrapped` type using `#[transparent(T)]`. Due to /// technical limitations, the type in the `#[transparent(Type)]` needs to be /// the exact same token sequence as the corresponding type in the struct /// definition. /// /// ## Examples /// /// ```rust /// # use bytemuck_derive::TransparentWrapper; /// # use std::marker::PhantomData; /// #[derive(Copy, Clone, TransparentWrapper)] /// #[repr(transparent)] /// #[transparent(u16)] /// struct Test { /// inner: u16, /// extra: PhantomData, /// } /// ``` /// /// If the struct contains more than one field, the `Wrapped` type must be /// explicitly specified. /// /// ```rust,compile_fail /// # use bytemuck_derive::TransparentWrapper; /// # use std::marker::PhantomData; /// #[derive(Copy, Clone, TransparentWrapper)] /// #[repr(transparent)] /// // missing `#[transparent(u16)]` /// struct Test { /// inner: u16, /// extra: PhantomData, /// } /// ``` /// /// Any ZST fields must be `Zeroable`. /// /// ```rust,compile_fail /// # use bytemuck_derive::TransparentWrapper; /// # use std::marker::PhantomData; /// struct NonTransparentSafeZST; /// /// #[derive(TransparentWrapper)] /// #[repr(transparent)] /// #[transparent(u16)] /// struct Test { /// inner: u16, /// extra: PhantomData, /// another_extra: NonTransparentSafeZST, // not `Zeroable` /// } /// ``` #[proc_macro_derive(TransparentWrapper, attributes(bytemuck, transparent))] pub fn derive_transparent( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!( input as DeriveInput )); proc_macro::TokenStream::from(expanded) } /// Derive the `Contiguous` trait for an enum /// /// The macro ensures that the enum follows all the the safety requirements /// for the `Contiguous` trait. /// /// The following constraints need to be satisfied for the macro to succeed /// /// - The enum must be `#[repr(Int)]` /// - The enum must be fieldless /// - The enum discriminants must form a contiguous range /// /// ## Example /// /// ```rust /// # use bytemuck_derive::{Contiguous}; /// /// #[derive(Copy, Clone, Contiguous)] /// #[repr(u8)] /// enum Test { /// A = 0, /// B = 1, /// C = 2, /// } /// ``` #[proc_macro_derive(Contiguous)] pub fn derive_contiguous( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let expanded = derive_marker_trait::(parse_macro_input!(input as DeriveInput)); proc_macro::TokenStream::from(expanded) } /// Derive the `PartialEq` and `Eq` trait for a type /// /// The macro implements `PartialEq` and `Eq` by casting both sides of the /// comparison to a byte slice and then compares those. /// /// ## Warning /// /// Since this implements a byte wise comparison, the behavior of floating point /// numbers does not match their usual comparison behavior. Additionally other /// custom comparison behaviors of the individual fields are also ignored. This /// also does not implement `StructuralPartialEq` / `StructuralEq` like /// `PartialEq` / `Eq` would. This means you can't pattern match on the values. /// /// ## Examples /// /// ```rust /// # use bytemuck_derive::{ByteEq, NoUninit}; /// #[derive(Copy, Clone, NoUninit, ByteEq)] /// #[repr(C)] /// struct Test { /// a: u32, /// b: char, /// c: f32, /// } /// ``` /// /// ```rust /// # use bytemuck_derive::ByteEq; /// # use bytemuck::NoUninit; /// #[derive(Copy, Clone, ByteEq)] /// #[repr(C)] /// struct Test { /// a: [u32; N], /// } /// unsafe impl NoUninit for Test {} /// ``` #[proc_macro_derive(ByteEq)] pub fn derive_byte_eq( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let crate_name = bytemuck_crate_name(&input); let ident = input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); proc_macro::TokenStream::from(quote! { impl #impl_generics ::core::cmp::PartialEq for #ident #ty_generics #where_clause { #[inline] #[must_use] fn eq(&self, other: &Self) -> bool { #crate_name::bytes_of(self) == #crate_name::bytes_of(other) } } impl #impl_generics ::core::cmp::Eq for #ident #ty_generics #where_clause { } }) } /// Derive the `Hash` trait for a type /// /// The macro implements `Hash` by casting the value to a byte slice and hashing /// that. /// /// ## Warning /// /// The hash does not match the standard library's `Hash` derive. /// /// ## Examples /// /// ```rust /// # use bytemuck_derive::{ByteHash, NoUninit}; /// #[derive(Copy, Clone, NoUninit, ByteHash)] /// #[repr(C)] /// struct Test { /// a: u32, /// b: char, /// c: f32, /// } /// ``` /// /// ```rust /// # use bytemuck_derive::ByteHash; /// # use bytemuck::NoUninit; /// #[derive(Copy, Clone, ByteHash)] /// #[repr(C)] /// struct Test { /// a: [u32; N], /// } /// unsafe impl NoUninit for Test {} /// ``` #[proc_macro_derive(ByteHash)] pub fn derive_byte_hash( input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let crate_name = bytemuck_crate_name(&input); let ident = input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); proc_macro::TokenStream::from(quote! { impl #impl_generics ::core::hash::Hash for #ident #ty_generics #where_clause { #[inline] fn hash(&self, state: &mut H) { ::core::hash::Hash::hash_slice(#crate_name::bytes_of(self), state) } #[inline] fn hash_slice(data: &[Self], state: &mut H) { ::core::hash::Hash::hash_slice(#crate_name::cast_slice::<_, u8>(data), state) } } }) } /// Basic wrapper for error handling fn derive_marker_trait(input: DeriveInput) -> TokenStream { derive_marker_trait_inner::(input) .unwrap_or_else(|err| err.into_compile_error()) } /// Find `#[name(key = "value")]` helper attributes on the struct, and return /// their `"value"`s parsed with `parser`. /// /// Returns an error if any attributes with the given `name` do not match the /// expected format. Returns `Ok([])` if no attributes with `name` are found. fn find_and_parse_helper_attributes( attributes: &[syn::Attribute], name: &str, key: &str, parser: P, example_value: &str, invalid_value_msg: &str, ) -> Result> { let invalid_format_msg = format!("{name} attribute must be `{name}({key} = \"{example_value}\")`",); let values_to_check = attributes.iter().filter_map(|attr| match &attr.meta { // If a `Path` matches our `name`, return an error, else ignore it. // e.g. `#[zeroable]` syn::Meta::Path(path) => path .is_ident(name) .then(|| Err(syn::Error::new_spanned(path, &invalid_format_msg))), // If a `NameValue` matches our `name`, return an error, else ignore it. // e.g. `#[zeroable = "hello"]` syn::Meta::NameValue(namevalue) => { namevalue.path.is_ident(name).then(|| { Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg)) }) } // If a `List` matches our `name`, match its contents to our format, else // ignore it. If its contents match our format, return the value, else // return an error. syn::Meta::List(list) => list.path.is_ident(name).then(|| { let namevalue: syn::MetaNameValue = syn::parse2(list.tokens.clone()) .map_err(|_| { syn::Error::new_spanned(&list.tokens, &invalid_format_msg) })?; if namevalue.path.is_ident(key) { match namevalue.value { syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(strlit), .. }) => Ok(strlit), _ => { Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg)) } } } else { Err(syn::Error::new_spanned(&namevalue.path, &invalid_format_msg)) } }), }); // Parse each value found with the given parser, and return them if no errors // occur. values_to_check .map(|lit| { let lit = lit?; lit.parse_with(parser).map_err(|err| { syn::Error::new_spanned(&lit, format!("{invalid_value_msg}: {err}")) }) }) .collect() } fn derive_marker_trait_inner( mut input: DeriveInput, ) -> Result { let crate_name = bytemuck_crate_name(&input); let trait_ = Trait::ident(&input, &crate_name)?; // If this trait allows explicit bounds, and any explicit bounds were given, // then use those explicit bounds. Else, apply the default bounds (bound // each generic type on this trait). if let Some(name) = Trait::explicit_bounds_attribute_name() { // See if any explicit bounds were given in attributes. let explicit_bounds = find_and_parse_helper_attributes( &input.attrs, name, "bound", >::parse_terminated, "Type: Trait", "invalid where predicate", )?; if !explicit_bounds.is_empty() { // Explicit bounds were given. // Enforce explicitly given bounds, and emit "perfect derive" (i.e. add // bounds for each field's type). let explicit_bounds = explicit_bounds .into_iter() .flatten() .collect::>(); let fields = match (Trait::perfect_derive_fields(&input), &input.data) { (Some(fields), _) => fields, (None, syn::Data::Struct(syn::DataStruct { fields, .. })) => { fields.clone() } (None, syn::Data::Union(_)) => { return Err(syn::Error::new_spanned( trait_, &"perfect derive is not supported for unions", )); } (None, syn::Data::Enum(_)) => { return Err(syn::Error::new_spanned( trait_, &"perfect derive is not supported for enums", )); } }; let predicates = &mut input.generics.make_where_clause().predicates; predicates.extend(explicit_bounds); for field in fields { let ty = field.ty; predicates.push(syn::parse_quote!( #ty: #trait_ )); } } else { // No explicit bounds were given. // Enforce trait bound on all type generics. add_trait_marker(&mut input.generics, &trait_); } } else { // This trait does not allow explicit bounds. // Enforce trait bound on all type generics. add_trait_marker(&mut input.generics, &trait_); } let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); Trait::check_attributes(&input.data, &input.attrs)?; let asserts = Trait::asserts(&input, &crate_name)?; let (trait_impl_extras, trait_impl) = Trait::trait_impl(&input, &crate_name)?; let implies_trait = if let Some(implies_trait) = Trait::implies_trait(&crate_name) { quote!(unsafe impl #impl_generics #implies_trait for #name #ty_generics #where_clause {}) } else { quote!() }; let where_clause = if Trait::requires_where_clause() { where_clause } else { None }; Ok(quote! { #asserts #trait_impl_extras unsafe impl #impl_generics #trait_ for #name #ty_generics #where_clause { #trait_impl } #implies_trait }) } /// Add a trait marker to the generics if it is not already present fn add_trait_marker(generics: &mut syn::Generics, trait_name: &syn::Path) { // Get each generic type parameter. let type_params = generics .type_params() .map(|param| ¶m.ident) .map(|param| { syn::parse_quote!( #param: #trait_name ) }) .collect::>(); generics.make_where_clause().predicates.extend(type_params); } bytemuck_derive-1.10.2/src/traits.rs000064400000000000000000001473351046102023000155460ustar 00000000000000#![allow(unused_imports)] use std::{cmp, convert::TryFrom}; use proc_macro2::{Ident, Span, TokenStream, TokenTree}; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream, Parser}, punctuated::Punctuated, spanned::Spanned, Result, *, }; macro_rules! bail { ($msg:expr $(,)?) => { return Err(Error::new(Span::call_site(), &$msg[..])) }; ( $msg:expr => $span_to_blame:expr $(,)? ) => { return Err(Error::new_spanned(&$span_to_blame, $msg)) }; } pub trait Derivable { fn ident(input: &DeriveInput, crate_name: &TokenStream) -> Result; fn implies_trait(_crate_name: &TokenStream) -> Option { None } fn asserts( _input: &DeriveInput, _crate_name: &TokenStream, ) -> Result { Ok(quote!()) } fn check_attributes(_ty: &Data, _attributes: &[Attribute]) -> Result<()> { Ok(()) } fn trait_impl( _input: &DeriveInput, _crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { Ok((quote!(), quote!())) } fn requires_where_clause() -> bool { true } fn explicit_bounds_attribute_name() -> Option<&'static str> { None } /// If this trait has a custom meaning for "perfect derive", this function /// should be overridden to return `Some`. /// /// The default is "the fields of a struct; unions and enums not supported". fn perfect_derive_fields(_input: &DeriveInput) -> Option { None } } pub struct Pod; impl Derivable for Pod { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::Pod)) } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { let repr = get_repr(&input.attrs)?; let completly_packed = repr.packed == Some(1) || repr.repr == Repr::Transparent; if !completly_packed && !input.generics.params.is_empty() { bail!("\ Pod requires cannot be derived for non-packed types containing \ generic parameters because the padding requirements can't be verified \ for generic non-packed structs\ " => input.generics.params.first().unwrap()); } match &input.data { Data::Struct(_) => { let assert_no_padding = if !completly_packed { Some(generate_assert_no_padding(input, None, "Pod")?) } else { None }; let assert_fields_are_pod = generate_fields_are_trait( input, None, Self::ident(input, crate_name)?, )?; Ok(quote!( #assert_no_padding #assert_fields_are_pod )) } Data::Enum(_) => bail!("Deriving Pod is not supported for enums"), Data::Union(_) => bail!("Deriving Pod is not supported for unions"), } } fn check_attributes(_ty: &Data, attributes: &[Attribute]) -> Result<()> { let repr = get_repr(attributes)?; match repr.repr { Repr::C => Ok(()), Repr::Transparent => Ok(()), _ => { bail!("Pod requires the type to be #[repr(C)] or #[repr(transparent)]") } } } } pub struct AnyBitPattern; impl Derivable for AnyBitPattern { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::AnyBitPattern)) } fn implies_trait(crate_name: &TokenStream) -> Option { Some(quote!(#crate_name::Zeroable)) } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { match &input.data { Data::Union(_) => Ok(quote!()), // unions are always `AnyBitPattern` Data::Struct(_) => { generate_fields_are_trait(input, None, Self::ident(input, crate_name)?) } Data::Enum(_) => { bail!("Deriving AnyBitPattern is not supported for enums") } } } } pub struct Zeroable; /// Helper function to get the variant with discriminant zero (implicit or /// explicit). fn get_zero_variant(enum_: &DataEnum) -> Result> { let iter = VariantDiscriminantIterator::new(enum_.variants.iter()); let mut zero_variant = None; for res in iter { let (discriminant, variant) = res?; if discriminant == 0 { zero_variant = Some(variant); break; } } Ok(zero_variant) } impl Derivable for Zeroable { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::Zeroable)) } fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> { let repr = get_repr(attributes)?; match ty { Data::Struct(_) => Ok(()), Data::Enum(_) => { if !matches!( repr.repr, Repr::C | Repr::Integer(_) | Repr::CWithDiscriminant(_) ) { bail!("Zeroable requires the enum to be an explicit #[repr(Int)] and/or #[repr(C)]") } // We ensure there is a zero variant in `asserts`, since it is needed // there anyway. Ok(()) } Data::Union(_) => Ok(()), } } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { match &input.data { Data::Union(_) => Ok(quote!()), // unions are always `Zeroable` Data::Struct(_) => { generate_fields_are_trait(input, None, Self::ident(input, crate_name)?) } Data::Enum(enum_) => { let zero_variant = get_zero_variant(enum_)?; if zero_variant.is_none() { bail!("No variant's discriminant is 0") }; generate_fields_are_trait( input, zero_variant, Self::ident(input, crate_name)?, ) } } } fn explicit_bounds_attribute_name() -> Option<&'static str> { Some("zeroable") } fn perfect_derive_fields(input: &DeriveInput) -> Option { match &input.data { Data::Struct(struct_) => Some(struct_.fields.clone()), Data::Enum(enum_) => { // We handle `Err` returns from `get_zero_variant` in `asserts`, so it's // fine to just ignore them here and return `None`. // Otherwise, we clone the `fields` of the zero variant (if any). Some(get_zero_variant(enum_).ok()??.fields.clone()) } Data::Union(_) => None, } } } pub struct NoUninit; impl Derivable for NoUninit { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::NoUninit)) } fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> { let repr = get_repr(attributes)?; match ty { Data::Struct(_) => match repr.repr { Repr::C | Repr::Transparent => Ok(()), _ => bail!("NoUninit requires the struct to be #[repr(C)] or #[repr(transparent)]"), }, Data::Enum(DataEnum { variants,.. }) => { if !enum_has_fields(variants.iter()) { if matches!(repr.repr, Repr::C | Repr::Integer(_)) { Ok(()) } else { bail!("NoUninit requires the enum to be #[repr(C)] or #[repr(Int)]") } } else if matches!(repr.repr, Repr::Rust) { bail!("NoUninit requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout") } else { Ok(()) } }, Data::Union(_) => bail!("NoUninit can only be derived on enums and structs") } } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { if !input.generics.params.is_empty() { bail!("NoUninit cannot be derived for structs containing generic parameters because the padding requirements can't be verified for generic structs"); } match &input.data { Data::Struct(DataStruct { .. }) => { let assert_no_padding = generate_assert_no_padding(&input, None, "NoUninit")?; let assert_fields_are_no_padding = generate_fields_are_trait( &input, None, Self::ident(input, crate_name)?, )?; Ok(quote!( #assert_no_padding #assert_fields_are_no_padding )) } Data::Enum(DataEnum { variants, .. }) => { if enum_has_fields(variants.iter()) { // There are two different C representations for enums with fields: // There's `#[repr(C)]`/`[repr(C, int)]` and `#[repr(int)]`. // `#[repr(C)]` is equivalent to a struct containing the discriminant // and a union of structs representing each variant's fields. // `#[repr(int)]` is equivalent to a union containing structs of the // discriminant and the fields. // // See https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.c.adt // and https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.primitive.adt // // In practice the only difference between the two is whether and // where padding bytes are placed. For `#[repr(C)]` enums, the first // enum fields of all variants start at the same location (the first // byte in the union). For `#[repr(int)]` enums, the structs // representing each variant are layed out individually and padding // does not depend on other variants, but only on the size of the // discriminant and the alignment of the first field. The location of // the first field might differ between variants, potentially // resulting in less padding or padding placed later in the enum. // // The `NoUninit` derive macro asserts that no padding exists by // removing all padding with `#[repr(packed)]` and checking that this // doesn't change the size. Since the location and presence of // padding bytes is the only difference between the two // representations and we're removing all padding bytes, the resuling // layout would identical for both representations. This means that // we can just pick one of the representations and don't have to // implement desugaring for both. We chose to implement the // desugaring for `#[repr(int)]`. let enum_discriminant = generate_enum_discriminant(input)?; let variant_assertions = variants .iter() .map(|variant| { let assert_no_padding = generate_assert_no_padding(&input, Some(variant), "NoUninit")?; let assert_fields_are_no_padding = generate_fields_are_trait( &input, Some(variant), Self::ident(input, crate_name)?, )?; Ok(quote!( #assert_no_padding #assert_fields_are_no_padding )) }) .collect::>>()?; Ok(quote! { const _: () = { #enum_discriminant #(#variant_assertions)* }; }) } else { Ok(quote!()) } } Data::Union(_) => bail!("NoUninit cannot be derived for unions"), /* shouldn't be possible since we already error in attribute check for this case */ } } fn trait_impl( _input: &DeriveInput, _crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { Ok((quote!(), quote!())) } } pub struct CheckedBitPattern; impl Derivable for CheckedBitPattern { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::CheckedBitPattern)) } fn check_attributes(ty: &Data, attributes: &[Attribute]) -> Result<()> { let repr = get_repr(attributes)?; match ty { Data::Struct(_) => match repr.repr { Repr::C | Repr::Transparent => Ok(()), _ => bail!("CheckedBitPattern derive requires the struct to be #[repr(C)] or #[repr(transparent)]"), }, Data::Enum(DataEnum { variants,.. }) => { if !enum_has_fields(variants.iter()){ if matches!(repr.repr, Repr::C | Repr::Integer(_)) { Ok(()) } else { bail!("CheckedBitPattern requires the enum to be #[repr(C)] or #[repr(Int)]") } } else if matches!(repr.repr, Repr::Rust) { bail!("CheckedBitPattern requires an explicit repr annotation because `repr(Rust)` doesn't have a specified type layout") } else { Ok(()) } } Data::Union(_) => bail!("CheckedBitPattern can only be derived on enums and structs") } } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { if !input.generics.params.is_empty() { bail!("CheckedBitPattern cannot be derived for structs containing generic parameters"); } match &input.data { Data::Struct(DataStruct { .. }) => { let assert_fields_are_maybe_pod = generate_fields_are_trait( &input, None, Self::ident(input, crate_name)?, )?; Ok(assert_fields_are_maybe_pod) } // nothing needed, already guaranteed OK by NoUninit. Data::Enum(_) => Ok(quote!()), Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), /* shouldn't be possible since we already error in attribute check for this case */ } } fn trait_impl( input: &DeriveInput, crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { match &input.data { Data::Struct(DataStruct { fields, .. }) => { generate_checked_bit_pattern_struct( &input.ident, fields, &input.attrs, crate_name, ) } Data::Enum(DataEnum { variants, .. }) => { generate_checked_bit_pattern_enum(input, variants, crate_name) } Data::Union(_) => bail!("Internal error in CheckedBitPattern derive"), /* shouldn't be possible since we already error in attribute check for this case */ } } } pub struct TransparentWrapper; struct WrappedType { wrapped_type: syn::Type, /// Was the type given with a #[transparent(Type)] attribute. explicit: bool, } impl TransparentWrapper { fn get_wrapped_type( attributes: &[Attribute], fields: &Fields, ) -> Option { let transparent_param = get_type_from_simple_attr(attributes, "transparent") .map(|wrapped_type| WrappedType { wrapped_type, explicit: true }); transparent_param.or_else(|| { let mut types = get_field_types(&fields); let first_type = types.next(); if let Some(_) = types.next() { // can't guess param type if there is more than one field return None; } else { first_type .cloned() .map(|wrapped_type| WrappedType { wrapped_type, explicit: false }) } }) } } impl Derivable for TransparentWrapper { fn ident(input: &DeriveInput, crate_name: &TokenStream) -> Result { let fields = get_struct_fields(input)?; let WrappedType { wrapped_type: ty, .. } = match Self::get_wrapped_type(&input.attrs, &fields) { Some(ty) => ty, None => bail!("when deriving TransparentWrapper for a struct with more \ than one field, you need to specify the transparent field \ using #[transparent(T)]"), }; Ok(syn::parse_quote!(#crate_name::TransparentWrapper<#ty>)) } fn asserts( input: &DeriveInput, crate_name: &TokenStream, ) -> Result { let (impl_generics, _ty_generics, where_clause) = input.generics.split_for_impl(); let fields = get_struct_fields(input)?; let (wrapped_type, explicit) = match Self::get_wrapped_type(&input.attrs, &fields) { Some(WrappedType { wrapped_type, explicit }) => { (wrapped_type.to_token_stream().to_string(), explicit) } None => unreachable!(), /* other code will already reject this derive */ }; let mut wrapped_field_ty = None; let mut nonwrapped_field_tys = vec![]; for field in fields.iter() { let field_ty = &field.ty; if field_ty.to_token_stream().to_string() == wrapped_type { if wrapped_field_ty.is_some() { if explicit { bail!("TransparentWrapper must have one field of the wrapped type. \ The type given in `#[transparent(Type)]` must match tokenwise \ with the type in the struct definition, not just be the same type. \ You may be able to use a type alias to work around this limitation."); } else { bail!("TransparentWrapper must have one field of the wrapped type"); } } wrapped_field_ty = Some(field_ty); } else { nonwrapped_field_tys.push(field_ty); } } if let Some(wrapped_field_ty) = wrapped_field_ty { Ok(quote!( const _: () = { #[repr(transparent)] #[allow(clippy::multiple_bound_locations)] struct AssertWrappedIsWrapped #impl_generics((u8, ::core::marker::PhantomData<#wrapped_field_ty>), #(#nonwrapped_field_tys),*) #where_clause; fn assert_zeroable() {} #[allow(clippy::multiple_bound_locations)] fn check #impl_generics () #where_clause { #( assert_zeroable::<#nonwrapped_field_tys>(); )* } }; )) } else { bail!("TransparentWrapper must have one field of the wrapped type") } } fn check_attributes(_ty: &Data, attributes: &[Attribute]) -> Result<()> { let repr = get_repr(attributes)?; match repr.repr { Repr::Transparent => Ok(()), _ => { bail!( "TransparentWrapper requires the struct to be #[repr(transparent)]" ) } } } fn requires_where_clause() -> bool { false } } pub struct Contiguous; impl Derivable for Contiguous { fn ident(_: &DeriveInput, crate_name: &TokenStream) -> Result { Ok(syn::parse_quote!(#crate_name::Contiguous)) } fn trait_impl( input: &DeriveInput, _crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { let repr = get_repr(&input.attrs)?; let integer_ty = if let Some(integer_ty) = repr.repr.as_integer() { integer_ty } else { bail!("Contiguous requires the enum to be #[repr(Int)]"); }; let variants = get_enum_variants(input)?; if enum_has_fields(variants.clone()) { return Err(Error::new_spanned( &input, "Only fieldless enums are supported", )); } let mut variants_with_discriminant = VariantDiscriminantIterator::new(variants); let (min, max, count) = variants_with_discriminant.try_fold( (i128::MAX, i128::MIN, 0), |(min, max, count), res| { let (discriminant, _variant) = res?; Ok::<_, Error>(( i128::min(min, discriminant), i128::max(max, discriminant), count + 1, )) }, )?; if max - min != count - 1 { bail! { "Contiguous requires the enum discriminants to be contiguous", } } let min_lit = LitInt::new(&format!("{}", min), input.span()); let max_lit = LitInt::new(&format!("{}", max), input.span()); // `from_integer` and `into_integer` are usually provided by the trait's // default implementation. We override this implementation because it // goes through `transmute_copy`, which can lead to inefficient assembly as seen in https://github.com/Lokathor/bytemuck/issues/175 . Ok(( quote!(), quote! { type Int = #integer_ty; #[allow(clippy::missing_docs_in_private_items)] const MIN_VALUE: #integer_ty = #min_lit; #[allow(clippy::missing_docs_in_private_items)] const MAX_VALUE: #integer_ty = #max_lit; #[inline] fn from_integer(value: Self::Int) -> Option { #[allow(clippy::manual_range_contains)] if Self::MIN_VALUE <= value && value <= Self::MAX_VALUE { Some(unsafe { ::core::mem::transmute(value) }) } else { None } } #[inline] fn into_integer(self) -> Self::Int { self as #integer_ty } }, )) } } fn get_struct_fields(input: &DeriveInput) -> Result<&Fields> { if let Data::Struct(DataStruct { fields, .. }) = &input.data { Ok(fields) } else { bail!("deriving this trait is only supported for structs") } } /// Extract the `Fields` off a `DeriveInput`, or, in the `enum` case, off /// those of the `enum_variant`, when provided (e.g., for `Zeroable`). /// /// We purposely allow not providing an `enum_variant` for cases where /// the caller wants to reject supporting `enum`s (e.g., `NoPadding`). fn get_fields( input: &DeriveInput, enum_variant: Option<&Variant>, ) -> Result { match &input.data { Data::Struct(DataStruct { fields, .. }) => Ok(fields.clone()), Data::Union(DataUnion { fields, .. }) => Ok(Fields::Named(fields.clone())), Data::Enum(_) => match enum_variant { Some(variant) => Ok(variant.fields.clone()), None => bail!("deriving this trait is not supported for enums"), }, } } fn get_enum_variants<'a>( input: &'a DeriveInput, ) -> Result + Clone + 'a> { if let Data::Enum(DataEnum { variants, .. }) = &input.data { Ok(variants.iter()) } else { bail!("deriving this trait is only supported for enums") } } fn get_field_types<'a>( fields: &'a Fields, ) -> impl Iterator + 'a { fields.iter().map(|field| &field.ty) } fn generate_checked_bit_pattern_struct( input_ident: &Ident, fields: &Fields, attrs: &[Attribute], crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { let bits_ty = Ident::new(&format!("{}Bits", input_ident), input_ident.span()); let repr = get_repr(attrs)?; let field_names = fields .iter() .enumerate() .map(|(i, field)| { field.ident.clone().unwrap_or_else(|| { Ident::new(&format!("field{}", i), input_ident.span()) }) }) .collect::>(); let field_tys = fields.iter().map(|field| &field.ty).collect::>(); let field_name = &field_names[..]; let field_ty = &field_tys[..]; Ok(( quote! { #[doc = #GENERATED_TYPE_DOCUMENTATION] #repr #[derive(Clone, Copy, #crate_name::AnyBitPattern)] #[allow(missing_docs)] pub struct #bits_ty { #(#field_name: <#field_ty as #crate_name::CheckedBitPattern>::Bits,)* } #[allow(unexpected_cfgs)] const _: () = { #[cfg(not(target_arch = "spirv"))] impl ::core::fmt::Debug for #bits_ty { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty)); #(::core::fmt::DebugStruct::field(&mut debug_struct, ::core::stringify!(#field_name), &{ self.#field_name });)* ::core::fmt::DebugStruct::finish(&mut debug_struct) } } }; }, quote! { type Bits = #bits_ty; #[inline] #[allow(clippy::double_comparisons, unused)] fn is_valid_bit_pattern(bits: &#bits_ty) -> bool { #(<#field_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(&{ bits.#field_name }) && )* true } }, )) } fn generate_checked_bit_pattern_enum( input: &DeriveInput, variants: &Punctuated, crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { if enum_has_fields(variants.iter()) { generate_checked_bit_pattern_enum_with_fields(input, variants, crate_name) } else { generate_checked_bit_pattern_enum_without_fields( input, variants, crate_name, ) } } fn generate_checked_bit_pattern_enum_without_fields( input: &DeriveInput, variants: &Punctuated, crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { let span = input.span(); let mut variants_with_discriminant = VariantDiscriminantIterator::new(variants.iter()); let (min, max, count) = variants_with_discriminant.try_fold( (i128::MAX, i128::MIN, 0), |(min, max, count), res| { let (discriminant, _variant) = res?; Ok::<_, Error>(( i128::min(min, discriminant), i128::max(max, discriminant), count + 1, )) }, )?; let check = if count == 0 { quote!(false) } else if max - min == count - 1 { // contiguous range let min_lit = LitInt::new(&format!("{}", min), span); let max_lit = LitInt::new(&format!("{}", max), span); quote!(*bits >= #min_lit && *bits <= #max_lit) } else { // not contiguous range, check for each let variant_discriminant_lits = VariantDiscriminantIterator::new(variants.iter()) .map(|res| { let (discriminant, _variant) = res?; Ok(LitInt::new(&format!("{}", discriminant), span)) }) .collect::>>()?; // count is at least 1 let first = &variant_discriminant_lits[0]; let rest = &variant_discriminant_lits[1..]; quote!(matches!(*bits, #first #(| #rest )*)) }; let (integer, defs) = get_enum_discriminant(input, crate_name)?; Ok(( quote!(#defs), quote! { type Bits = #integer; #[inline] #[allow(clippy::double_comparisons)] fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { #check } }, )) } fn generate_checked_bit_pattern_enum_with_fields( input: &DeriveInput, variants: &Punctuated, crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { let representation = get_repr(&input.attrs)?; let vis = &input.vis; match representation.repr { Repr::Rust => unreachable!(), Repr::C | Repr::CWithDiscriminant(_) => { let (integer, defs) = get_enum_discriminant(input, crate_name)?; let input_ident = &input.ident; let bits_repr = Representation { repr: Repr::C, ..representation }; // the enum manually re-configured as the actual tagged union it // represents, thus circumventing the requirements rust imposes on // the tag even when using #[repr(C)] enum layout // see: https://doc.rust-lang.org/reference/type-layout.html#reprc-enums-with-fields let bits_ty_ident = Ident::new(&format!("{input_ident}Bits"), input.span()); // the variants union part of the tagged union. These get put into a union // which gets the AnyBitPattern derive applied to it, thus checking // that the fields of the union obey the requriements of AnyBitPattern. // The types that actually go in the union are one more level of // indirection deep: we generate new structs for each variant // (`variant_struct_definitions`) which themselves have the // `CheckedBitPattern` derive applied, thus generating // `{variant_struct_ident}Bits` structs, which are the ones that go // into this union. let variants_union_ident = Ident::new(&format!("{}Variants", input.ident), input.span()); let variant_struct_idents = variants.iter().map(|v| { Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span()) }); let variant_struct_definitions = variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| { let fields = v.fields.iter().map(|v| &v.ty); quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)] #[repr(C)] #vis struct #variant_struct_ident(#(#fields),*); } }); let union_fields = variant_struct_idents .clone() .zip(variants.iter()) .map(|(variant_struct_ident, v)| { let variant_struct_bits_ident = Ident::new(&format!("{variant_struct_ident}Bits"), input.span()); let field_ident = &v.ident; quote! { #field_ident: #variant_struct_bits_ident } }); let variant_checks = variant_struct_idents .clone() .zip(VariantDiscriminantIterator::new(variants.iter())) .zip(variants.iter()) .map(|((variant_struct_ident, discriminant), v)| -> Result<_> { let (discriminant, _variant) = discriminant?; let discriminant = LitInt::new(&discriminant.to_string(), v.span()); let ident = &v.ident; Ok(quote! { #discriminant => { let payload = unsafe { &bits.payload.#ident }; <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload) } }) }) .collect::>>()?; Ok(( quote! { #defs #[doc = #GENERATED_TYPE_DOCUMENTATION] #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)] #bits_repr #vis struct #bits_ty_ident { tag: #integer, payload: #variants_union_ident, } #[allow(unexpected_cfgs)] const _: () = { #[cfg(not(target_arch = "spirv"))] impl ::core::fmt::Debug for #bits_ty_ident { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty_ident)); ::core::fmt::DebugStruct::field(&mut debug_struct, "tag", &self.tag); ::core::fmt::DebugStruct::field(&mut debug_struct, "payload", &self.payload); ::core::fmt::DebugStruct::finish(&mut debug_struct) } } }; #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)] #[repr(C)] #[allow(non_snake_case)] #vis union #variants_union_ident { #(#union_fields,)* } #[allow(unexpected_cfgs)] const _: () = { #[cfg(not(target_arch = "spirv"))] impl ::core::fmt::Debug for #variants_union_ident { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#variants_union_ident)); ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct) } } }; #(#variant_struct_definitions)* }, quote! { type Bits = #bits_ty_ident; #[inline] #[allow(clippy::double_comparisons)] fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { match bits.tag { #(#variant_checks)* _ => false, } } }, )) } Repr::Transparent => { if variants.len() != 1 { bail!("enums with more than one variant cannot be transparent") } let variant = &variants[0]; let bits_ty = Ident::new(&format!("{}Bits", input.ident), input.span()); let fields = variant.fields.iter().map(|v| &v.ty); Ok(( quote! { #[doc = #GENERATED_TYPE_DOCUMENTATION] #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)] #[repr(C)] #vis struct #bits_ty(#(#fields),*); }, quote! { type Bits = <#bits_ty as #crate_name::CheckedBitPattern>::Bits; #[inline] #[allow(clippy::double_comparisons)] fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { <#bits_ty as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(bits) } }, )) } Repr::Integer(integer) => { let bits_repr = Representation { repr: Repr::C, ..representation }; let input_ident = &input.ident; // the enum manually re-configured as the union it represents. such a // union is the union of variants as a repr(c) struct with the // discriminator type inserted at the beginning. in our case we // union the `Bits` representation of each variant rather than the variant // itself, which we generate via a nested `CheckedBitPattern` derive // on the `variant_struct_definitions` generated below. // // see: https://doc.rust-lang.org/reference/type-layout.html#primitive-representation-of-enums-with-fields let bits_ty_ident = Ident::new(&format!("{input_ident}Bits"), input.span()); let variant_struct_idents = variants.iter().map(|v| { Ident::new(&format!("{input_ident}Variant{}", v.ident), v.span()) }); let variant_struct_definitions = variant_struct_idents.clone().zip(variants.iter()).map(|(variant_struct_ident, v)| { let fields = v.fields.iter().map(|v| &v.ty); // adding the discriminant repr integer as first field, as described above quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::CheckedBitPattern)] #[repr(C)] #vis struct #variant_struct_ident(#integer, #(#fields),*); } }); let union_fields = variant_struct_idents .clone() .zip(variants.iter()) .map(|(variant_struct_ident, v)| { let variant_struct_bits_ident = Ident::new(&format!("{variant_struct_ident}Bits"), input.span()); let field_ident = &v.ident; quote! { #field_ident: #variant_struct_bits_ident } }); let variant_checks = variant_struct_idents .clone() .zip(VariantDiscriminantIterator::new(variants.iter())) .zip(variants.iter()) .map(|((variant_struct_ident, discriminant), v)| -> Result<_> { let (discriminant, _variant) = discriminant?; let discriminant = LitInt::new(&discriminant.to_string(), v.span()); let ident = &v.ident; Ok(quote! { #discriminant => { let payload = unsafe { &bits.#ident }; <#variant_struct_ident as #crate_name::CheckedBitPattern>::is_valid_bit_pattern(payload) } }) }) .collect::>>()?; Ok(( quote! { #[doc = #GENERATED_TYPE_DOCUMENTATION] #[derive(::core::clone::Clone, ::core::marker::Copy, #crate_name::AnyBitPattern)] #bits_repr #[allow(non_snake_case)] #vis union #bits_ty_ident { __tag: #integer, #(#union_fields,)* } #[allow(unexpected_cfgs)] const _: () = { #[cfg(not(target_arch = "spirv"))] impl ::core::fmt::Debug for #bits_ty_ident { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { let mut debug_struct = ::core::fmt::Formatter::debug_struct(f, ::core::stringify!(#bits_ty_ident)); ::core::fmt::DebugStruct::field(&mut debug_struct, "tag", unsafe { &self.__tag }); ::core::fmt::DebugStruct::finish_non_exhaustive(&mut debug_struct) } } }; #(#variant_struct_definitions)* }, quote! { type Bits = #bits_ty_ident; #[inline] #[allow(clippy::double_comparisons)] fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { match unsafe { bits.__tag } { #(#variant_checks)* _ => false, } } }, )) } } } /// Check that a struct or enum has no padding by asserting that the size of /// the type is equal to the sum of the size of it's fields and discriminant /// (for enums, this must be asserted for each variant). fn generate_assert_no_padding( input: &DeriveInput, enum_variant: Option<&Variant>, for_trait: &str, ) -> Result { let struct_type = &input.ident; let fields = get_fields(input, enum_variant)?; // If the type is an enum, determine the type of its discriminant. let enum_discriminant = if matches!(input.data, Data::Enum(_)) { let ident = Ident::new(&format!("{}Discriminant", input.ident), input.ident.span()); Some(ident.into_token_stream()) } else { None }; // Prepend the type of the discriminant to the types of the fields. let mut field_types = enum_discriminant .into_iter() .chain(get_field_types(&fields).map(ToTokens::to_token_stream)); let size_sum = if let Some(first) = field_types.next() { let size_first = quote!(::core::mem::size_of::<#first>()); let size_rest = quote!(#( + ::core::mem::size_of::<#field_types>() )*); quote!(#size_first #size_rest) } else { quote!(0) }; let message = format!("derive({for_trait}) was applied to a type with padding"); Ok(quote! {const _: () = { assert!( ::core::mem::size_of::<#struct_type>() == (#size_sum), #message, ); };}) } /// Check that all fields implement a given trait fn generate_fields_are_trait( input: &DeriveInput, enum_variant: Option<&Variant>, trait_: syn::Path, ) -> Result { let (impl_generics, _ty_generics, where_clause) = input.generics.split_for_impl(); let fields = get_fields(input, enum_variant)?; let field_types = get_field_types(&fields); Ok(quote! {#(const _: fn() = || { #[allow(clippy::missing_const_for_fn)] #[doc(hidden)] fn check #impl_generics () #where_clause { fn assert_impl() {} assert_impl::<#field_types>(); } };)* }) } /// Get the type of an enum's discriminant. /// /// For `repr(int)` and `repr(C, int)` enums, this will return the known bare /// integer type specified. /// /// For `repr(C)` enums, this will extract the underlying size chosen by rustc. /// It will return a token stream which is a type expression that evaluates to /// a primitive integer type of this size, using our `EnumTagIntegerBytes` /// trait. /// /// For fieldless `repr(C)` enums, we can feed the size of the enum directly /// into the trait. /// /// For `repr(C)` enums with fields, we generate a new fieldless `repr(C)` enum /// with the same variants, then use that in the calculation. This is the /// specified behavior, see https://doc.rust-lang.org/stable/reference/type-layout.html#reprc-enums-with-fields /// /// Returns a tuple of (type ident, auxiliary definitions) fn get_enum_discriminant( input: &DeriveInput, crate_name: &TokenStream, ) -> Result<(TokenStream, TokenStream)> { let repr = get_repr(&input.attrs)?; match repr.repr { Repr::C => { let e = if let Data::Enum(e) = &input.data { e } else { unreachable!() }; if enum_has_fields(e.variants.iter()) { // If the enum has fields, we must first isolate the discriminant by // removing all the fields. let enum_discriminant = generate_enum_discriminant(input)?; let discriminant_ident = Ident::new( &format!("{}Discriminant", input.ident), input.ident.span(), ); Ok(( quote!(<[::core::primitive::u8; ::core::mem::size_of::<#discriminant_ident>()] as #crate_name::derive::EnumTagIntegerBytes>::Integer), quote! { #enum_discriminant }, )) } else { // If the enum doesn't have fields, we can just use it directly. let ident = &input.ident; Ok(( quote!(<[::core::primitive::u8; ::core::mem::size_of::<#ident>()] as #crate_name::derive::EnumTagIntegerBytes>::Integer), quote!(), )) } } Repr::Integer(integer) | Repr::CWithDiscriminant(integer) => { Ok((quote!(#integer), quote!())) } _ => unreachable!(), } } fn generate_enum_discriminant(input: &DeriveInput) -> Result { let e = if let Data::Enum(e) = &input.data { e } else { unreachable!() }; let repr = get_repr(&input.attrs)?; let repr = match repr.repr { Repr::C => quote!(#[repr(C)]), Repr::Integer(int) | Repr::CWithDiscriminant(int) => quote!(#[repr(#int)]), Repr::Rust | Repr::Transparent => unreachable!(), }; let ident = Ident::new(&format!("{}Discriminant", input.ident), input.ident.span()); let variants = e.variants.iter().cloned().map(|mut e| { e.fields = Fields::Unit; e }); Ok(quote! { #repr #[allow(dead_code)] enum #ident { #(#variants,)* } }) } fn get_wrapped_type_from_stream(tokens: TokenStream) -> Option { let mut tokens = tokens.into_iter().peekable(); match tokens.peek() { Some(TokenTree::Group(group)) => { let res = get_wrapped_type_from_stream(group.stream()); tokens.next(); // remove the peeked token tree match tokens.next() { // If there were more tokens, the input was invalid Some(_) => None, None => res, } } _ => syn::parse2(tokens.collect()).ok(), } } /// get a simple `#[foo(bar)]` attribute, returning `bar` fn get_type_from_simple_attr( attributes: &[Attribute], attr_name: &str, ) -> Option { for attr in attributes { if let (AttrStyle::Outer, Meta::List(list)) = (&attr.style, &attr.meta) { if list.path.is_ident(attr_name) { if let Some(ty) = get_wrapped_type_from_stream(list.tokens.clone()) { return Some(ty); } } } } None } fn get_repr(attributes: &[Attribute]) -> Result { attributes .iter() .filter_map(|attr| { if attr.path().is_ident("repr") { Some(attr.parse_args::()) } else { None } }) .try_fold(Representation::default(), |a, b| { let b = b?; Ok(Representation { repr: match (a.repr, b.repr) { (a, Repr::Rust) => a, (Repr::Rust, b) => b, _ => bail!("conflicting representation hints"), }, packed: match (a.packed, b.packed) { (a, None) => a, (None, b) => b, _ => bail!("conflicting representation hints"), }, align: match (a.align, b.align) { (Some(a), Some(b)) => Some(cmp::max(a, b)), (a, None) => a, (None, b) => b, }, }) }) } mk_repr! { U8 => u8, I8 => i8, U16 => u16, I16 => i16, U32 => u32, I32 => i32, U64 => u64, I64 => i64, I128 => i128, U128 => u128, Usize => usize, Isize => isize, } // where macro_rules! mk_repr {( $( $Xn:ident => $xn:ident ),* $(,)? ) => ( #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum IntegerRepr { $($Xn),* } impl<'a> TryFrom<&'a str> for IntegerRepr { type Error = &'a str; fn try_from(value: &'a str) -> std::result::Result { match value { $( stringify!($xn) => Ok(Self::$Xn), )* _ => Err(value), } } } impl ToTokens for IntegerRepr { fn to_tokens(&self, tokens: &mut TokenStream) { match self { $( Self::$Xn => tokens.extend(quote!($xn)), )* } } } )} use mk_repr; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Repr { Rust, C, Transparent, Integer(IntegerRepr), CWithDiscriminant(IntegerRepr), } impl Repr { fn as_integer(&self) -> Option { if let Self::Integer(v) = self { Some(*v) } else { None } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Representation { packed: Option, align: Option, repr: Repr, } impl Default for Representation { fn default() -> Self { Self { packed: None, align: None, repr: Repr::Rust } } } impl Parse for Representation { fn parse(input: ParseStream<'_>) -> Result { let mut ret = Representation::default(); while !input.is_empty() { let keyword = input.parse::()?; // preĆ«mptively call `.to_string()` *once* (rather than on `is_ident()`) let keyword_str = keyword.to_string(); let new_repr = match keyword_str.as_str() { "C" => Repr::C, "transparent" => Repr::Transparent, "packed" => { ret.packed = Some(if input.peek(token::Paren) { let contents; parenthesized!(contents in input); LitInt::base10_parse::(&contents.parse()?)? } else { 1 }); let _: Option = input.parse()?; continue; } "align" => { let contents; parenthesized!(contents in input); let new_align = LitInt::base10_parse::(&contents.parse()?)?; ret.align = Some( ret .align .map_or(new_align, |old_align| cmp::max(old_align, new_align)), ); let _: Option = input.parse()?; continue; } ident => { let primitive = IntegerRepr::try_from(ident) .map_err(|_| input.error("unrecognized representation hint"))?; Repr::Integer(primitive) } }; ret.repr = match (ret.repr, new_repr) { (Repr::Rust, new_repr) => { // This is the first explicit repr. new_repr } (Repr::C, Repr::Integer(integer)) | (Repr::Integer(integer), Repr::C) => { // Both the C repr and an integer repr have been specified // -> merge into a C wit discriminant. Repr::CWithDiscriminant(integer) } (_, _) => { return Err(input.error("duplicate representation hint")); } }; let _: Option = input.parse()?; } Ok(ret) } } impl ToTokens for Representation { fn to_tokens(&self, tokens: &mut TokenStream) { let mut meta = Punctuated::<_, Token![,]>::new(); match self.repr { Repr::Rust => {} Repr::C => meta.push(quote!(C)), Repr::Transparent => meta.push(quote!(transparent)), Repr::Integer(primitive) => meta.push(quote!(#primitive)), Repr::CWithDiscriminant(primitive) => { meta.push(quote!(C)); meta.push(quote!(#primitive)); } } if let Some(packed) = self.packed.as_ref() { let lit = LitInt::new(&packed.to_string(), Span::call_site()); meta.push(quote!(packed(#lit))); } if let Some(align) = self.align.as_ref() { let lit = LitInt::new(&align.to_string(), Span::call_site()); meta.push(quote!(align(#lit))); } tokens.extend(quote!( #[repr(#meta)] )); } } fn enum_has_fields<'a>( mut variants: impl Iterator, ) -> bool { variants.any(|v| matches!(v.fields, Fields::Named(_) | Fields::Unnamed(_))) } struct VariantDiscriminantIterator<'a, I: Iterator + 'a> { inner: I, last_value: i128, } impl<'a, I: Iterator + 'a> VariantDiscriminantIterator<'a, I> { fn new(inner: I) -> Self { VariantDiscriminantIterator { inner, last_value: -1 } } } impl<'a, I: Iterator + 'a> Iterator for VariantDiscriminantIterator<'a, I> { type Item = Result<(i128, &'a Variant)>; fn next(&mut self) -> Option { let variant = self.inner.next()?; if let Some((_, discriminant)) = &variant.discriminant { let discriminant_value = match parse_int_expr(discriminant) { Ok(value) => value, Err(e) => return Some(Err(e)), }; self.last_value = discriminant_value; } else { // If this wraps, then either: // 1. the enum is using repr(u128), so wrapping is correct // 2. the enum is using repr(i<=128 or u<128), so the compiler will // already emit a "wrapping discriminant" E0370 error. self.last_value = self.last_value.wrapping_add(1); // Static assert that there is no integer repr > 128 bits. If that // changes, the above comment is inaccurate and needs to be updated! // FIXME(zachs18): maybe should also do something to ensure `isize::BITS // <= 128`? if let Some(repr) = None:: { match repr { IntegerRepr::U8 | IntegerRepr::I8 | IntegerRepr::U16 | IntegerRepr::I16 | IntegerRepr::U32 | IntegerRepr::I32 | IntegerRepr::U64 | IntegerRepr::I64 | IntegerRepr::I128 | IntegerRepr::U128 | IntegerRepr::Usize | IntegerRepr::Isize => (), } } } Some(Ok((self.last_value, variant))) } } fn parse_int_expr(expr: &Expr) -> Result { match expr { Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => { parse_int_expr(expr).map(|int| -int) } Expr::Lit(ExprLit { lit: Lit::Int(int), .. }) => int.base10_parse(), Expr::Lit(ExprLit { lit: Lit::Byte(byte), .. }) => Ok(byte.value().into()), _ => bail!("Not an integer expression"), } } #[cfg(test)] mod tests { use syn::parse_quote; use super::{get_repr, IntegerRepr, Repr, Representation}; #[test] fn parse_basic_repr() { let attr = parse_quote!(#[repr(C)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { repr: Repr::C, ..Default::default() }); let attr = parse_quote!(#[repr(transparent)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!( repr, Representation { repr: Repr::Transparent, ..Default::default() } ); let attr = parse_quote!(#[repr(u8)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!( repr, Representation { repr: Repr::Integer(IntegerRepr::U8), ..Default::default() } ); let attr = parse_quote!(#[repr(packed)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { packed: Some(1), ..Default::default() }); let attr = parse_quote!(#[repr(packed(1))]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { packed: Some(1), ..Default::default() }); let attr = parse_quote!(#[repr(packed(2))]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { packed: Some(2), ..Default::default() }); let attr = parse_quote!(#[repr(align(2))]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { align: Some(2), ..Default::default() }); } #[test] fn parse_advanced_repr() { let attr = parse_quote!(#[repr(align(4), align(2))]); let repr = get_repr(&[attr]).unwrap(); assert_eq!(repr, Representation { align: Some(4), ..Default::default() }); let attr1 = parse_quote!(#[repr(align(1))]); let attr2 = parse_quote!(#[repr(align(4))]); let attr3 = parse_quote!(#[repr(align(2))]); let repr = get_repr(&[attr1, attr2, attr3]).unwrap(); assert_eq!(repr, Representation { align: Some(4), ..Default::default() }); let attr = parse_quote!(#[repr(C, u8)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!( repr, Representation { repr: Repr::CWithDiscriminant(IntegerRepr::U8), ..Default::default() } ); let attr = parse_quote!(#[repr(u8, C)]); let repr = get_repr(&[attr]).unwrap(); assert_eq!( repr, Representation { repr: Repr::CWithDiscriminant(IntegerRepr::U8), ..Default::default() } ); } } pub fn bytemuck_crate_name(input: &DeriveInput) -> TokenStream { const ATTR_NAME: &'static str = "crate"; let mut crate_name = quote!(::bytemuck); for attr in &input.attrs { if !attr.path().is_ident("bytemuck") { continue; } attr.parse_nested_meta(|meta| { if meta.path.is_ident(ATTR_NAME) { let expr: syn::Expr = meta.value()?.parse()?; let mut value = &expr; while let syn::Expr::Group(e) = value { value = &e.expr; } if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = value { let suffix = lit.suffix(); if !suffix.is_empty() { bail!(format!("Unexpected suffix `{}` on string literal", suffix)) } let path: syn::Path = match lit.parse() { Ok(path) => path, Err(_) => { bail!(format!("Failed to parse path: {:?}", lit.value())) } }; crate_name = path.into_token_stream(); } else { bail!( "Expected bytemuck `crate` attribute to be a string: `crate = \"...\"`", ) } } Ok(()) }).unwrap(); } return crate_name; } const GENERATED_TYPE_DOCUMENTATION: &str = " `bytemuck`-generated type for internal purposes only."; bytemuck_derive-1.10.2/tests/basic.rs000064400000000000000000000333731046102023000156700ustar 00000000000000#![allow(dead_code)] #![deny(clippy::allow_attributes)] use bytemuck::{ checked::CheckedCastError, AnyBitPattern, CheckedBitPattern, Contiguous, NoUninit, Pod, TransparentWrapper, Zeroable, }; use std::marker::{PhantomData, PhantomPinned}; #[derive(Copy, Clone, Pod, Zeroable)] #[repr(C)] struct Test { a: u16, b: u16, } #[derive(Pod, Zeroable)] #[repr(C, packed)] struct GenericPackedStruct { a: u32, b: T, c: u32, } impl Clone for GenericPackedStruct { fn clone(&self) -> Self { *self } } impl Copy for GenericPackedStruct {} #[derive(Pod, Zeroable)] #[repr(C, packed(1))] struct GenericPackedStructExplicitPackedAlignment { a: u32, b: T, c: u32, } impl Clone for GenericPackedStructExplicitPackedAlignment { fn clone(&self) -> Self { *self } } impl Copy for GenericPackedStructExplicitPackedAlignment {} #[derive(Zeroable)] struct ZeroGeneric { a: T, } #[derive(Zeroable)] #[repr(u8)] enum ZeroEnum { A = 0, B = 1, C = 2, } #[derive(Zeroable)] #[repr(u8)] enum BasicFieldfulZeroEnum { A(u8) = 0, B = 1, C(String) = 2, } #[derive(Zeroable)] #[repr(C)] enum ReprCFieldfulZeroEnum { A(u8), B(Box<[u8]>), C, } #[derive(Zeroable)] #[repr(C, i32)] enum ReprCIntFieldfulZeroEnum { B(String) = 1, A(u8, bool, char) = 0, C = 2, } #[derive(Zeroable)] #[repr(i32)] enum GenericFieldfulZeroEnum { A(Box) = 1, B(T, T) = 0, } #[derive(Zeroable)] #[repr(i32)] #[zeroable(bound = "")] enum GenericCustomBoundFieldfulZeroEnum { A(Option>), B(String), } #[derive(TransparentWrapper)] #[repr(transparent)] struct TransparentSingle { a: u16, } #[derive(TransparentWrapper)] #[repr(transparent)] #[transparent(u16)] struct TransparentWithZeroSized { a: u16, b: PhantomData, } struct MyZst(PhantomData, [u8; 0], PhantomPinned); unsafe impl Zeroable for MyZst {} #[derive(TransparentWrapper)] #[repr(transparent)] #[transparent(u16)] struct TransparentTupleWithCustomZeroSized(u16, MyZst); #[repr(u8)] #[derive(Clone, Copy, Contiguous)] enum ContiguousWithValues { A = 0, B = 1, C = 2, D = 3, E = 4, } #[repr(i8)] #[derive(Clone, Copy, Contiguous)] enum ContiguousWithImplicitValues { A = -10, B, C, D, E, } #[derive(Copy, Clone, NoUninit)] #[repr(C)] struct NoUninitTest { a: u16, b: u16, } #[derive(Copy, Clone, AnyBitPattern)] #[repr(C)] union UnionTestAnyBitPattern { a: u8, b: u16, } #[repr(u8)] #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)] enum CheckedBitPatternEnumWithValues { A = 0, B = 1, C = 2, D = 3, E = 4, } #[repr(i8)] #[derive(Clone, Copy, NoUninit, CheckedBitPattern)] enum CheckedBitPatternEnumWithImplicitValues { A = -10, B, C, D, E, } #[repr(u8)] #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)] enum CheckedBitPatternEnumNonContiguous { A = 1, B = 8, C = 2, D = 3, E = 56, } #[repr(u8)] #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)] enum CheckedBitPatternEnumByteLit { A = b'A', B = b'B', C = b'C', D = b'D', E = b'E', } #[derive(Debug, Copy, Clone, NoUninit, CheckedBitPattern, PartialEq, Eq)] #[repr(C)] struct CheckedBitPatternStruct { a: u8, b: CheckedBitPatternEnumNonContiguous, } #[derive(Debug, Copy, Clone, NoUninit)] #[repr(C)] enum NoUninitEnum { A, B, } #[derive(Debug, Copy, Clone, NoUninit)] #[repr(C)] enum NoUninitEnumWithFields { A(u32, u32), B(u16, u16, u16, u16), } #[derive(Debug, Copy, Clone, NoUninit)] #[repr(C, u16)] enum NoUninitEnumWithFieldsAndCAndDiscriminant { A(u16, u16), B(u8, u8, u8, u8), } #[derive(Debug, Clone, Copy, NoUninit)] #[repr(u16)] enum NoUninitEnumWithFieldsAndDiscriminant { A(u16, u16), B(u8, u8, u8, u8), } #[derive(Debug, Copy, Clone, AnyBitPattern, PartialEq, Eq)] #[repr(C)] struct AnyBitPatternTest { a: A, b: B, } #[derive(Clone, Copy, CheckedBitPattern)] #[repr(C, align(8))] struct CheckedBitPatternAlignedStruct { a: u16, } #[derive(Clone, Copy, CheckedBitPattern)] #[repr(C, packed)] struct CheckedBitPatternPackedStruct { a: u8, b: u16, } #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(C)] enum CheckedBitPatternCDefaultDiscriminantEnum { A, B, } #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(C)] enum CheckedBitPatternCDefaultDiscriminantEnumWithFields { A(u64), B { c: u64 }, } #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(C, u8)] enum CheckedBitPatternCEnumWithFields { A(u32), B { c: u32 }, } #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(u8)] enum CheckedBitPatternIntEnumWithFields { A(u8), B { c: u32 }, } #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(transparent)] enum CheckedBitPatternTransparentEnumWithFields { A { b: u32 }, } // size 24, align 8. // first byte always the u8 discriminant, then 7 bytes of padding until the // payload union since the align of the payload is the greatest of the align of // all the variants, which is 8 (from // CheckedBitPatternCDefaultDiscriminantEnumWithFields) #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)] #[repr(C, u8)] enum CheckedBitPatternEnumNested { A(CheckedBitPatternCEnumWithFields), B(CheckedBitPatternCDefaultDiscriminantEnumWithFields), } /// ```compile_fail /// use bytemuck::{Pod, Zeroable}; /// /// #[derive(Pod, Zeroable)] /// #[repr(transparent)] /// struct TransparentSingle(T); /// /// struct NotPod(u32); /// /// let _: u32 = bytemuck::cast(TransparentSingle(NotPod(0u32))); /// ``` #[derive( Debug, Copy, Clone, PartialEq, Eq, Pod, Zeroable, TransparentWrapper, )] #[repr(transparent)] struct NewtypeWrapperTest(T); #[derive(Debug, Clone, PartialEq, Eq, TransparentWrapper)] #[repr(transparent)] struct AlgebraicNewtypeWrapperTest(Vec); #[test] fn algebraic_newtype_corect() { let x: Vec = vec![1, 2, 3, 4]; let y: AlgebraicNewtypeWrapperTest = AlgebraicNewtypeWrapperTest::wrap(x.clone()); assert_eq!(y.0, x); } #[derive(Debug, Clone, PartialEq, Eq, TransparentWrapper)] #[repr(transparent)] #[transparent(Vec)] struct AlgebraicNewtypeWrapperTestWithFields(Vec, PhantomData); #[test] fn algebraic_newtype_fields_corect() { let x: Vec = vec![1, 2, 3, 4]; let y: AlgebraicNewtypeWrapperTestWithFields = AlgebraicNewtypeWrapperTestWithFields::wrap(x.clone()); assert_eq!(y.0, x); } #[test] fn fails_cast_contiguous() { let can_cast = CheckedBitPatternEnumWithValues::is_valid_bit_pattern(&5); assert!(!can_cast); } #[test] fn passes_cast_contiguous() { let res = bytemuck::checked::from_bytes::(&[2u8]); assert_eq!(*res, CheckedBitPatternEnumWithValues::C); } #[test] fn fails_cast_noncontiguous() { let can_cast = CheckedBitPatternEnumNonContiguous::is_valid_bit_pattern(&4); assert!(!can_cast); } #[test] fn passes_cast_noncontiguous() { let res = bytemuck::checked::from_bytes::(&[ 56u8, ]); assert_eq!(*res, CheckedBitPatternEnumNonContiguous::E); } #[test] fn fails_cast_bytelit() { let can_cast = CheckedBitPatternEnumByteLit::is_valid_bit_pattern(&b'a'); assert!(!can_cast); } #[test] fn passes_cast_bytelit() { let res = bytemuck::checked::cast_slice::(b"CAB"); assert_eq!( res, [ CheckedBitPatternEnumByteLit::C, CheckedBitPatternEnumByteLit::A, CheckedBitPatternEnumByteLit::B ] ); } #[test] fn fails_cast_struct() { let pod = [0u8, 24u8]; let res = bytemuck::checked::try_from_bytes::(&pod); assert!(res.is_err()); } #[test] fn passes_cast_struct() { let pod = [0u8, 8u8]; let res = bytemuck::checked::from_bytes::(&pod); assert_eq!( *res, CheckedBitPatternStruct { a: 0, b: CheckedBitPatternEnumNonContiguous::B } ); } #[test] fn anybitpattern_implies_zeroable() { let test = AnyBitPatternTest::::zeroed(); assert_eq!(test, AnyBitPatternTest { a: 0isize, b: 0usize }); } #[test] fn checkedbitpattern_try_pod_read_unaligned() { let pod = [0u8]; let res = bytemuck::checked::try_pod_read_unaligned::< CheckedBitPatternEnumWithValues, >(&pod); assert!(res.is_ok()); let pod = [5u8]; let res = bytemuck::checked::try_pod_read_unaligned::< CheckedBitPatternEnumWithValues, >(&pod); assert!(res.is_err()); } #[test] fn checkedbitpattern_aligned_struct() { let pod = [0u8; 8]; bytemuck::checked::pod_read_unaligned::(&pod); } #[test] fn checkedbitpattern_c_default_discriminant_enum_with_fields() { let pod = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xcc, ]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternCDefaultDiscriminantEnumWithFields, >(&pod); assert_eq!( value, CheckedBitPatternCDefaultDiscriminantEnumWithFields::A(0xcc555555555555cc) ); let pod = [ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xcc, ]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternCDefaultDiscriminantEnumWithFields, >(&pod); assert_eq!( value, CheckedBitPatternCDefaultDiscriminantEnumWithFields::B { c: 0xcc555555555555cc } ); } #[test] fn checkedbitpattern_c_enum_with_fields() { let pod = [0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternCEnumWithFields, >(&pod); assert_eq!(value, CheckedBitPatternCEnumWithFields::A(0xcc5555cc)); let pod = [0x01, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternCEnumWithFields, >(&pod); assert_eq!(value, CheckedBitPatternCEnumWithFields::B { c: 0xcc5555cc }); } #[test] fn checkedbitpattern_int_enum_with_fields() { let pod = [0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternIntEnumWithFields, >(&pod); assert_eq!(value, CheckedBitPatternIntEnumWithFields::A(0x55)); let pod = [0x01, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternIntEnumWithFields, >(&pod); assert_eq!(value, CheckedBitPatternIntEnumWithFields::B { c: 0xcc5555cc }); } #[test] fn checkedbitpattern_nested_enum_with_fields() { // total size 24 bytes. first byte always the u8 discriminant. #[repr(C, align(8))] struct Align8Bytes([u8; 24]); // first we'll check variantA, nested variant A let pod = Align8Bytes([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // byte 0 discriminant = 0 = variant A, bytes 1-7 irrelevant padding. 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc, // bytes 8-15 are the nested CheckedBitPatternCEnumWithFields, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bytes 16-23 padding ]); let value = bytemuck::checked::from_bytes::(&pod.0); assert_eq!( value, &CheckedBitPatternEnumNested::A(CheckedBitPatternCEnumWithFields::A( 0xcc5555cc )) ); // next we'll check invalid first discriminant fails let pod = Align8Bytes([ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // byte 0 discriminant = 2 = invalid, bytes 1-7 padding 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc, // bytes 8-15 are the nested CheckedBitPatternCEnumWithFields = A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bytes 16-23 padding ]); let result = bytemuck::checked::try_from_bytes::(&pod.0); assert_eq!(result, Err(CheckedCastError::InvalidBitPattern)); // next we'll check variant B, nested variant B let pod = Align8Bytes([ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // byte 0 discriminant = 1 = variant B, bytes 1-7 padding 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* bytes 8-15 is C int size discriminant of * CheckedBitPatternCDefaultDiscrimimantEnumWithFields, 1 (LE byte * order) = variant B */ 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xcc, // bytes 16-13 is the data contained in nested variant B ]); let value = bytemuck::checked::from_bytes::(&pod.0); assert_eq!( value, &CheckedBitPatternEnumNested::B( CheckedBitPatternCDefaultDiscriminantEnumWithFields::B { c: 0xcc555555555555cc } ) ); // finally we'll check variant B, nested invalid discriminant let pod = Align8Bytes([ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 discriminant = variant B, bytes 1-7 padding 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* bytes 8-15 is C int size discriminant of * CheckedBitPatternCDefaultDiscrimimantEnumWithFields, 0x08 is * invalid */ 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xcc, // bytes 16-13 is the data contained in nested variant B ]); let result = bytemuck::checked::try_from_bytes::(&pod.0); assert_eq!(result, Err(CheckedCastError::InvalidBitPattern)); } #[test] fn checkedbitpattern_transparent_enum_with_fields() { let pod = [0xcc, 0x55, 0x55, 0xcc]; let value = bytemuck::checked::pod_read_unaligned::< CheckedBitPatternTransparentEnumWithFields, >(&pod); assert_eq!( value, CheckedBitPatternTransparentEnumWithFields::A { b: 0xcc5555cc } ); } #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C, align(16))] struct Issue127 {} use bytemuck as reexport_name; #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable, bytemuck::ByteEq)] #[bytemuck(crate = "reexport_name")] #[repr(C)] struct Issue93 {}