Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"files":{"Cargo.lock":"cc4cec9d0cb5fd186a5fcb3b84caa5718eeecafa8955db50bb98725e195f11cd","Cargo.toml":"96e1d8d28b24cb63396ac4b306c622f982681298b4d3e3854a90c2419197aa70","LICENSE-APACHE":"e3ba223bb1423f0aad8c3dfce0fe3148db48926d41e6fbc3afbbf5ff9e1c89cb","LICENSE-MIT":"9df9ba60a11af705f2e451b53762686e615d86f76b169cf075c3237730dbd7e2","LICENSE-ZLIB":"84b34dd7608f7fb9b17bd588a6bf392bf7de504e2716f024a77d89f1b145a151","README.md":"09d8238fd7fdac39857da88e090667d8327ca9ac240768e216ef2079c2f06846","changelog.md":"b6c50e2af3372f2e3ad08365b46084420c419606659b2429f5c700615c6f24be","src/lib.rs":"2f569eb8538918193ca930bf5da27677e6ac3c5c4929c8725df03af94125a90a","src/traits.rs":"d876c5e0548afe7948e1de40e4d9759b4cb74b394493530d4c236246ddc92173","tests/basic.rs":"00610a43f3eb66bf7fcab285815c839fc33c1c5e31f59cf7c1886e69ba6ba285"},"package":"4f154e572231cb6ba2bd1176980827e3d5dc04cc183a75dea38109fbdd672d29"}

47
vendor/bytemuck_derive/Cargo.lock generated vendored Normal file
View File

@@ -0,0 +1,47 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "bytemuck_derive"
version = "1.10.1"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"

56
vendor/bytemuck_derive/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,56 @@
# 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.1"
authors = ["Lokathor <zefria@gmail.com>"]
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]

61
vendor/bytemuck_derive/LICENSE-APACHE vendored Normal file
View File

@@ -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.

9
vendor/bytemuck_derive/LICENSE-MIT vendored Normal file
View File

@@ -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.

11
vendor/bytemuck_derive/LICENSE-ZLIB vendored Normal file
View File

@@ -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.

4
vendor/bytemuck_derive/README.md vendored Normal file
View File

@@ -0,0 +1,4 @@
# bytemuck_derive
Derive macros for [bytemuck](https://docs.rs/bytemuck) traits.

111
vendor/bytemuck_derive/changelog.md vendored Normal file
View File

@@ -0,0 +1,111 @@
## `bytemuck_derive` changelog
## 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.

707
vendor/bytemuck_derive/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,707 @@
//! 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, B> {
/// a: A,
/// b: PhantomData<B>,
/// }
/// ```
///
/// 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: 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, B> {
/// a: A,
/// b: PhantomData<B>,
/// }
///
/// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<u32> });
/// ```
///
/// ```compile_fail
/// # use bytemuck::{Pod, Zeroable};
/// # use std::marker::PhantomData;
/// # #[derive(Copy, Clone, Pod, Zeroable)]
/// # #[repr(transparent)]
/// # struct Generic<A, B> {
/// # a: A,
/// # b: PhantomData<B>,
/// # }
/// struct NotPod;
///
/// let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<NotPod> });
/// ```
#[proc_macro_derive(Pod, attributes(bytemuck))]
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, attributes(bytemuck))]
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 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<T> {
/// a: PhantomData<T>,
/// }
///
/// AlwaysZeroable::<std::num::NonZeroU8>::zeroed();
/// ```
/// ```rust
/// # use bytemuck::{Zeroable};
/// #[derive(Copy, Clone, Zeroable)]
/// #[repr(u8)]
/// #[zeroable(bound = "")]
/// enum MyOption<T> {
/// None,
/// Some(T),
/// }
///
/// assert!(matches!(MyOption::<std::num::NonZeroU8>::zeroed(), MyOption::None));
/// ```
///
/// ```rust,compile_fail
/// # use bytemuck::Zeroable;
/// # use std::marker::PhantomData;
/// #[derive(Clone, Zeroable)]
/// #[zeroable(bound = "T: Copy")]
/// struct ZeroableWhenTIsCopy<T> {
/// a: PhantomData<T>,
/// }
///
/// ZeroableWhenTIsCopy::<String>::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<T> {
/// a: T,
/// }
/// ZeroableWhenTIsZeroable::<u32>::zeroed();
/// ```
///
/// ```rust,compile_fail
/// # use bytemuck::Zeroable;
/// # #[derive(Clone, Zeroable)]
/// # #[zeroable(bound = "")]
/// # struct ZeroableWhenTIsZeroable<T> {
/// # a: T,
/// # }
/// ZeroableWhenTIsZeroable::<String>::zeroed();
/// ```
#[proc_macro_derive(Zeroable, attributes(bytemuck, 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)]`, `#[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::<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:
///
/// 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::<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
/// - 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)]`
///
/// ## Examples
///
/// ```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>,
/// }
/// ```
///
/// 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<T> {
/// inner: u16,
/// extra: PhantomData<T>,
/// }
/// ```
///
/// 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<T> {
/// inner: u16,
/// extra: PhantomData<T>,
/// 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::<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.
///
/// ## 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<const N: usize> {
/// a: [u32; N],
/// }
/// unsafe impl<const N: usize> NoUninit for Test<N> {}
/// ```
#[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<const N: usize> {
/// a: [u32; N],
/// }
/// unsafe impl<const N: usize> NoUninit for Test<N> {}
/// ```
#[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<H: ::core::hash::Hasher>(&self, state: &mut H) {
::core::hash::Hash::hash_slice(#crate_name::bytes_of(self), state)
}
#[inline]
fn hash_slice<H: ::core::hash::Hasher>(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<Trait: Derivable>(input: DeriveInput) -> TokenStream {
derive_marker_trait_inner::<Trait>(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<P: syn::parse::Parser + Copy>(
attributes: &[syn::Attribute], name: &str, key: &str, parser: P,
example_value: &str, invalid_value_msg: &str,
) -> Result<Vec<P::Output>> {
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<Trait: Derivable>(
mut input: DeriveInput,
) -> Result<TokenStream> {
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",
<syn::punctuated::Punctuated<syn::WherePredicate, syn::Token![,]>>::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::<Vec<syn::WherePredicate>>();
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| &param.ident)
.map(|param| {
syn::parse_quote!(
#param: #trait_name
)
})
.collect::<Vec<syn::WherePredicate>>();
generics.make_where_clause().predicates.extend(type_params);
}

1614
vendor/bytemuck_derive/src/traits.rs vendored Normal file

File diff suppressed because it is too large Load Diff

559
vendor/bytemuck_derive/tests/basic.rs vendored Normal file
View File

@@ -0,0 +1,559 @@
#![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<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(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<T> {
A(Box<T>) = 1,
B(T, T) = 0,
}
#[derive(Zeroable)]
#[repr(i32)]
#[zeroable(bound = "")]
enum GenericCustomBoundFieldfulZeroEnum<T> {
A(Option<Box<T>>),
B(String),
}
#[derive(TransparentWrapper)]
#[repr(transparent)]
struct TransparentSingle {
a: u16,
}
#[derive(TransparentWrapper)]
#[repr(transparent)]
#[transparent(u16)]
struct TransparentWithZeroSized<T> {
a: u16,
b: PhantomData<T>,
}
struct MyZst<T>(PhantomData<T>, [u8; 0], PhantomPinned);
unsafe impl<T> Zeroable for MyZst<T> {}
#[derive(TransparentWrapper)]
#[repr(transparent)]
#[transparent(u16)]
struct TransparentTupleWithCustomZeroSized<T>(u16, MyZst<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, 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: AnyBitPattern, B: AnyBitPattern> {
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>(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::<isize, usize>::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::<CheckedBitPatternAlignedStruct>(&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::<CheckedBitPatternEnumNested>(&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::<CheckedBitPatternEnumNested>(&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::<CheckedBitPatternEnumNested>(&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::<CheckedBitPatternEnumNested>(&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 {}