diff options
-rw-r--r-- | .cargo_vcs_info.json | 6 | ||||
-rw-r--r-- | Cargo.toml | 44 | ||||
-rw-r--r-- | Cargo.toml.orig | 24 | ||||
-rw-r--r-- | LICENSE-APACHE | 61 | ||||
-rw-r--r-- | LICENSE-MIT | 9 | ||||
-rw-r--r-- | LICENSE-ZLIB | 11 | ||||
-rw-r--r-- | README.md | 4 | ||||
-rw-r--r-- | changelog.md | 51 | ||||
-rw-r--r-- | src/lib.rs | 372 | ||||
-rw-r--r-- | src/traits.rs | 772 | ||||
-rw-r--r-- | tests/basic.rs | 253 |
11 files changed, 1607 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..7a56c61 --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "2bcc0ef6de45203b3added2593787d3bab213280" + }, + "path_in_vcs": "derive" +}
\ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8b1a466 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,44 @@ +# 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" +name = "bytemuck_derive" +version = "1.4.0" +authors = ["Lokathor <zefria@gmail.com>"] +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" +proc-macro = true + +[dependencies.proc-macro2] +version = "1" + +[dependencies.quote] +version = "1" + +[dependencies.syn] +version = "1.0.99" + +[dev-dependencies] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..020f76a --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,24 @@ +[package] +name = "bytemuck_derive" +description = "derive proc-macros for `bytemuck`" +version = "1.4.0" +authors = ["Lokathor <zefria@gmail.com>"] +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" + +[lib] +name = "bytemuck_derive" +proc-macro = true + +[dependencies] +# syn seems to have broken backwards compability in this version https://github.com/dtolnay/syn/issues/1194 +syn = "1.0.99" +quote = "1" +proc-macro2 = "1" + +[dev-dependencies] +bytemuck = { path = "../", features = ["derive"] } diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..136d900 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,61 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..164045f --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,9 @@ +MIT 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. diff --git a/LICENSE-ZLIB b/LICENSE-ZLIB new file mode 100644 index 0000000..d70707c --- /dev/null +++ b/LICENSE-ZLIB @@ -0,0 +1,11 @@ +Copyright (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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..553a40e --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ + +# bytemuck_derive + +Derive macros for [bytemuck](https://docs.rs/bytemuck) traits. diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..e8662e7 --- /dev/null +++ b/changelog.md @@ -0,0 +1,51 @@ + +## `bytemuck_derive` changelog + +## 1.4.0 + +* ByteEq and ByteHash derives will make Eq and Hash impls that treat the value as a &[u8]. 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 occured 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 + "curret" (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. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..e16d43e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,372 @@ +//! 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::{ + 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 +/// +/// ## Example +/// +/// ```rust +/// # use bytemuck_derive::{Pod, Zeroable}; +/// +/// #[derive(Copy, Clone, Pod, Zeroable)] +/// #[repr(C)] +/// struct Test { +/// a: u16, +/// b: u16, +/// } +/// ``` +#[proc_macro_derive(Pod)] +pub fn derive_pod(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let expanded = + derive_marker_trait::<Pod>(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)] +pub fn derive_anybitpattern( + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let expanded = derive_marker_trait::<AnyBitPattern>(parse_macro_input!( + input as DeriveInput + )); + + proc_macro::TokenStream::from(expanded) +} + +/// Derive the `Zeroable` trait for a struct +/// +/// The macro ensures that the struct follows all the the safety requirements +/// for the `Zeroable` trait. +/// +/// The following constraints need to be satisfied for the macro to succeed +/// +/// - All fields in the struct must to implement `Zeroable` +/// +/// ## Example +/// +/// ```rust +/// # use bytemuck_derive::{Zeroable}; +/// +/// #[derive(Copy, Clone, Zeroable)] +/// #[repr(C)] +/// struct Test { +/// a: u16, +/// b: u16, +/// } +/// ``` +#[proc_macro_derive(Zeroable)] +pub fn derive_zeroable( + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let expanded = + derive_marker_trait::<Zeroable>(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)]` +/// - All variants must be fieldless +/// - The enum must contain no generic parameters +#[proc_macro_derive(NoUninit)] +pub fn derive_no_uninit( + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let expanded = + derive_marker_trait::<NoUninit>(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 +/// (the rest of the constraints are guaranteed by the `CheckedBitPattern` +/// subtrait bounds, i.e. are guaranteed by the requirements of the `NoUninit` +/// trait which `CheckedBitPattern` is a subtrait of): +/// +/// If applied to a struct: +/// - All fields must implement `CheckedBitPattern` +/// +/// If applied to an enum: +/// - All requirements already checked by `NoUninit`, just impls the trait +#[proc_macro_derive(CheckedBitPattern)] +pub fn derive_maybe_pod( + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let expanded = derive_marker_trait::<CheckedBitPattern>(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 +/// +/// 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)]` +/// +/// ## Example +/// +/// ```rust +/// # use bytemuck_derive::TransparentWrapper; +/// # use std::marker::PhantomData; +/// +/// #[derive(Copy, Clone, TransparentWrapper)] +/// #[repr(transparent)] +/// #[transparent(u16)] +/// struct Test<T> { +/// inner: u16, +/// extra: PhantomData<T>, +/// } +/// ``` +#[proc_macro_derive(TransparentWrapper, attributes(transparent))] +pub fn derive_transparent( + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let expanded = derive_marker_trait::<TransparentWrapper>(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::<Contiguous>(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. +/// +/// ## Example +/// +/// ```rust +/// # use bytemuck_derive::{ByteEq, NoUninit}; +/// #[derive(Copy, Clone, NoUninit, ByteEq)] +/// #[repr(C)] +/// struct Test { +/// a: u32, +/// b: char, +/// c: f32, +/// } +/// ``` +#[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 ident = input.ident; + + proc_macro::TokenStream::from(quote! { + impl ::core::cmp::PartialEq for #ident { + #[inline] + #[must_use] + fn eq(&self, other: &Self) -> bool { + ::bytemuck::bytes_of(self) == ::bytemuck::bytes_of(other) + } + } + impl ::core::cmp::Eq for #ident { } + }) +} + +/// 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. +/// +/// ## Example +/// +/// ```rust +/// # use bytemuck_derive::{ByteHash, NoUninit}; +/// #[derive(Copy, Clone, NoUninit, ByteHash)] +/// #[repr(C)] +/// struct Test { +/// a: u32, +/// b: char, +/// c: f32, +/// } +/// ``` +#[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 ident = input.ident; + + proc_macro::TokenStream::from(quote! { + impl ::core::hash::Hash for #ident { + #[inline] + fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) { + ::core::hash::Hash::hash_slice(::bytemuck::bytes_of(self), state) + } + + #[inline] + fn hash_slice<H: ::core::hash::Hasher>(data: &[Self], state: &mut H) { + ::core::hash::Hash::hash_slice(::bytemuck::cast_slice::<_, u8>(data), state) + } + } + }) +} + +/// Basic wrapper for error handling +fn derive_marker_trait<Trait: Derivable>(input: DeriveInput) -> TokenStream { + derive_marker_trait_inner::<Trait>(input) + .unwrap_or_else(|err| err.into_compile_error()) +} + +fn derive_marker_trait_inner<Trait: Derivable>( + mut input: DeriveInput, +) -> Result<TokenStream> { + // Enforce Pod on all generic fields. + let trait_ = Trait::ident(&input)?; + 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)?; + let (trait_impl_extras, trait_impl) = Trait::trait_impl(&input)?; + + let implies_trait = if let Some(implies_trait) = Trait::implies_trait() { + quote!(unsafe impl #implies_trait for #name {}) + } 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::<Vec<syn::WherePredicate>>(); + + generics.make_where_clause().predicates.extend(type_params); +} diff --git a/src/traits.rs b/src/traits.rs new file mode 100644 index 0000000..0f4e0a9 --- /dev/null +++ b/src/traits.rs @@ -0,0 +1,772 @@ +#![allow(unused_imports)] +use proc_macro2::{Ident, Span, TokenStream, TokenTree}; +use quote::{quote, quote_spanned, 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) -> Result<syn::Path>; + fn implies_trait() -> Option<TokenStream> { + None + } + fn asserts(_input: &DeriveInput) -> Result<TokenStream> { + Ok(quote!()) + } + fn check_attributes(_ty: &Data, _attributes: &[Attribute]) -> Result<()> { + Ok(()) + } + fn trait_impl(_input: &DeriveInput) -> Result<(TokenStream, TokenStream)> { + Ok((quote!(), quote!())) + } + fn requires_where_clause() -> bool { + true + } +} + +pub struct Pod; + +impl Derivable for Pod { + fn ident(_: &DeriveInput) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::Pod)) + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + 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)?) + } else { + None + }; + let assert_fields_are_pod = + generate_fields_are_trait(input, Self::ident(input)?)?; + + 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) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::AnyBitPattern)) + } + + fn implies_trait() -> Option<TokenStream> { + Some(quote!(::bytemuck::Zeroable)) + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + match &input.data { + Data::Union(_) => Ok(quote!()), // unions are always `AnyBitPattern` + Data::Struct(_) => generate_fields_are_trait(input, Self::ident(input)?), + Data::Enum(_) => { + bail!("Deriving AnyBitPattern is not supported for enums") + } + } + } +} + +pub struct Zeroable; + +impl Derivable for Zeroable { + fn ident(_: &DeriveInput) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::Zeroable)) + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + match &input.data { + Data::Union(_) => Ok(quote!()), // unions are always `Zeroable` + Data::Struct(_) => generate_fields_are_trait(input, Self::ident(input)?), + Data::Enum(_) => bail!("Deriving Zeroable is not supported for enums"), + } + } +} + +pub struct NoUninit; + +impl Derivable for NoUninit { + fn ident(_: &DeriveInput) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::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(_) => if repr.repr.is_integer() { + Ok(()) + } else { + bail!("NoUninit requires the enum to be an explicit #[repr(Int)]") + }, + Data::Union(_) => bail!("NoUninit can only be derived on enums and structs") + } + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + 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)?; + let assert_fields_are_no_padding = + generate_fields_are_trait(&input, Self::ident(input)?)?; + + Ok(quote!( + #assert_no_padding + #assert_fields_are_no_padding + )) + } + Data::Enum(DataEnum { variants, .. }) => { + if variants.iter().any(|variant| !variant.fields.is_empty()) { + bail!("Only fieldless enums are supported for NoUninit") + } 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) -> Result<(TokenStream, TokenStream)> { + Ok((quote!(), quote!())) + } +} + +pub struct CheckedBitPattern; + +impl Derivable for CheckedBitPattern { + fn ident(_: &DeriveInput) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::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(_) => if repr.repr.is_integer() { + Ok(()) + } else { + bail!("CheckedBitPattern requires the enum to be an explicit #[repr(Int)]") + }, + Data::Union(_) => bail!("CheckedBitPattern can only be derived on enums and structs") + } + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + 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, Self::ident(input)?)?; + + Ok(assert_fields_are_maybe_pod) + } + Data::Enum(_) => Ok(quote!()), /* nothing needed, already guaranteed + * OK by NoUninit */ + 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) -> Result<(TokenStream, TokenStream)> { + match &input.data { + Data::Struct(DataStruct { fields, .. }) => { + generate_checked_bit_pattern_struct(&input.ident, fields, &input.attrs) + } + Data::Enum(_) => generate_checked_bit_pattern_enum(input), + 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; + +impl TransparentWrapper { + fn get_wrapper_type( + attributes: &[Attribute], fields: &Fields, + ) -> Option<TokenStream> { + let transparent_param = get_simple_attr(attributes, "transparent"); + transparent_param.map(|ident| ident.to_token_stream()).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.map(|ty| ty.to_token_stream()) + } + }) + } +} + +impl Derivable for TransparentWrapper { + fn ident(input: &DeriveInput) -> Result<syn::Path> { + let fields = get_struct_fields(input)?; + + let ty = match Self::get_wrapper_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!(::bytemuck::TransparentWrapper<#ty>)) + } + + fn asserts(input: &DeriveInput) -> Result<TokenStream> { + let fields = get_struct_fields(input)?; + let wrapped_type = match Self::get_wrapper_type(&input.attrs, &fields) { + Some(wrapped_type) => wrapped_type.to_string(), + None => unreachable!(), /* other code will already reject this derive */ + }; + let mut wrapped_fields = fields + .iter() + .filter(|field| field.ty.to_token_stream().to_string() == wrapped_type); + if let None = wrapped_fields.next() { + bail!("TransparentWrapper must have one field of the wrapped type"); + }; + if let Some(_) = wrapped_fields.next() { + bail!("TransparentWrapper can only have one field of the wrapped type") + } else { + Ok(quote!()) + } + } + + 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) -> Result<syn::Path> { + Ok(syn::parse_quote!(::bytemuck::Contiguous)) + } + + fn trait_impl(input: &DeriveInput) -> Result<(TokenStream, TokenStream)> { + let repr = get_repr(&input.attrs)?; + + let integer_ty = if let Some(integer_ty) = repr.repr.as_integer_type() { + integer_ty + } else { + bail!("Contiguous requires the enum to be #[repr(Int)]"); + }; + + let variants = get_enum_variants(input)?; + let mut variants_with_discriminator = + VariantDiscriminantIterator::new(variants); + + let (min, max, count) = variants_with_discriminator.try_fold( + (i64::max_value(), i64::min_value(), 0), + |(min, max, count), res| { + let discriminator = res?; + Ok::<_, Error>(( + i64::min(min, discriminator), + i64::max(max, discriminator), + 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()); + + Ok(( + quote!(), + quote! { + type Int = #integer_ty; + const MIN_VALUE: #integer_ty = #min_lit; + const MAX_VALUE: #integer_ty = #max_lit; + }, + )) + } +} + +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") + } +} + +fn get_fields(input: &DeriveInput) -> Result<Fields> { + match &input.data { + Data::Struct(DataStruct { fields, .. }) => Ok(fields.clone()), + Data::Union(DataUnion { fields, .. }) => Ok(Fields::Named(fields.clone())), + Data::Enum(_) => bail!("deriving this trait is not supported for enums"), + } +} + +fn get_enum_variants<'a>( + input: &'a DeriveInput, +) -> Result<impl Iterator<Item = &'a Variant> + '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<Item = &'a Type> + 'a { + fields.iter().map(|field| &field.ty) +} + +fn generate_checked_bit_pattern_struct( + input_ident: &Ident, fields: &Fields, attrs: &[Attribute], +) -> 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::<Vec<_>>(); + let field_tys = fields.iter().map(|field| &field.ty).collect::<Vec<_>>(); + + let field_name = &field_names[..]; + let field_ty = &field_tys[..]; + + let derive_dbg = + quote!(#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]); + + Ok(( + quote! { + #repr + #[derive(Clone, Copy, ::bytemuck::AnyBitPattern)] + #derive_dbg + pub struct #bits_ty { + #(#field_name: <#field_ty as ::bytemuck::CheckedBitPattern>::Bits,)* + } + }, + quote! { + type Bits = #bits_ty; + + #[inline] + #[allow(clippy::double_comparisons)] + fn is_valid_bit_pattern(bits: &#bits_ty) -> bool { + #(<#field_ty as ::bytemuck::CheckedBitPattern>::is_valid_bit_pattern(&bits.#field_name) && )* true + } + }, + )) +} + +fn generate_checked_bit_pattern_enum( + input: &DeriveInput, +) -> Result<(TokenStream, TokenStream)> { + let span = input.span(); + let mut variants_with_discriminant = + VariantDiscriminantIterator::new(get_enum_variants(input)?); + + let (min, max, count) = variants_with_discriminant.try_fold( + (i64::max_value(), i64::min_value(), 0), + |(min, max, count), res| { + let discriminant = res?; + Ok::<_, Error>(( + i64::min(min, discriminant), + i64::max(max, discriminant), + count + 1, + )) + }, + )?; + + let check = if count == 0 { + quote_spanned!(span => 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_lits = + VariantDiscriminantIterator::new(get_enum_variants(input)?) + .map(|res| { + let variant = res?; + Ok(LitInt::new(&format!("{}", variant), span)) + }) + .collect::<Result<Vec<_>>>()?; + + // count is at least 1 + let first = &variant_lits[0]; + let rest = &variant_lits[1..]; + + quote!(matches!(*bits, #first #(| #rest )*)) + }; + + let repr = get_repr(&input.attrs)?; + let integer_ty = repr.repr.as_integer_type().unwrap(); // should be checked in attr check already + Ok(( + quote!(), + quote! { + type Bits = #integer_ty; + + #[inline] + #[allow(clippy::double_comparisons)] + fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { + #check + } + }, + )) +} + +/// Check that a struct has no padding by asserting that the size of the struct +/// is equal to the sum of the size of it's fields +fn generate_assert_no_padding(input: &DeriveInput) -> Result<TokenStream> { + let struct_type = &input.ident; + let span = input.ident.span(); + let fields = get_fields(input)?; + + let mut field_types = get_field_types(&fields); + let size_sum = if let Some(first) = field_types.next() { + let size_first = quote_spanned!(span => ::core::mem::size_of::<#first>()); + let size_rest = + quote_spanned!(span => #( + ::core::mem::size_of::<#field_types>() )*); + + quote_spanned!(span => #size_first#size_rest) + } else { + quote_spanned!(span => 0) + }; + + Ok(quote_spanned! {span => const _: fn() = || { + struct TypeWithoutPadding([u8; #size_sum]); + let _ = ::core::mem::transmute::<#struct_type, TypeWithoutPadding>; + };}) +} + +/// Check that all fields implement a given trait +fn generate_fields_are_trait( + input: &DeriveInput, trait_: syn::Path, +) -> Result<TokenStream> { + let (impl_generics, _ty_generics, where_clause) = + input.generics.split_for_impl(); + let fields = get_fields(input)?; + let span = input.span(); + let field_types = get_field_types(&fields); + Ok(quote_spanned! {span => #(const _: fn() = || { + #[allow(clippy::missing_const_for_fn)] + fn check #impl_generics () #where_clause { + fn assert_impl<T: #trait_>() {} + assert_impl::<#field_types>(); + } + };)* + }) +} + +fn get_ident_from_stream(tokens: TokenStream) -> Option<Ident> { + match tokens.into_iter().next() { + Some(TokenTree::Group(group)) => get_ident_from_stream(group.stream()), + Some(TokenTree::Ident(ident)) => Some(ident), + _ => None, + } +} + +/// get a simple #[foo(bar)] attribute, returning "bar" +fn get_simple_attr(attributes: &[Attribute], attr_name: &str) -> Option<Ident> { + for attr in attributes { + if let (AttrStyle::Outer, Some(outer_ident), Some(inner_ident)) = ( + &attr.style, + attr.path.get_ident(), + get_ident_from_stream(attr.tokens.clone()), + ) { + if outer_ident.to_string() == attr_name { + return Some(inner_ident); + } + } + } + + None +} + +fn get_repr(attributes: &[Attribute]) -> Result<Representation> { + attributes + .iter() + .filter_map(|attr| { + if attr.path.is_ident("repr") { + Some(attr.parse_args::<Representation>()) + } 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) { + (a, None) => a, + (None, b) => b, + _ => bail!("conflicting representation hints"), + }, + }) + }) +} + +mk_repr! { + U8 => u8, + I8 => i8, + U16 => u16, + I16 => i16, + U32 => u32, + I32 => i32, + U64 => u64, + I64 => i64, + I128 => i128, + U128 => u128, +} +// where +macro_rules! mk_repr {( + $( + $Xn:ident => $xn:ident + ),* $(,)? +) => ( + #[derive(Clone, Copy, PartialEq)] + enum Repr { + Rust, + C, + Transparent, + $($Xn),* + } + + impl Repr { + fn is_integer(self) -> bool { + match self { + Repr::Rust | Repr::C | Repr::Transparent => false, + _ => true, + } + } + + fn as_integer_type(self) -> Option<TokenStream> { + match self { + Repr::Rust | Repr::C | Repr::Transparent => None, + $( + Repr::$Xn => Some(quote! { ::core::primitive::$xn }), + )* + } + } + } + + #[derive(Clone, Copy)] + struct Representation { + packed: Option<u32>, + align: Option<u32>, + 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<Representation> { + let mut ret = Representation::default(); + while !input.is_empty() { + let keyword = input.parse::<Ident>()?; + // 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::<u32>(&contents.parse()?)? + } else { + 1 + }); + let _: Option<Token![,]> = input.parse()?; + continue; + }, + "align" => { + let contents; parenthesized!(contents in input); + ret.align = Some(LitInt::base10_parse::<u32>(&contents.parse()?)?); + let _: Option<Token![,]> = input.parse()?; + continue; + }, + $( + stringify!($xn) => Repr::$Xn, + )* + _ => return Err(input.error("unrecognized representation hint")) + }; + if ::core::mem::replace(&mut ret.repr, new_repr) != Repr::Rust { + input.error("duplicate representation hint"); + } + let _: Option<Token![,]> = input.parse()?; + } + Ok(ret) + } + } + + impl ToTokens for Representation { + fn to_tokens(&self, tokens: &mut TokenStream) { + let repr = match self.repr { + Repr::Rust => None, + Repr::C => Some(quote!(C)), + Repr::Transparent => Some(quote!(transparent)), + $( + Repr::$Xn => Some(quote!($xn)), + )* + }; + let packed = self.packed.map(|p| quote!(packed(#p))); + let comma = if packed.is_some() && repr.is_some() { + Some(quote!(,)) + } else { + None + }; + tokens.extend(quote!( + #[repr( #repr #comma #packed )] + )); + } + } +)} +use mk_repr; + +struct VariantDiscriminantIterator<'a, I: Iterator<Item = &'a Variant> + 'a> { + inner: I, + last_value: i64, +} + +impl<'a, I: Iterator<Item = &'a Variant> + 'a> + VariantDiscriminantIterator<'a, I> +{ + fn new(inner: I) -> Self { + VariantDiscriminantIterator { inner, last_value: -1 } + } +} + +impl<'a, I: Iterator<Item = &'a Variant> + 'a> Iterator + for VariantDiscriminantIterator<'a, I> +{ + type Item = Result<i64>; + + fn next(&mut self) -> Option<Self::Item> { + let variant = self.inner.next()?; + if !variant.fields.is_empty() { + return Some(Err(Error::new_spanned( + &variant.fields, + "Only fieldless enums are supported", + ))); + } + + 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 { + self.last_value += 1; + } + + Some(Ok(self.last_value)) + } +} + +fn parse_int_expr(expr: &Expr) -> Result<i64> { + 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"), + } +} diff --git a/tests/basic.rs b/tests/basic.rs new file mode 100644 index 0000000..755a667 --- /dev/null +++ b/tests/basic.rs @@ -0,0 +1,253 @@ +#![allow(dead_code)] + +use bytemuck::{ + AnyBitPattern, CheckedBitPattern, Contiguous, NoUninit, Pod, + TransparentWrapper, Zeroable, +}; +use std::marker::PhantomData; + +#[derive(Copy, Clone, Pod, Zeroable)] +#[repr(C)] +struct Test { + a: u16, + b: u16, +} + +#[derive(Pod, Zeroable)] +#[repr(C, packed)] +struct GenericPackedStruct<T: Pod> { + a: u32, + b: T, + c: u32, +} + +impl<T: Pod> Clone for GenericPackedStruct<T> { + fn clone(&self) -> Self { + *self + } +} + +impl<T: Pod> Copy for GenericPackedStruct<T> {} + +#[derive(Pod, Zeroable)] +#[repr(C, packed(1))] +struct GenericPackedStructExplicitPackedAlignment<T: Pod> { + a: u32, + b: T, + c: u32, +} + +impl<T: Pod> Clone for GenericPackedStructExplicitPackedAlignment<T> { + fn clone(&self) -> Self { + *self + } +} + +impl<T: Pod> Copy for GenericPackedStructExplicitPackedAlignment<T> {} + +#[derive(Zeroable)] +struct ZeroGeneric<T: bytemuck::Zeroable> { + a: T, +} + +#[derive(TransparentWrapper)] +#[repr(transparent)] +struct TransparentSingle { + a: u16, +} + +#[derive(TransparentWrapper)] +#[repr(transparent)] +#[transparent(u16)] +struct TransparentWithZeroSized<T> { + a: u16, + b: PhantomData<T>, +} + +#[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, AnyBitPattern, PartialEq, Eq)] +#[repr(C)] +struct AnyBitPatternTest { + a: u16, + b: u16, +} + +/// ```compile_fail +/// use bytemuck::{Pod, Zeroable}; +/// +/// #[derive(Pod, Zeroable)] +/// #[repr(transparent)] +/// struct TransparentSingle<T>(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>(T); + +#[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::<CheckedBitPatternEnumWithValues>(&[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::<CheckedBitPatternEnumNonContiguous>(&[ + 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::<u8, CheckedBitPatternEnumByteLit>(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::<CheckedBitPatternStruct>(&pod); + assert!(res.is_err()); +} + +#[test] +fn passes_cast_struct() { + let pod = [0u8, 8u8]; + let res = bytemuck::checked::from_bytes::<CheckedBitPatternStruct>(&pod); + assert_eq!( + *res, + CheckedBitPatternStruct { a: 0, b: CheckedBitPatternEnumNonContiguous::B } + ); +} + +#[test] +fn anybitpattern_implies_zeroable() { + let test = AnyBitPatternTest::zeroed(); + assert_eq!(test, AnyBitPatternTest { a: 0, b: 0 }); +} + +#[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()); +} + +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +#[repr(C, align(16))] +struct Issue127 {} |