aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKaiyi Li <kaiyili@google.com>2023-07-24 18:09:39 -0700
committerKaiyi Li <kaiyili@google.com>2023-07-24 18:17:36 -0700
commit8ff219fec22001ab03625471a59623644108cfbf (patch)
tree3f106d83efd21dbe7c8e355d0b66447aa973519f
parent3dc91939ea2397c9fdc3635653162d429dbecce1 (diff)
downloadbytemuck-main-16k.tar.gz
Import 'bytemuck' cratemain-16k
Bug: b/288486627 Change-Id: I9212a07639cf1476274cf647a203e5f0175af98f
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--.github/FUNDING.yml3
-rw-r--r--.github/workflows/rust.yml113
-rw-r--r--.gitignore10
-rw-r--r--Cargo.toml69
-rw-r--r--Cargo.toml.orig57
l---------LICENSE1
-rw-r--r--LICENSE-APACHE61
-rw-r--r--LICENSE-MIT9
-rw-r--r--LICENSE-ZLIB11
-rw-r--r--METADATA20
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--OWNERS1
-rw-r--r--README.md60
-rw-r--r--changelog.md252
-rw-r--r--rustfmt.toml16
-rw-r--r--src/allocation.rs688
-rw-r--r--src/anybitpattern.rs60
-rw-r--r--src/checked.rs527
-rw-r--r--src/contiguous.rs202
-rw-r--r--src/internal.rs382
-rw-r--r--src/lib.rs400
-rw-r--r--src/no_uninit.rs80
-rw-r--r--src/offset_of.rs135
-rw-r--r--src/pod.rs148
-rw-r--r--src/pod_in_option.rs27
-rw-r--r--src/transparent.rs288
-rw-r--r--src/zeroable.rs235
-rw-r--r--src/zeroable_in_option.rs34
-rw-r--r--tests/array_tests.rs12
-rw-r--r--tests/cast_slice_tests.rs194
-rw-r--r--tests/checked_tests.rs416
-rw-r--r--tests/derive.rs77
-rw-r--r--tests/doc_tests.rs123
-rw-r--r--tests/offset_of_tests.rs60
-rw-r--r--tests/std_tests.rs46
-rw-r--r--tests/transparent.rs116
-rw-r--r--tests/wrapper_forgets.rs13
38 files changed, 4952 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..499b132
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "b19f8abfe34d6ab660e748086874c01e0212b738"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000..3509ccc
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+# These are supported funding model platforms
+
+github: [Lokathor]
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
new file mode 100644
index 0000000..0807319
--- /dev/null
+++ b/.github/workflows/rust.yml
@@ -0,0 +1,113 @@
+name: Rust
+
+on:
+ push: {}
+ pull_request: {}
+
+env:
+ RUST_BACKTRACE: 1
+
+jobs:
+ test:
+ name: Test Rust ${{ matrix.rust }} on ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ # it's a little tempting to use `matrix` to do a cartesian product with
+ # our `--feature` config here, but doing so will be very slow, as the
+ # free tier only supports up to 20 job runners at a time.
+ include:
+ # versions (all on linux-x86_64)
+ - { rust: 1.34.0, os: ubuntu-latest }
+ - { rust: stable, os: ubuntu-latest }
+ - { rust: beta, os: ubuntu-latest }
+ - { rust: nightly, os: ubuntu-latest }
+ # non-linux platforms (ones which don't require `cross`)
+ - { rust: stable, os: macos-latest }
+ - { rust: stable, os: windows-latest }
+ - { rust: stable-x86_64-gnu, os: windows-latest }
+ - { rust: stable-i686-msvc, os: windows-latest }
+ - { rust: stable-i686-gnu, os: windows-latest }
+ steps:
+ - uses: hecrj/setup-rust-action@v1
+ with:
+ rust-version: ${{ matrix.rust }}
+ - uses: actions/checkout@v3
+ - run: cargo test --verbose
+ - run: cargo test --verbose --no-default-features
+ - run: cargo test --verbose
+ - run: cargo test --verbose --all-features
+ if: matrix.rust == 'nightly'
+ - run: cargo test --verbose --manifest-path=derive/Cargo.toml --all-features
+ if: matrix.rust == 'nightly'
+
+ cross-test:
+ name: Test on ${{ matrix.target }} with cross
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ # note: the mips targets are here so that we have big-endian coverage (both 32bit and 64bit)
+ target: [i686-unknown-linux-gnu, mips-unknown-linux-gnu, mips64-unknown-linux-gnuabi64]
+ steps:
+ - uses: hecrj/setup-rust-action@v1
+ with:
+ rust-version: nightly
+ - uses: actions/checkout@v3
+ - run: cargo install cross
+ - run: cross test --verbose --target=${{ matrix.target }} --no-default-features
+ - run: cross test --verbose --target=${{ matrix.target }}
+ - run: cross test --verbose --target=${{ matrix.target }} --all-features
+ if: matrix.rust == 'nightly'
+ - run: cross test --verbose --target=${{ matrix.target }} --manifest-path=derive/Cargo.toml --all-features
+ if: matrix.rust == 'nightly'
+
+ miri-test:
+ name: Test with miri
+ runs-on: ubuntu-latest
+ env:
+ MIRIFLAGS: -Zmiri-tag-raw-pointers
+ steps:
+ - uses: hecrj/setup-rust-action@v1
+ with:
+ rust-version: nightly
+ components: miri
+ - uses: actions/checkout@v3
+ # Note(Lokathor): We got some cached json errors, and so we cargo clean for this run.
+ - run: rm -fr target
+ - run: cargo miri test --verbose --no-default-features
+ - run: cargo miri test --verbose --all-features
+ - run: cd derive && rm -fr target && cargo miri test --verbose --all-features
+
+ sanitizer-test:
+ name: Test with -Zsanitizer=${{ matrix.sanitizer }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ sanitizer: [address, memory, leak]
+ steps:
+ - uses: actions/checkout@v3
+ - uses: hecrj/setup-rust-action@v1
+ with:
+ rust-version: nightly
+ components: rust-src
+ - name: Test with sanitizer
+ env:
+ RUSTFLAGS: -Zsanitizer=${{ matrix.sanitizer }}
+ RUSTDOCFLAGS: -Zsanitizer=${{ matrix.sanitizer }}
+ ASAN_OPTIONS: detect_stack_use_after_return=1
+ # Asan's leak detection occasionally complains about some small leaks if
+ # backtraces are captured.
+ RUST_BACKTRACE: 0
+ # We don't run `derive`'s unit tests here the way we do elsewhere (for
+ # example, in `miri-test` above), as at the moment we can't easily build
+ # the `proc_macro` runtime with sanitizers on. IIUC doing this would
+ # require a custom rustc build, and... lol nope.
+ #
+ # This would mean only part of the code running under the sanitizer would
+ # actually include the sanitizer's checks, which is a recipe for false
+ # positives, so we just skip it, the generated code is what we care
+ # about anyway.
+ run: |
+ cargo test -Zbuild-std --verbose --target=x86_64-unknown-linux-gnu --no-default-features
+ cargo test -Zbuild-std --verbose --target=x86_64-unknown-linux-gnu --all-features
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..69e45ed
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+
+Cargo.lock
+/target/
+/.vscode/
+
+# These are backup files generated by rustfmt
+**/*.rs.bk
+
+/derive/target/
+/derive/.vscode/
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..b7d55e8
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,69 @@
+# 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"
+version = "1.13.1"
+authors = ["Lokathor <zefria@gmail.com>"]
+exclude = ["/pedantic.bat"]
+description = "A crate for mucking around with piles of bytes."
+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"
+
+[package.metadata.docs.rs]
+features = [
+ "derive",
+ "extern_crate_alloc",
+ "extern_crate_std",
+ "zeroable_maybe_uninit",
+ "zeroable_atomics",
+ "min_const_generics",
+ "wasm_simd",
+]
+
+[package.metadata.playground]
+features = [
+ "derive",
+ "extern_crate_alloc",
+ "extern_crate_std",
+ "zeroable_maybe_uninit",
+ "zeroable_atomics",
+ "min_const_generics",
+ "wasm_simd",
+]
+
+[dependencies.bytemuck_derive]
+version = "1.4"
+optional = true
+
+[features]
+aarch64_simd = []
+derive = ["bytemuck_derive"]
+extern_crate_alloc = []
+extern_crate_std = ["extern_crate_alloc"]
+min_const_generics = []
+nightly_portable_simd = []
+nightly_stdsimd = []
+unsound_ptr_pod_impl = []
+wasm_simd = []
+zeroable_atomics = []
+zeroable_maybe_uninit = []
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..9d6be11
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,57 @@
+[package]
+name = "bytemuck"
+description = "A crate for mucking around with piles of bytes."
+version = "1.13.1"
+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"
+exclude = ["/pedantic.bat"]
+
+[features]
+# In v2 we'll fix these names to be more "normal".
+derive = ["bytemuck_derive"]
+extern_crate_alloc = []
+extern_crate_std = ["extern_crate_alloc"]
+zeroable_maybe_uninit = []
+zeroable_atomics = []
+min_const_generics = []
+wasm_simd = [] # Until >= 1.54.0 is MSRV this is an off-by-default feature.
+aarch64_simd = [] # Until >= 1.59.0 is MSRV this is an off-by-default feature.
+
+# Do not use if you can avoid it, because this is unsound.
+unsound_ptr_pod_impl = []
+
+# NOT SEMVER SUPPORTED! TEMPORARY ONLY!
+nightly_portable_simd = []
+nightly_stdsimd = []
+
+[dependencies]
+bytemuck_derive = { version = "1.4", path = "derive", optional = true }
+
+[package.metadata.docs.rs]
+# Note(Lokathor): Don't use all-features or it would use `unsound_ptr_pod_impl` too.
+features = [
+ "derive",
+ "extern_crate_alloc",
+ "extern_crate_std",
+ "zeroable_maybe_uninit",
+ "zeroable_atomics",
+ "min_const_generics",
+ "wasm_simd",
+]
+
+[package.metadata.playground]
+# Note(Lokathor): Don't use all-features or it would use `unsound_ptr_pod_impl` too.
+features = [
+ "derive",
+ "extern_crate_alloc",
+ "extern_crate_std",
+ "zeroable_maybe_uninit",
+ "zeroable_atomics",
+ "min_const_generics",
+ "wasm_simd",
+]
diff --git a/LICENSE b/LICENSE
new file mode 120000
index 0000000..6b579aa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1 @@
+LICENSE-APACHE \ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..1d02268
--- /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..0aa8816
--- /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..aa2dabe
--- /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/METADATA b/METADATA
new file mode 100644
index 0000000..bd36741
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,20 @@
+name: "bytemuck"
+description: "A crate for mucking around with piles of bytes."
+third_party {
+ url {
+ type: HOMEPAGE
+ value: "https://crates.io/crates/bytemuck"
+ }
+ url {
+ type: ARCHIVE
+ value: "https://static.crates.io/crates/bytemuck/bytemuck-1.13.1.crate"
+ }
+ version: "1.13.1"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2023
+ month: 7
+ day: 10
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..45dc4dd
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1 @@
+include platform/prebuilts/rust:master:/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..032316f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,60 @@
+* **[Latest Docs.rs Here](https://docs.rs/bytemuck/)**
+
+[![License:Zlib](https://img.shields.io/badge/License-Zlib-brightgreen.svg)](https://opensource.org/licenses/Zlib)
+![Minimum Rust Version](https://img.shields.io/badge/Min%20Rust-1.34-green.svg)
+[![crates.io](https://img.shields.io/crates/v/bytemuck.svg)](https://crates.io/crates/bytemuck)
+
+# bytemuck
+
+A crate for mucking around with piles of bytes.
+
+This crate lets you safely perform "bit cast" operations between data types.
+That's where you take a value and just reinterpret the bits as being some other
+type of value, without changing the bits.
+
+* This is **not** like the [`as` keyword][keyword-as]
+* This is **not** like the [`From` trait][from-trait]
+* It is **most like** [`f32::to_bits`][f32-to_bits], just generalized to let you
+ convert between all sorts of data types.
+
+[keyword-as]: https://doc.rust-lang.org/nightly/std/keyword.as.html
+[from-trait]: https://doc.rust-lang.org/nightly/core/convert/trait.From.html
+[f32-to_bits]: https://doc.rust-lang.org/nightly/std/primitive.f32.html#method.to_bits
+
+### Here's the part you're more likely to care about: *you can do this with slices too!*
+
+When a slice is involved it's not a *direct* bitcast. Instead, the `cast_slice`
+and `cast_slice_mut` functions will pull apart a slice's data and give you a new
+slice that's the same span of memory just viewed as the new type. If the size of
+the slice's element changes then the length of the slice you get back will be
+changed accordingly.
+
+This lets you cast a slice of color values into a slice of `u8` and send it to
+the GPU, or things like that. I'm sure there's other examples, but honestly this
+crate is as popular as it is mostly because of Rust's 3D graphics community
+wanting to cast slices of different types into byte slices for sending to the
+GPU. Hi friends! Push those vertices, or whatever it is that you all do.
+
+## See Also
+
+While `bytemuck` is full of unsafe code, I've also started a "sibling crate"
+called [bitfrob](https://docs.rs/bitfrob/latest/bitfrob/), which is where
+operations that are 100% safe will be added.
+
+## Stability
+
+* The crate is 1.0 and I consider this it to be "basically done". New features
+ are usually being accepted when other people want to put in the work, but
+ myself I wanna move on to using `bytemuck` in bigger projects.
+* The default build of the `bytemuck` crate will continue to work with `rustc-1.34`
+ for at least the rest of the `1.y.z` versions.
+* Any other cargo features of the crate **are not** held to the same standard, and
+ may work only on the latest Stable or even only on latest Nightly.
+
+**Future Plans:** Once the [Safe Transmute Project][pg-st] completes and
+stabilizes ("eventually") this crate will be updated to use that as the
+underlying mechanism for transmutation bounds, and a 2.0 version of `bytemuck`
+will be released. The hope is for the 1.0 to 2.0 transition to be as seamless as
+possible, but the future is always uncertain.
+
+[pg-st]: https://rust-lang.github.io/rfcs/2835-project-safe-transmute.html
diff --git a/changelog.md b/changelog.md
new file mode 100644
index 0000000..0dff0c2
--- /dev/null
+++ b/changelog.md
@@ -0,0 +1,252 @@
+# `bytemuck` changelog
+
+## 1.13.1
+
+* Remove the requirement for the *source* data type to be `AnyBitPattern` on
+ `pod_collect_to_vec`, allowing you to pod collect vecs of `char` into vecs of
+ `u32`, or whatever.
+
+## 1.13
+
+* Now depends on `bytemuck_derive-1.4.0`
+* Various small enhancements that would have been patch version updates, but
+ which have been rolled into this minor version update.
+
+## 1.12.4
+
+* This has additional impls for existing traits and cleans up some internal code,
+ but there's no new functions so I guess it counts as just a patch release.
+
+## 1.12.3
+
+* This bugfix makes the crate do stuff with `Arc` or not based on the
+ `target_has_atomic` config. Previously, some targets that have allocation but
+ not atomics were getting errors. This raises the MSRV of the
+ `extern_crate_alloc` feature to 1.60, but opt-in features are *not* considered
+ to be hard locked to 1.34 like the basic build of the crate is.
+
+## 1.12.2
+
+* Fixes `try_pod_read_unaligned` bug that made it always fail unless the target
+ type was exactly pointer sized in which case UB *could* happen. The
+ `CheckedBitPattern::is_valid_bit_pattern` was being asked to check that a
+ *reference* to the `pod` value was a valid bit pattern, rather than the actual
+ bit pattern itself, and so the check could in some cases be illegally
+ bypassed.
+
+## 1.12.1
+
+* Patch bumped the required `bytemuck_derive` version because of a regression in
+ how it handled `align(N)` attributes.
+
+## 1.12
+
+* This minor version bump is caused by a version bump in our `bytemuck_derive`
+ dependency, which is in turn caused by a mixup in the minimum version of `syn`
+ that `bytemuck_derive` uses. See [Issue
+ 122](https://github.com/Lokathor/bytemuck/issues/122). There's not any
+ specific "new" API as you might normally expect from a minor version bump.
+* [pali](https://github.com/pali6) fixed a problem with SPIR-V builds being
+ broken. The error handling functions were trying to be generic over `Display`,
+ which the error types normally support, except on SPIR-V targets (which run on
+ the GPU and don't have text formatting).
+
+## 1.11
+
+* [WaffleLapkin](https://github.com/WaffleLapkin) added `wrap_box` and `peel_box`
+ to the `TransparentWrapperAlloc` trait. Default impls of these functions are
+ provided, and (as usual with the transparent trait stuff) you should not override
+ the default versions.
+
+## 1.10
+
+* [TheEdward162](https://github.com/TheEdward162) added the `ZeroableInOption`
+ and `PodInOption` traits. These are for types that are `Zeroable` or `Pod`
+ *when in an option*, but not on their own. We provide impls for the various
+ "NonZeroINTEGER" types in `core`, and if you need to newtype a NonZero value
+ then you can impl these traits when you use `repr(transparent)`.
+
+## 1.9.1
+
+* Bumped the minimum `bytemuck_derive` dependency version from `1.0` to `1.1`.
+ The fact that `bytemuck` and `bytemuck_derive` are separate crates at all is
+ an unfortunate technical limit of current Rust, woe and calamity.
+
+## 1.9.0
+
+* [fu5ha](https://github.com/fu5ha) added the `NoUninit`, `AnyBitPattern`, and
+ `CheckedBitPattern` traits. This allows for a more fine-grained level of
+ detail in what casting operations are allowed for a type. Types that already
+ implement `Zeroable` and `Pod` will have a blanket impl for these new traits.
+ This is a "preview" of the direction that the crate will probably go in the
+ eventual 2.0 version. We're still waiting on [Project Safe
+ Transmute](https://github.com/rust-lang/project-safe-transmute) for an actual
+ 2.0 version of the crate, but until then please enjoy this preview.
+* Also Fusha added better support for `union` types in the derive macros. I
+ still don't know how any of the proc-macro stuff works at all, so please
+ direct questions to her.
+
+## 1.8.0
+
+* `try_pod_read_unaligned` and `pod_read_unaligned` let you go from `&[u8]` to
+ `T:Pod` without worrying about alignment.
+
+## 1.7.3
+
+* Experimental support for the `portable_simd` language extension under the
+ `nightly_portable_simd` cargo feature. As the name implies, this is an
+ experimental crate feature and it's **not** part of the semver contract. All
+ it does is add the appropriate `Zeroable` and `Pod` impls.
+
+## 1.7.2
+
+* Why does this repo keep being hit with publishing problems? What did I do to
+ deserve this curse, Ferris? This doesn't ever happen with tinyvec or fermium,
+ only bytemuck.
+
+## 1.7.1
+
+* **Soundness Fix:** The wrap/peel methods for owned value conversion, added to
+ `TransparentWrapper` in 1.6, can cause a double-drop if used with types that
+ impl `Drop`. The fix was simply to add a `ManuallyDrop` layer around the value
+ before doing the `transmute_copy` that is used to wrap/peel. While this fix
+ could technically be backported to the 1.6 series, since 1.7 is semver
+ compatible anyway the 1.6 series has simply been yanked.
+
+## 1.7
+
+* In response to [Unsafe Code Guidelines Issue
+ #286](https://github.com/rust-lang/unsafe-code-guidelines/issues/286), this
+ version of Bytemuck has a ***Soundness-Required Breaking Change***. This is
+ "allowed" under Rust's backwards-compatibility guidelines, but it's still
+ annoying of course so we're trying to keep the damage minimal.
+ * **The Reason:** It turns out that pointer values should not have been `Pod`. More
+ specifically, `ptr as usize` is *not* the same operation as calling
+ `transmute::<_, usize>(ptr)`.
+ * LLVM has yet to fully sort out their story, but until they do, transmuting
+ pointers can cause miscompilations. They may fix things up in the future,
+ but we're not gonna just wait and have broken code in the mean time.
+ * **The Fix:** The breaking change is that the `Pod` impls for `*const T`,
+ `*mut T`, and `Option<NonNull<T>` are now gated behind the
+ `unsound_ptr_pod_impl` feature, which is off by default.
+ * You are *strongly discouraged* from using this feature, but if a dependency
+ of yours doesn't work when you upgrade to 1.7 because it relied on pointer
+ casting, then you might wish to temporarily enable the feature just to get
+ that dependency to build. Enabled features are global across all users of a
+ given semver compatible version, so if you enable the feature in your own
+ crate, your dependency will also end up getting the feature too, and then
+ it'll be able to compile.
+ * Please move away from using this feature as soon as you can. Consider it to
+ *already* be deprecated.
+ * [PR 65](https://github.com/Lokathor/bytemuck/pull/65)
+
+## 1.6.3
+
+* Small goof with an errant `;`, so [PR 69](https://github.com/Lokathor/bytemuck/pull/69)
+ *actually* got things working on SPIR-V.
+
+## 1.6.2
+
+cargo upload goof! ignore this one.
+
+## 1.6.1
+
+* [DJMcNab](https://github.com/DJMcNab) did a fix so that the crate can build for SPIR-V
+ [PR 67](https://github.com/Lokathor/bytemuck/pull/67)
+
+## 1.6
+
+* The `TransparentWrapper` trait now has more methods. More ways to wrap, and
+ now you can "peel" too! Note that we don't call it "unwrap" because that name
+ is too strongly associated with the Option/Result methods.
+ Thanks to [LU15W1R7H](https://github.com/LU15W1R7H) for doing
+ [PR 58](https://github.com/Lokathor/bytemuck/pull/58)
+* Min Const Generics! Now there's Pod and Zeroable for arrays of any size when
+ you turn on the `min_const_generics` crate feature.
+ [zakarumych](https://github.com/zakarumych) got the work started in
+ [PR 59](https://github.com/Lokathor/bytemuck/pull/59),
+ and [chorman0773](https://github.com/chorman0773) finished off the task in
+ [PR 63](https://github.com/Lokathor/bytemuck/pull/63)
+
+## 1.5.1
+
+* Fix `bytes_of` failing on zero sized types.
+ [PR 53](https://github.com/Lokathor/bytemuck/pull/53)
+
+## 1.5
+
+* Added `pod_collect_to_vec`, which will gather a slice into a vec,
+allowing you to change the pod type while also safely ignoring alignment.
+[PR 50](https://github.com/Lokathor/bytemuck/pull/50)
+
+## 1.4.2
+
+* [Kimundi](https://github.com/Kimundi) fixed an issue that could make `try_zeroed_box`
+stack overflow for large values at low optimization levels.
+[PR 43](https://github.com/Lokathor/bytemuck/pull/43)
+
+## 1.4.1
+
+* [thomcc](https://github.com/thomcc) fixed up the CI and patched over a soundness hole in `offset_of!`.
+[PR 38](https://github.com/Lokathor/bytemuck/pull/38)
+
+## 1.4
+
+* [icewind1991](https://github.com/icewind1991) has contributed the proc-macros
+ for deriving impls of `Pod`, `TransparentWrapper`, `Zeroable`!! Everyone has
+ been waiting for this one folks! It's a big deal. Just enable the `derive`
+ cargo feature and then you'll be able to derive the traits on your types. It
+ generates all the appropriate tests for you.
+* The `zeroable_maybe_uninit` feature now adds a `Zeroable` impl to the
+ `MaybeUninit` type. This is only behind a feature flag because `MaybeUninit`
+ didn't exist back in `1.34.0` (the minimum rust version of `bytemuck`).
+
+## 1.3.1
+
+* The entire crate is now available under the `Apache-2.0 OR MIT` license as
+ well as the previous `Zlib` license
+ [#24](https://github.com/Lokathor/bytemuck/pull/24).
+* [HeroicKatora](https://github.com/HeroicKatora) added the
+ `try_zeroed_slice_box` function
+ [#10](https://github.com/Lokathor/bytemuck/pull/17). `zeroed_slice_box` is
+ also available.
+* The `offset_of!` macro now supports a 2-arg version. For types that impl
+ Default, it'll just make an instance using `default` and then call over to the
+ 3-arg version.
+* The `PodCastError` type now supports `Hash` and `Display`. Also if you enable
+ the `extern_crate_std` feature then it will support `std::error::Error`.
+* We now provide a `TransparentWrapper<T>` impl for `core::num::Wrapper<T>`.
+* The error type of `try_from_bytes` and `try_from_bytes_mut` when the input
+ isn't aligned has been corrected from being `AlignmentMismatch` (intended for
+ allocation casting only) to `TargetAlignmentGreaterAndInputNotAligned`.
+
+## 1.3.0
+
+* Had a bug because the CI was messed up! It wasn't soundness related, because
+ it prevented the crate from building entirely if the `extern_crate_alloc`
+ feature was used. Still, this is yanked, sorry.
+
+## 1.2.0
+
+* [thomcc](https://github.com/thomcc) added many things:
+ * A fully sound `offset_of!` macro
+ [#10](https://github.com/Lokathor/bytemuck/pull/10)
+ * A `Contiguous` trait for when you've got enums with declared values
+ all in a row [#12](https://github.com/Lokathor/bytemuck/pull/12)
+ * A `TransparentWrapper` marker trait for when you want to more clearly
+ enable adding and removing a wrapper struct to its inner value
+ [#15](https://github.com/Lokathor/bytemuck/pull/15)
+ * Now MIRI is run on CI in every single push!
+ [#16](https://github.com/Lokathor/bytemuck/pull/16)
+
+## 1.1.0
+
+* [SimonSapin](https://github.com/SimonSapin) added `from_bytes`,
+ `from_bytes_mut`, `try_from_bytes`, and `try_from_bytes_mut` ([PR
+ Link](https://github.com/Lokathor/bytemuck/pull/8))
+
+## 1.0.1
+
+* Changed to the [zlib](https://opensource.org/licenses/Zlib) license.
+* Added much more proper documentation.
+* Reduced the minimum Rust version to 1.34
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..a572164
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1,16 @@
+# Based on
+# https://github.com/rust-lang/rustfmt/blob/rustfmt-1.4.19/Configurations.md
+
+# Stable
+edition = "2018"
+fn_args_layout = "Compressed"
+max_width = 80
+tab_spaces = 2
+use_field_init_shorthand = true
+use_try_shorthand = true
+use_small_heuristics = "Max"
+
+# Unstable
+format_code_in_doc_comments = true
+imports_granularity = "Crate"
+wrap_comments = true
diff --git a/src/allocation.rs b/src/allocation.rs
new file mode 100644
index 0000000..0ab6625
--- /dev/null
+++ b/src/allocation.rs
@@ -0,0 +1,688 @@
+#![cfg(feature = "extern_crate_alloc")]
+
+//! Stuff to boost things in the `alloc` crate.
+//!
+//! * You must enable the `extern_crate_alloc` feature of `bytemuck` or you will
+//! not be able to use this module! This is generally done by adding the
+//! feature to the dependency in Cargo.toml like so:
+//!
+//! `bytemuck = { version = "VERSION_YOU_ARE_USING", features =
+//! ["extern_crate_alloc"]}`
+
+use super::*;
+#[cfg(target_has_atomic = "ptr")]
+use alloc::sync::Arc;
+use alloc::{
+ alloc::{alloc_zeroed, Layout},
+ boxed::Box,
+ rc::Rc,
+ vec,
+ vec::Vec,
+};
+
+/// As [`try_cast_box`](try_cast_box), but unwraps for you.
+#[inline]
+pub fn cast_box<A: NoUninit, B: AnyBitPattern>(input: Box<A>) -> Box<B> {
+ try_cast_box(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a [`Box`](alloc::boxed::Box).
+///
+/// On failure you get back an error along with the starting `Box`.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Box` must have the exact same
+/// alignment.
+/// * The start and end size of the `Box` must have the exact same size.
+#[inline]
+pub fn try_cast_box<A: NoUninit, B: AnyBitPattern>(
+ input: Box<A>,
+) -> Result<Box<B>, (PodCastError, Box<A>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Note(Lokathor): This is much simpler than with the Vec casting!
+ let ptr: *mut B = Box::into_raw(input) as *mut B;
+ Ok(unsafe { Box::from_raw(ptr) })
+ }
+}
+
+/// Allocates a `Box<T>` with all of the contents being zeroed out.
+///
+/// This uses the global allocator to create a zeroed allocation and _then_
+/// turns it into a Box. In other words, it's 100% assured that the zeroed data
+/// won't be put temporarily on the stack. You can make a box of any size
+/// without fear of a stack overflow.
+///
+/// ## Failure
+///
+/// This fails if the allocation fails.
+#[inline]
+pub fn try_zeroed_box<T: Zeroable>() -> Result<Box<T>, ()> {
+ if size_of::<T>() == 0 {
+ // This will not allocate but simply create a dangling pointer.
+ let dangling = core::ptr::NonNull::dangling().as_ptr();
+ return Ok(unsafe { Box::from_raw(dangling) });
+ }
+ let layout = Layout::new::<T>();
+ let ptr = unsafe { alloc_zeroed(layout) };
+ if ptr.is_null() {
+ // we don't know what the error is because `alloc_zeroed` is a dumb API
+ Err(())
+ } else {
+ Ok(unsafe { Box::<T>::from_raw(ptr as *mut T) })
+ }
+}
+
+/// As [`try_zeroed_box`], but unwraps for you.
+#[inline]
+pub fn zeroed_box<T: Zeroable>() -> Box<T> {
+ try_zeroed_box().unwrap()
+}
+
+/// Allocates a `Vec<T>` of length and capacity exactly equal to `length` and
+/// all elements zeroed.
+///
+/// ## Failure
+///
+/// This fails if the allocation fails, or if a layout cannot be calculated for
+/// the allocation.
+pub fn try_zeroed_vec<T: Zeroable>(length: usize) -> Result<Vec<T>, ()> {
+ if length == 0 {
+ Ok(Vec::new())
+ } else {
+ let boxed_slice = try_zeroed_slice_box(length)?;
+ Ok(boxed_slice.into_vec())
+ }
+}
+
+/// As [`try_zeroed_vec`] but unwraps for you
+pub fn zeroed_vec<T: Zeroable>(length: usize) -> Vec<T> {
+ try_zeroed_vec(length).unwrap()
+}
+
+/// Allocates a `Box<[T]>` with all contents being zeroed out.
+///
+/// This uses the global allocator to create a zeroed allocation and _then_
+/// turns it into a Box. In other words, it's 100% assured that the zeroed data
+/// won't be put temporarily on the stack. You can make a box of any size
+/// without fear of a stack overflow.
+///
+/// ## Failure
+///
+/// This fails if the allocation fails, or if a layout cannot be calculated for
+/// the allocation.
+#[inline]
+pub fn try_zeroed_slice_box<T: Zeroable>(
+ length: usize,
+) -> Result<Box<[T]>, ()> {
+ if size_of::<T>() == 0 || length == 0 {
+ // This will not allocate but simply create a dangling slice pointer.
+ let dangling = core::ptr::NonNull::dangling().as_ptr();
+ let dangling_slice = core::ptr::slice_from_raw_parts_mut(dangling, length);
+ return Ok(unsafe { Box::from_raw(dangling_slice) });
+ }
+ let layout = core::alloc::Layout::array::<T>(length).map_err(|_| ())?;
+ let ptr = unsafe { alloc_zeroed(layout) };
+ if ptr.is_null() {
+ // we don't know what the error is because `alloc_zeroed` is a dumb API
+ Err(())
+ } else {
+ let slice =
+ unsafe { core::slice::from_raw_parts_mut(ptr as *mut T, length) };
+ Ok(unsafe { Box::<[T]>::from_raw(slice) })
+ }
+}
+
+/// As [`try_zeroed_slice_box`](try_zeroed_slice_box), but unwraps for you.
+pub fn zeroed_slice_box<T: Zeroable>(length: usize) -> Box<[T]> {
+ try_zeroed_slice_box(length).unwrap()
+}
+
+/// As [`try_cast_slice_box`](try_cast_slice_box), but unwraps for you.
+#[inline]
+pub fn cast_slice_box<A: NoUninit, B: AnyBitPattern>(
+ input: Box<[A]>,
+) -> Box<[B]> {
+ try_cast_slice_box(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a `Box<[T]>`.
+///
+/// On failure you get back an error along with the starting `Box<[T]>`.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Box<[T]>` must have the exact same
+/// alignment.
+/// * The start and end content size in bytes of the `Box<[T]>` must be the
+/// exact same.
+#[inline]
+pub fn try_cast_slice_box<A: NoUninit, B: AnyBitPattern>(
+ input: Box<[A]>,
+) -> Result<Box<[B]>, (PodCastError, Box<[A]>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ if size_of::<A>() * input.len() % size_of::<B>() != 0 {
+ // If the size in bytes of the underlying buffer does not match an exact
+ // multiple of the size of B, we cannot cast between them.
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Because the size is an exact multiple, we can now change the length
+ // of the slice and recreate the Box
+ // NOTE: This is a valid operation because according to the docs of
+ // std::alloc::GlobalAlloc::dealloc(), the Layout that was used to alloc
+ // the block must be the same Layout that is used to dealloc the block.
+ // Luckily, Layout only stores two things, the alignment, and the size in
+ // bytes. So as long as both of those stay the same, the Layout will
+ // remain a valid input to dealloc.
+ let length = size_of::<A>() * input.len() / size_of::<B>();
+ let box_ptr: *mut A = Box::into_raw(input) as *mut A;
+ let ptr: *mut [B] =
+ unsafe { core::slice::from_raw_parts_mut(box_ptr as *mut B, length) };
+ Ok(unsafe { Box::<[B]>::from_raw(ptr) })
+ }
+ } else {
+ let box_ptr: *mut [A] = Box::into_raw(input);
+ let ptr: *mut [B] = box_ptr as *mut [B];
+ Ok(unsafe { Box::<[B]>::from_raw(ptr) })
+ }
+}
+
+/// As [`try_cast_vec`](try_cast_vec), but unwraps for you.
+#[inline]
+pub fn cast_vec<A: NoUninit, B: AnyBitPattern>(input: Vec<A>) -> Vec<B> {
+ try_cast_vec(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a [`Vec`](alloc::vec::Vec).
+///
+/// On failure you get back an error along with the starting `Vec`.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Vec` must have the exact same
+/// alignment.
+/// * The start and end content size in bytes of the `Vec` must be the exact
+/// same.
+/// * The start and end capacity in bytes of the `Vec` must be the exact same.
+#[inline]
+pub fn try_cast_vec<A: NoUninit, B: AnyBitPattern>(
+ input: Vec<A>,
+) -> Result<Vec<B>, (PodCastError, Vec<A>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ if size_of::<A>() * input.len() % size_of::<B>() != 0
+ || size_of::<A>() * input.capacity() % size_of::<B>() != 0
+ {
+ // If the size in bytes of the underlying buffer does not match an exact
+ // multiple of the size of B, we cannot cast between them.
+ // Note that we have to pay special attention to make sure that both
+ // length and capacity are valid under B, as we do not want to
+ // change which bytes are considered part of the initialized slice
+ // of the Vec
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Because the size is an exact multiple, we can now change the length and
+ // capacity and recreate the Vec
+ // NOTE: This is a valid operation because according to the docs of
+ // std::alloc::GlobalAlloc::dealloc(), the Layout that was used to alloc
+ // the block must be the same Layout that is used to dealloc the block.
+ // Luckily, Layout only stores two things, the alignment, and the size in
+ // bytes. So as long as both of those stay the same, the Layout will
+ // remain a valid input to dealloc.
+
+ // Note(Lokathor): First we record the length and capacity, which don't
+ // have any secret provenance metadata.
+ let length: usize = size_of::<A>() * input.len() / size_of::<B>();
+ let capacity: usize = size_of::<A>() * input.capacity() / size_of::<B>();
+ // Note(Lokathor): Next we "pre-forget" the old Vec by wrapping with
+ // ManuallyDrop, because if we used `core::mem::forget` after taking the
+ // pointer then that would invalidate our pointer. In nightly there's a
+ // "into raw parts" method, which we can switch this too eventually.
+ let mut manual_drop_vec = ManuallyDrop::new(input);
+ let vec_ptr: *mut A = manual_drop_vec.as_mut_ptr();
+ let ptr: *mut B = vec_ptr as *mut B;
+ Ok(unsafe { Vec::from_raw_parts(ptr, length, capacity) })
+ }
+ } else {
+ // Note(Lokathor): First we record the length and capacity, which don't have
+ // any secret provenance metadata.
+ let length: usize = input.len();
+ let capacity: usize = input.capacity();
+ // Note(Lokathor): Next we "pre-forget" the old Vec by wrapping with
+ // ManuallyDrop, because if we used `core::mem::forget` after taking the
+ // pointer then that would invalidate our pointer. In nightly there's a
+ // "into raw parts" method, which we can switch this too eventually.
+ let mut manual_drop_vec = ManuallyDrop::new(input);
+ let vec_ptr: *mut A = manual_drop_vec.as_mut_ptr();
+ let ptr: *mut B = vec_ptr as *mut B;
+ Ok(unsafe { Vec::from_raw_parts(ptr, length, capacity) })
+ }
+}
+
+/// This "collects" a slice of pod data into a vec of a different pod type.
+///
+/// Unlike with [`cast_slice`] and [`cast_slice_mut`], this will always work.
+///
+/// The output vec will be of a minimal size/capacity to hold the slice given.
+///
+/// ```rust
+/// # use bytemuck::*;
+/// let halfwords: [u16; 4] = [5, 6, 7, 8];
+/// let vec_of_words: Vec<u32> = pod_collect_to_vec(&halfwords);
+/// if cfg!(target_endian = "little") {
+/// assert_eq!(&vec_of_words[..], &[0x0006_0005, 0x0008_0007][..])
+/// } else {
+/// assert_eq!(&vec_of_words[..], &[0x0005_0006, 0x0007_0008][..])
+/// }
+/// ```
+pub fn pod_collect_to_vec<A: NoUninit, B: NoUninit + AnyBitPattern>(
+ src: &[A],
+) -> Vec<B> {
+ let src_size = size_of_val(src);
+ // Note(Lokathor): dst_count is rounded up so that the dest will always be at
+ // least as many bytes as the src.
+ let dst_count = src_size / size_of::<B>()
+ + if src_size % size_of::<B>() != 0 { 1 } else { 0 };
+ let mut dst = vec![B::zeroed(); dst_count];
+
+ let src_bytes: &[u8] = cast_slice(src);
+ let dst_bytes: &mut [u8] = cast_slice_mut(&mut dst[..]);
+ dst_bytes[..src_size].copy_from_slice(src_bytes);
+ dst
+}
+
+/// As [`try_cast_rc`](try_cast_rc), but unwraps for you.
+#[inline]
+pub fn cast_rc<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
+ input: Rc<A>,
+) -> Rc<B> {
+ try_cast_rc(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a [`Rc`](alloc::rc::Rc).
+///
+/// On failure you get back an error along with the starting `Rc`.
+///
+/// The bounds on this function are the same as [`cast_mut`], because a user
+/// could call `Rc::get_unchecked_mut` on the output, which could be observable
+/// in the input.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Rc` must have the exact same
+/// alignment.
+/// * The start and end size of the `Rc` must have the exact same size.
+#[inline]
+pub fn try_cast_rc<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
+ input: Rc<A>,
+) -> Result<Rc<B>, (PodCastError, Rc<A>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Safety: Rc::from_raw requires size and alignment match, which is met.
+ let ptr: *const B = Rc::into_raw(input) as *const B;
+ Ok(unsafe { Rc::from_raw(ptr) })
+ }
+}
+
+/// As [`try_cast_arc`](try_cast_arc), but unwraps for you.
+#[inline]
+#[cfg(target_has_atomic = "ptr")]
+pub fn cast_arc<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
+ input: Arc<A>,
+) -> Arc<B> {
+ try_cast_arc(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a [`Arc`](alloc::sync::Arc).
+///
+/// On failure you get back an error along with the starting `Arc`.
+///
+/// The bounds on this function are the same as [`cast_mut`], because a user
+/// could call `Rc::get_unchecked_mut` on the output, which could be observable
+/// in the input.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Arc` must have the exact same
+/// alignment.
+/// * The start and end size of the `Arc` must have the exact same size.
+#[inline]
+#[cfg(target_has_atomic = "ptr")]
+pub fn try_cast_arc<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ input: Arc<A>,
+) -> Result<Arc<B>, (PodCastError, Arc<A>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Safety: Arc::from_raw requires size and alignment match, which is met.
+ let ptr: *const B = Arc::into_raw(input) as *const B;
+ Ok(unsafe { Arc::from_raw(ptr) })
+ }
+}
+
+/// As [`try_cast_slice_rc`](try_cast_slice_rc), but unwraps for you.
+#[inline]
+pub fn cast_slice_rc<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ input: Rc<[A]>,
+) -> Rc<[B]> {
+ try_cast_slice_rc(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a `Rc<[T]>`.
+///
+/// On failure you get back an error along with the starting `Rc<[T]>`.
+///
+/// The bounds on this function are the same as [`cast_mut`], because a user
+/// could call `Rc::get_unchecked_mut` on the output, which could be observable
+/// in the input.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Rc<[T]>` must have the exact same
+/// alignment.
+/// * The start and end content size in bytes of the `Rc<[T]>` must be the exact
+/// same.
+#[inline]
+pub fn try_cast_slice_rc<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ input: Rc<[A]>,
+) -> Result<Rc<[B]>, (PodCastError, Rc<[A]>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ if size_of::<A>() * input.len() % size_of::<B>() != 0 {
+ // If the size in bytes of the underlying buffer does not match an exact
+ // multiple of the size of B, we cannot cast between them.
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Because the size is an exact multiple, we can now change the length
+ // of the slice and recreate the Rc
+ // NOTE: This is a valid operation because according to the docs of
+ // std::rc::Rc::from_raw(), the type U that was in the original Rc<U>
+ // acquired from Rc::into_raw() must have the same size alignment and
+ // size of the type T in the new Rc<T>. So as long as both the size
+ // and alignment stay the same, the Rc will remain a valid Rc.
+ let length = size_of::<A>() * input.len() / size_of::<B>();
+ let rc_ptr: *const A = Rc::into_raw(input) as *const A;
+ // Must use ptr::slice_from_raw_parts, because we cannot make an
+ // intermediate const reference, because it has mutable provenance,
+ // nor an intermediate mutable reference, because it could be aliased.
+ let ptr = core::ptr::slice_from_raw_parts(rc_ptr as *const B, length);
+ Ok(unsafe { Rc::<[B]>::from_raw(ptr) })
+ }
+ } else {
+ let rc_ptr: *const [A] = Rc::into_raw(input);
+ let ptr: *const [B] = rc_ptr as *const [B];
+ Ok(unsafe { Rc::<[B]>::from_raw(ptr) })
+ }
+}
+
+/// As [`try_cast_slice_arc`](try_cast_slice_arc), but unwraps for you.
+#[inline]
+#[cfg(target_has_atomic = "ptr")]
+pub fn cast_slice_arc<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ input: Arc<[A]>,
+) -> Arc<[B]> {
+ try_cast_slice_arc(input).map_err(|(e, _v)| e).unwrap()
+}
+
+/// Attempts to cast the content type of a `Arc<[T]>`.
+///
+/// On failure you get back an error along with the starting `Arc<[T]>`.
+///
+/// The bounds on this function are the same as [`cast_mut`], because a user
+/// could call `Rc::get_unchecked_mut` on the output, which could be observable
+/// in the input.
+///
+/// ## Failure
+///
+/// * The start and end content type of the `Arc<[T]>` must have the exact same
+/// alignment.
+/// * The start and end content size in bytes of the `Arc<[T]>` must be the
+/// exact same.
+#[inline]
+#[cfg(target_has_atomic = "ptr")]
+pub fn try_cast_slice_arc<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ input: Arc<[A]>,
+) -> Result<Arc<[B]>, (PodCastError, Arc<[A]>)> {
+ if align_of::<A>() != align_of::<B>() {
+ Err((PodCastError::AlignmentMismatch, input))
+ } else if size_of::<A>() != size_of::<B>() {
+ if size_of::<A>() * input.len() % size_of::<B>() != 0 {
+ // If the size in bytes of the underlying buffer does not match an exact
+ // multiple of the size of B, we cannot cast between them.
+ Err((PodCastError::SizeMismatch, input))
+ } else {
+ // Because the size is an exact multiple, we can now change the length
+ // of the slice and recreate the Arc
+ // NOTE: This is a valid operation because according to the docs of
+ // std::sync::Arc::from_raw(), the type U that was in the original Arc<U>
+ // acquired from Arc::into_raw() must have the same size alignment and
+ // size of the type T in the new Arc<T>. So as long as both the size
+ // and alignment stay the same, the Arc will remain a valid Arc.
+ let length = size_of::<A>() * input.len() / size_of::<B>();
+ let arc_ptr: *const A = Arc::into_raw(input) as *const A;
+ // Must use ptr::slice_from_raw_parts, because we cannot make an
+ // intermediate const reference, because it has mutable provenance,
+ // nor an intermediate mutable reference, because it could be aliased.
+ let ptr = core::ptr::slice_from_raw_parts(arc_ptr as *const B, length);
+ Ok(unsafe { Arc::<[B]>::from_raw(ptr) })
+ }
+ } else {
+ let arc_ptr: *const [A] = Arc::into_raw(input);
+ let ptr: *const [B] = arc_ptr as *const [B];
+ Ok(unsafe { Arc::<[B]>::from_raw(ptr) })
+ }
+}
+
+/// An extension trait for `TransparentWrapper` and alloc types.
+pub trait TransparentWrapperAlloc<Inner: ?Sized>:
+ TransparentWrapper<Inner>
+{
+ /// Convert a vec of the inner type into a vec of the wrapper type.
+ fn wrap_vec(s: Vec<Inner>) -> Vec<Self>
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ let mut s = core::mem::ManuallyDrop::new(s);
+
+ let length = s.len();
+ let capacity = s.capacity();
+ let ptr = s.as_mut_ptr();
+
+ unsafe {
+ // SAFETY:
+ // * ptr comes from Vec (and will not be double-dropped)
+ // * the two types have the identical representation
+ // * the len and capacity fields are valid
+ Vec::from_raw_parts(ptr as *mut Self, length, capacity)
+ }
+ }
+
+ /// Convert a box to the inner type into a box to the wrapper
+ /// type.
+ #[inline]
+ fn wrap_box(s: Box<Inner>) -> Box<Self> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations
+ // * Box is guaranteed to have representation identical to a (non-null)
+ // pointer
+ // * The pointer comes from a box (and thus satisfies all safety
+ // requirements of Box)
+ let inner_ptr: *mut Inner = Box::into_raw(s);
+ let wrapper_ptr: *mut Self = transmute!(inner_ptr);
+ Box::from_raw(wrapper_ptr)
+ }
+ }
+
+ /// Convert an [`Rc`](alloc::rc::Rc) to the inner type into an `Rc` to the
+ /// wrapper type.
+ #[inline]
+ fn wrap_rc(s: Rc<Inner>) -> Rc<Self> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the layout of Rc is unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations, and that the size and alignment of Inner
+ // and Self are the same, which meets the safety requirements of
+ // Rc::from_raw
+ let inner_ptr: *const Inner = Rc::into_raw(s);
+ let wrapper_ptr: *const Self = transmute!(inner_ptr);
+ Rc::from_raw(wrapper_ptr)
+ }
+ }
+
+ /// Convert an [`Arc`](alloc::sync::Arc) to the inner type into an `Arc` to
+ /// the wrapper type.
+ #[inline]
+ #[cfg(target_has_atomic = "ptr")]
+ fn wrap_arc(s: Arc<Inner>) -> Arc<Self> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the layout of Arc is unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations, and that the size and alignment of Inner
+ // and Self are the same, which meets the safety requirements of
+ // Arc::from_raw
+ let inner_ptr: *const Inner = Arc::into_raw(s);
+ let wrapper_ptr: *const Self = transmute!(inner_ptr);
+ Arc::from_raw(wrapper_ptr)
+ }
+ }
+
+ /// Convert a vec of the wrapper type into a vec of the inner type.
+ fn peel_vec(s: Vec<Self>) -> Vec<Inner>
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ let mut s = core::mem::ManuallyDrop::new(s);
+
+ let length = s.len();
+ let capacity = s.capacity();
+ let ptr = s.as_mut_ptr();
+
+ unsafe {
+ // SAFETY:
+ // * ptr comes from Vec (and will not be double-dropped)
+ // * the two types have the identical representation
+ // * the len and capacity fields are valid
+ Vec::from_raw_parts(ptr as *mut Inner, length, capacity)
+ }
+ }
+
+ /// Convert a box to the wrapper type into a box to the inner
+ /// type.
+ #[inline]
+ fn peel_box(s: Box<Self>) -> Box<Inner> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations
+ // * Box is guaranteed to have representation identical to a (non-null)
+ // pointer
+ // * The pointer comes from a box (and thus satisfies all safety
+ // requirements of Box)
+ let wrapper_ptr: *mut Self = Box::into_raw(s);
+ let inner_ptr: *mut Inner = transmute!(wrapper_ptr);
+ Box::from_raw(inner_ptr)
+ }
+ }
+
+ /// Convert an [`Rc`](alloc::rc::Rc) to the wrapper type into an `Rc` to the
+ /// inner type.
+ #[inline]
+ fn peel_rc(s: Rc<Self>) -> Rc<Inner> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the layout of Rc is unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations, and that the size and alignment of Inner
+ // and Self are the same, which meets the safety requirements of
+ // Rc::from_raw
+ let wrapper_ptr: *const Self = Rc::into_raw(s);
+ let inner_ptr: *const Inner = transmute!(wrapper_ptr);
+ Rc::from_raw(inner_ptr)
+ }
+ }
+
+ /// Convert an [`Arc`](alloc::sync::Arc) to the wrapper type into an `Arc` to
+ /// the inner type.
+ #[inline]
+ #[cfg(target_has_atomic = "ptr")]
+ fn peel_arc(s: Arc<Self>) -> Arc<Inner> {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+
+ unsafe {
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the layout of Arc is unspecified.
+ //
+ // SAFETY:
+ // * The unsafe contract requires that pointers to Inner and Self have
+ // identical representations, and that the size and alignment of Inner
+ // and Self are the same, which meets the safety requirements of
+ // Arc::from_raw
+ let wrapper_ptr: *const Self = Arc::into_raw(s);
+ let inner_ptr: *const Inner = transmute!(wrapper_ptr);
+ Arc::from_raw(inner_ptr)
+ }
+ }
+}
+impl<I: ?Sized, T: TransparentWrapper<I>> TransparentWrapperAlloc<I> for T {}
diff --git a/src/anybitpattern.rs b/src/anybitpattern.rs
new file mode 100644
index 0000000..9332d61
--- /dev/null
+++ b/src/anybitpattern.rs
@@ -0,0 +1,60 @@
+use crate::{Pod, Zeroable};
+
+/// Marker trait for "plain old data" types that are valid for any bit pattern.
+///
+/// The requirements for this is very similar to [`Pod`],
+/// except that the type can allow uninit (or padding) bytes.
+/// This limits what you can do with a type of this kind, but also broadens the
+/// included types to `repr(C)` `struct`s that contain padding as well as
+/// `union`s. Notably, you can only cast *immutable* references and *owned*
+/// values into [`AnyBitPattern`] types, not *mutable* references.
+///
+/// [`Pod`] is a subset of [`AnyBitPattern`], meaning that any `T: Pod` is also
+/// [`AnyBitPattern`] but any `T: AnyBitPattern` is not necessarily [`Pod`].
+///
+/// [`AnyBitPattern`] is a subset of [`Zeroable`], meaning that any `T:
+/// AnyBitPattern` is also [`Zeroable`], but any `T: Zeroable` is not
+/// necessarily [`AnyBitPattern ]
+///
+/// # Derive
+///
+/// A `#[derive(AnyBitPattern)]` macro is provided under the `derive` feature
+/// flag which will automatically validate the requirements of this trait and
+/// implement the trait for you for both structs and enums. This is the
+/// recommended method for implementing the trait, however it's also possible to
+/// do manually. If you implement it manually, you *must* carefully follow the
+/// below safety rules.
+///
+/// * *NOTE: even `C-style`, fieldless enums are intentionally **excluded** from
+/// this trait, since it is **unsound** for an enum to have a discriminant value
+/// that is not one of its defined variants.
+///
+/// # Safety
+///
+/// Similar to [`Pod`] except we disregard the rule about it must not contain
+/// uninit bytes. Still, this is a quite strong guarantee about a type, so *be
+/// careful* when implementing it manually.
+///
+/// * The type must be inhabited (eg: no
+/// [Infallible](core::convert::Infallible)).
+/// * The type must be valid for any bit pattern of its backing memory.
+/// * Structs need to have all fields also be `AnyBitPattern`.
+/// * It is disallowed for types to contain pointer types, `Cell`, `UnsafeCell`,
+/// atomics, and any other forms of interior mutability.
+/// * More precisely: A shared reference to the type must allow reads, and
+/// *only* reads. RustBelt's separation logic is based on the notion that a
+/// type is allowed to define a sharing predicate, its own invariant that must
+/// hold for shared references, and this predicate is the reasoning that allow
+/// it to deal with atomic and cells etc. We require the sharing predicate to
+/// be trivial and permit only read-only access.
+/// * There's probably more, don't mess it up (I mean it).
+pub unsafe trait AnyBitPattern:
+ Zeroable + Sized + Copy + 'static
+{
+}
+
+unsafe impl<T: Pod> AnyBitPattern for T {}
+
+#[cfg(feature = "zeroable_maybe_uninit")]
+unsafe impl<T> AnyBitPattern for core::mem::MaybeUninit<T> where T: AnyBitPattern
+{}
diff --git a/src/checked.rs b/src/checked.rs
new file mode 100644
index 0000000..2d97340
--- /dev/null
+++ b/src/checked.rs
@@ -0,0 +1,527 @@
+//! Checked versions of the casting functions exposed in crate root
+//! that support [`CheckedBitPattern`] types.
+
+use crate::{
+ internal::{self, something_went_wrong},
+ AnyBitPattern, NoUninit,
+};
+
+/// A marker trait that allows types that have some invalid bit patterns to be
+/// used in places that otherwise require [`AnyBitPattern`] or [`Pod`] types by
+/// performing a runtime check on a perticular set of bits. This is particularly
+/// useful for types like fieldless ('C-style') enums, [`char`], bool, and
+/// structs containing them.
+///
+/// To do this, we define a `Bits` type which is a type with equivalent layout
+/// to `Self` other than the invalid bit patterns which disallow `Self` from
+/// being [`AnyBitPattern`]. This `Bits` type must itself implement
+/// [`AnyBitPattern`]. Then, we implement a function that checks whether a
+/// certain instance of the `Bits` is also a valid bit pattern of `Self`. If
+/// this check passes, then we can allow casting from the `Bits` to `Self` (and
+/// therefore, any type which is able to be cast to `Bits` is also able to be
+/// cast to `Self`).
+///
+/// [`AnyBitPattern`] is a subset of [`CheckedBitPattern`], meaning that any `T:
+/// AnyBitPattern` is also [`CheckedBitPattern`]. This means you can also use
+/// any [`AnyBitPattern`] type in the checked versions of casting functions in
+/// this module. If it's possible, prefer implementing [`AnyBitPattern`] for
+/// your type directly instead of [`CheckedBitPattern`] as it gives greater
+/// flexibility.
+///
+/// # Derive
+///
+/// A `#[derive(CheckedBitPattern)]` macro is provided under the `derive`
+/// feature flag which will automatically validate the requirements of this
+/// trait and implement the trait for you for both enums and structs. This is
+/// the recommended method for implementing the trait, however it's also
+/// possible to do manually.
+///
+/// # Example
+///
+/// If manually implementing the trait, we can do something like so:
+///
+/// ```rust
+/// use bytemuck::{CheckedBitPattern, NoUninit};
+///
+/// #[repr(u32)]
+/// #[derive(Copy, Clone)]
+/// enum MyEnum {
+/// Variant0 = 0,
+/// Variant1 = 1,
+/// Variant2 = 2,
+/// }
+///
+/// unsafe impl CheckedBitPattern for MyEnum {
+/// type Bits = u32;
+///
+/// fn is_valid_bit_pattern(bits: &u32) -> bool {
+/// match *bits {
+/// 0 | 1 | 2 => true,
+/// _ => false,
+/// }
+/// }
+/// }
+///
+/// // It is often useful to also implement `NoUninit` on our `CheckedBitPattern` types.
+/// // This will allow us to do casting of mutable references (and mutable slices).
+/// // It is not always possible to do so, but in this case we have no padding so it is.
+/// unsafe impl NoUninit for MyEnum {}
+/// ```
+///
+/// We can now use relevant casting functions. For example,
+///
+/// ```rust
+/// # use bytemuck::{CheckedBitPattern, NoUninit};
+/// # #[repr(u32)]
+/// # #[derive(Copy, Clone, PartialEq, Eq, Debug)]
+/// # enum MyEnum {
+/// # Variant0 = 0,
+/// # Variant1 = 1,
+/// # Variant2 = 2,
+/// # }
+/// # unsafe impl NoUninit for MyEnum {}
+/// # unsafe impl CheckedBitPattern for MyEnum {
+/// # type Bits = u32;
+/// # fn is_valid_bit_pattern(bits: &u32) -> bool {
+/// # match *bits {
+/// # 0 | 1 | 2 => true,
+/// # _ => false,
+/// # }
+/// # }
+/// # }
+/// use bytemuck::{bytes_of, bytes_of_mut};
+/// use bytemuck::checked;
+///
+/// let bytes = bytes_of(&2u32);
+/// let result = checked::try_from_bytes::<MyEnum>(bytes);
+/// assert_eq!(result, Ok(&MyEnum::Variant2));
+///
+/// // Fails for invalid discriminant
+/// let bytes = bytes_of(&100u32);
+/// let result = checked::try_from_bytes::<MyEnum>(bytes);
+/// assert!(result.is_err());
+///
+/// // Since we implemented NoUninit, we can also cast mutably from an original type
+/// // that is `NoUninit + AnyBitPattern`:
+/// let mut my_u32 = 2u32;
+/// {
+/// let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32);
+/// assert_eq!(as_enum_mut, &mut MyEnum::Variant2);
+/// *as_enum_mut = MyEnum::Variant0;
+/// }
+/// assert_eq!(my_u32, 0u32);
+/// ```
+///
+/// # Safety
+///
+/// * `Self` *must* have the same layout as the specified `Bits` except for
+/// the possible invalid bit patterns being checked during
+/// [`is_valid_bit_pattern`].
+/// * This almost certainly means your type must be `#[repr(C)]` or a similar
+/// specified repr, but if you think you know better, you probably don't. If
+/// you still think you know better, be careful and have fun. And don't mess
+/// it up (I mean it).
+/// * If [`is_valid_bit_pattern`] returns true, then the bit pattern contained
+/// in `bits` must also be valid for an instance of `Self`.
+/// * Probably more, don't mess it up (I mean it 2.0)
+///
+/// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
+/// [`Pod`]: crate::Pod
+pub unsafe trait CheckedBitPattern: Copy {
+ /// `Self` *must* have the same layout as the specified `Bits` except for
+ /// the possible invalid bit patterns being checked during
+ /// [`is_valid_bit_pattern`].
+ ///
+ /// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
+ type Bits: AnyBitPattern;
+
+ /// If this function returns true, then it must be valid to reinterpret `bits`
+ /// as `&Self`.
+ fn is_valid_bit_pattern(bits: &Self::Bits) -> bool;
+}
+
+unsafe impl<T: AnyBitPattern> CheckedBitPattern for T {
+ type Bits = T;
+
+ #[inline(always)]
+ fn is_valid_bit_pattern(_bits: &T) -> bool {
+ true
+ }
+}
+
+unsafe impl CheckedBitPattern for char {
+ type Bits = u32;
+
+ #[inline]
+ fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
+ core::char::from_u32(*bits).is_some()
+ }
+}
+
+unsafe impl CheckedBitPattern for bool {
+ type Bits = u8;
+
+ #[inline]
+ fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
+ match *bits {
+ 0 | 1 => true,
+ _ => false,
+ }
+ }
+}
+
+macro_rules! impl_checked_for_nonzero {
+ ($($nonzero:ty: $primitive:ty),* $(,)?) => {
+ $(
+ unsafe impl CheckedBitPattern for $nonzero {
+ type Bits = $primitive;
+
+ #[inline]
+ fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
+ // Note(zachs18): The size and alignment check are almost certainly
+ // not necessary, but Rust currently doesn't explicitly document that
+ // NonZero[int] has the same layout as [int], so we check it to be safe.
+ // In a const to reduce debug-profile overhead.
+ const LAYOUT_SAME: bool =
+ core::mem::size_of::<$nonzero>() == core::mem::size_of::<$primitive>()
+ && core::mem::align_of::<$nonzero>() == core::mem::align_of::<$primitive>();
+ LAYOUT_SAME && *bits != 0
+ }
+ }
+ )*
+ };
+}
+impl_checked_for_nonzero! {
+ core::num::NonZeroU8: u8,
+ core::num::NonZeroI8: i8,
+ core::num::NonZeroU16: u16,
+ core::num::NonZeroI16: i16,
+ core::num::NonZeroU32: u32,
+ core::num::NonZeroI32: i32,
+ core::num::NonZeroU64: u64,
+ core::num::NonZeroI64: i64,
+ core::num::NonZeroI128: i128,
+ core::num::NonZeroU128: u128,
+ core::num::NonZeroUsize: usize,
+ core::num::NonZeroIsize: isize,
+}
+
+/// The things that can go wrong when casting between [`CheckedBitPattern`] data
+/// forms.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum CheckedCastError {
+ /// An error occurred during a true-[`Pod`] cast
+ ///
+ /// [`Pod`]: crate::Pod
+ PodCastError(crate::PodCastError),
+ /// When casting to a [`CheckedBitPattern`] type, it is possible that the
+ /// original data contains an invalid bit pattern. If so, the cast will
+ /// fail and this error will be returned. Will never happen on casts
+ /// between [`Pod`] types.
+ ///
+ /// [`Pod`]: crate::Pod
+ InvalidBitPattern,
+}
+
+#[cfg(not(target_arch = "spirv"))]
+impl core::fmt::Display for CheckedCastError {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ write!(f, "{:?}", self)
+ }
+}
+#[cfg(feature = "extern_crate_std")]
+impl std::error::Error for CheckedCastError {}
+
+impl From<crate::PodCastError> for CheckedCastError {
+ fn from(err: crate::PodCastError) -> CheckedCastError {
+ CheckedCastError::PodCastError(err)
+ }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+/// * If the slice contains an invalid bit pattern for `T`
+#[inline]
+pub fn try_from_bytes<T: CheckedBitPattern>(
+ s: &[u8],
+) -> Result<&T, CheckedCastError> {
+ let pod = unsafe { internal::try_from_bytes(s) }?;
+
+ if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
+ Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+/// * If the slice contains an invalid bit pattern for `T`
+#[inline]
+pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
+ s: &mut [u8],
+) -> Result<&mut T, CheckedCastError> {
+ let pod = unsafe { internal::try_from_bytes_mut(s) }?;
+
+ if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
+ Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Reads from the bytes as if they were a `T`.
+///
+/// ## Failure
+/// * If the `bytes` length is not equal to `size_of::<T>()`.
+/// * If the slice contains an invalid bit pattern for `T`
+#[inline]
+pub fn try_pod_read_unaligned<T: CheckedBitPattern>(
+ bytes: &[u8],
+) -> Result<T, CheckedCastError> {
+ let pod = unsafe { internal::try_pod_read_unaligned(bytes) }?;
+
+ if <T as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
+ Ok(unsafe { transmute!(pod) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Try to cast `T` into `U`.
+///
+/// Note that for this particular type of cast, alignment isn't a factor. The
+/// input value is semantically copied into the function and then returned to a
+/// new memory location which will have whatever the required alignment of the
+/// output type is.
+///
+/// ## Failure
+///
+/// * If the types don't have the same size this fails.
+/// * If `a` contains an invalid bit pattern for `B` this fails.
+#[inline]
+pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
+ a: A,
+) -> Result<B, CheckedCastError> {
+ let pod = unsafe { internal::try_cast(a) }?;
+
+ if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
+ Ok(unsafe { transmute!(pod) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Try to convert a `&T` into `&U`.
+///
+/// ## Failure
+///
+/// * If the reference isn't aligned in the new type
+/// * If the source type and target type aren't the same size.
+/// * If `a` contains an invalid bit pattern for `B` this fails.
+#[inline]
+pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
+ a: &A,
+) -> Result<&B, CheckedCastError> {
+ let pod = unsafe { internal::try_cast_ref(a) }?;
+
+ if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
+ Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Try to convert a `&mut T` into `&mut U`.
+///
+/// As [`try_cast_ref`], but `mut`.
+#[inline]
+pub fn try_cast_mut<
+ A: NoUninit + AnyBitPattern,
+ B: CheckedBitPattern + NoUninit,
+>(
+ a: &mut A,
+) -> Result<&mut B, CheckedCastError> {
+ let pod = unsafe { internal::try_cast_mut(a) }?;
+
+ if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
+ Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
+///
+/// * `input.as_ptr() as usize == output.as_ptr() as usize`
+/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
+///
+/// ## Failure
+///
+/// * If the target type has a greater alignment requirement and the input slice
+/// isn't aligned.
+/// * If the target element type is a different size from the current element
+/// type, and the output slice wouldn't be a whole number of elements when
+/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
+/// that's a failure).
+/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
+/// and a non-ZST.
+/// * If any element of the converted slice would contain an invalid bit pattern
+/// for `B` this fails.
+#[inline]
+pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
+ a: &[A],
+) -> Result<&[B], CheckedCastError> {
+ let pod = unsafe { internal::try_cast_slice(a) }?;
+
+ if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
+ Ok(unsafe {
+ core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
+ })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
+/// length).
+///
+/// As [`try_cast_slice`], but `&mut`.
+#[inline]
+pub fn try_cast_slice_mut<
+ A: NoUninit + AnyBitPattern,
+ B: CheckedBitPattern + NoUninit,
+>(
+ a: &mut [A],
+) -> Result<&mut [B], CheckedCastError> {
+ let pod = unsafe { internal::try_cast_slice_mut(a) }?;
+
+ if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
+ Ok(unsafe {
+ core::slice::from_raw_parts_mut(pod.as_mut_ptr() as *mut B, pod.len())
+ })
+ } else {
+ Err(CheckedCastError::InvalidBitPattern)
+ }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes`] but will panic on error.
+#[inline]
+pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
+ match try_from_bytes(s) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("from_bytes", e),
+ }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes_mut`] but will panic on error.
+#[inline]
+pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
+ match try_from_bytes_mut(s) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("from_bytes_mut", e),
+ }
+}
+
+/// Reads the slice into a `T` value.
+///
+/// ## Panics
+/// * This is like `try_pod_read_unaligned` but will panic on failure.
+#[inline]
+pub fn pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> T {
+ match try_pod_read_unaligned(bytes) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("pod_read_unaligned", e),
+ }
+}
+
+/// Cast `T` into `U`
+///
+/// ## Panics
+///
+/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
+#[inline]
+pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
+ match try_cast(a) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("cast", e),
+ }
+}
+
+/// Cast `&mut T` into `&mut U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_mut`] but will panic on error.
+#[inline]
+pub fn cast_mut<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + CheckedBitPattern,
+>(
+ a: &mut A,
+) -> &mut B {
+ match try_cast_mut(a) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("cast_mut", e),
+ }
+}
+
+/// Cast `&T` into `&U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_ref`] but will panic on error.
+#[inline]
+pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
+ match try_cast_ref(a) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("cast_ref", e),
+ }
+}
+
+/// Cast `&[A]` into `&[B]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice`] but will panic on error.
+#[inline]
+pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
+ match try_cast_slice(a) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("cast_slice", e),
+ }
+}
+
+/// Cast `&mut [T]` into `&mut [U]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice_mut`] but will panic on error.
+#[inline]
+pub fn cast_slice_mut<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + CheckedBitPattern,
+>(
+ a: &mut [A],
+) -> &mut [B] {
+ match try_cast_slice_mut(a) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("cast_slice_mut", e),
+ }
+}
diff --git a/src/contiguous.rs b/src/contiguous.rs
new file mode 100644
index 0000000..f84a612
--- /dev/null
+++ b/src/contiguous.rs
@@ -0,0 +1,202 @@
+use super::*;
+
+/// A trait indicating that:
+///
+/// 1. A type has an equivalent representation to some known integral type.
+/// 2. All instances of this type fall in a fixed range of values.
+/// 3. Within that range, there are no gaps.
+///
+/// This is generally useful for fieldless enums (aka "c-style" enums), however
+/// it's important that it only be used for those with an explicit `#[repr]`, as
+/// `#[repr(Rust)]` fieldess enums have an unspecified layout.
+///
+/// Additionally, you shouldn't assume that all implementations are enums. Any
+/// type which meets the requirements above while following the rules under
+/// "Safety" below is valid.
+///
+/// # Example
+///
+/// ```
+/// # use bytemuck::Contiguous;
+/// #[repr(u8)]
+/// #[derive(Debug, Copy, Clone, PartialEq)]
+/// enum Foo {
+/// A = 0,
+/// B = 1,
+/// C = 2,
+/// D = 3,
+/// E = 4,
+/// }
+/// unsafe impl Contiguous for Foo {
+/// type Int = u8;
+/// const MIN_VALUE: u8 = Foo::A as u8;
+/// const MAX_VALUE: u8 = Foo::E as u8;
+/// }
+/// assert_eq!(Foo::from_integer(3).unwrap(), Foo::D);
+/// assert_eq!(Foo::from_integer(8), None);
+/// assert_eq!(Foo::C.into_integer(), 2);
+/// ```
+/// # Safety
+///
+/// This is an unsafe trait, and incorrectly implementing it is undefined
+/// behavior.
+///
+/// Informally, by implementing it, you're asserting that `C` is identical to
+/// the integral type `C::Int`, and that every `C` falls between `C::MIN_VALUE`
+/// and `C::MAX_VALUE` exactly once, without any gaps.
+///
+/// Precisely, the guarantees you must uphold when implementing `Contiguous` for
+/// some type `C` are:
+///
+/// 1. The size of `C` and `C::Int` must be the same, and neither may be a ZST.
+/// (Note: alignment is explicitly allowed to differ)
+///
+/// 2. `C::Int` must be a primitive integer, and not a wrapper type. In the
+/// future, this may be lifted to include cases where the behavior is
+/// identical for a relevant set of traits (Ord, arithmetic, ...).
+///
+/// 3. All `C::Int`s which are in the *inclusive* range between `C::MIN_VALUE`
+/// and `C::MAX_VALUE` are bitwise identical to unique valid instances of
+/// `C`.
+///
+/// 4. There exist no instances of `C` such that their bitpatterns, when
+/// interpreted as instances of `C::Int`, fall outside of the `MAX_VALUE` /
+/// `MIN_VALUE` range -- It is legal for unsafe code to assume that if it
+/// gets a `C` that implements `Contiguous`, it is in the appropriate range.
+///
+/// 5. Finally, you promise not to provide overridden implementations of
+/// `Contiguous::from_integer` and `Contiguous::into_integer`.
+///
+/// For clarity, the following rules could be derived from the above, but are
+/// listed explicitly:
+///
+/// - `C::MAX_VALUE` must be greater or equal to `C::MIN_VALUE` (therefore, `C`
+/// must be an inhabited type).
+///
+/// - There exist no two values between `MIN_VALUE` and `MAX_VALUE` such that
+/// when interpreted as a `C` they are considered identical (by, say, match).
+pub unsafe trait Contiguous: Copy + 'static {
+ /// The primitive integer type with an identical representation to this
+ /// type.
+ ///
+ /// Contiguous is broadly intended for use with fieldless enums, and for
+ /// these the correct integer type is easy: The enum should have a
+ /// `#[repr(Int)]` or `#[repr(C)]` attribute, (if it does not, it is
+ /// *unsound* to implement `Contiguous`!).
+ ///
+ /// - For `#[repr(Int)]`, use the listed `Int`. e.g. `#[repr(u8)]` should use
+ /// `type Int = u8`.
+ ///
+ /// - For `#[repr(C)]`, use whichever type the C compiler will use to
+ /// represent the given enum. This is usually `c_int` (from `std::os::raw`
+ /// or `libc`), but it's up to you to make the determination as the
+ /// implementer of the unsafe trait.
+ ///
+ /// For precise rules, see the list under "Safety" above.
+ type Int: Copy + Ord;
+
+ /// The upper *inclusive* bound for valid instances of this type.
+ const MAX_VALUE: Self::Int;
+
+ /// The lower *inclusive* bound for valid instances of this type.
+ const MIN_VALUE: Self::Int;
+
+ /// If `value` is within the range for valid instances of this type,
+ /// returns `Some(converted_value)`, otherwise, returns `None`.
+ ///
+ /// This is a trait method so that you can write `value.into_integer()` in
+ /// your code. It is a contract of this trait that if you implement
+ /// `Contiguous` on your type you **must not** override this method.
+ ///
+ /// # Panics
+ ///
+ /// We will not panic for any correct implementation of `Contiguous`, but
+ /// *may* panic if we detect an incorrect one.
+ ///
+ /// This is undefined behavior regardless, so it could have been the nasal
+ /// demons at that point anyway ;).
+ #[inline]
+ fn from_integer(value: Self::Int) -> Option<Self> {
+ // Guard against an illegal implementation of Contiguous. Annoyingly we
+ // can't rely on `transmute` to do this for us (see below), but
+ // whatever, this gets compiled into nothing in release.
+ assert!(size_of::<Self>() == size_of::<Self::Int>());
+ if Self::MIN_VALUE <= value && value <= Self::MAX_VALUE {
+ // SAFETY: We've checked their bounds (and their size, even though
+ // they've sworn under the Oath Of Unsafe Rust that that already
+ // matched) so this is allowed by `Contiguous`'s unsafe contract.
+ //
+ // So, the `transmute!`. ideally we'd use transmute here, which
+ // is more obviously safe. Sadly, we can't, as these types still
+ // have unspecified sizes.
+ Some(unsafe { transmute!(value) })
+ } else {
+ None
+ }
+ }
+
+ /// Perform the conversion from `C` into the underlying integral type. This
+ /// mostly exists otherwise generic code would need unsafe for the `value as
+ /// integer`
+ ///
+ /// This is a trait method so that you can write `value.into_integer()` in
+ /// your code. It is a contract of this trait that if you implement
+ /// `Contiguous` on your type you **must not** override this method.
+ ///
+ /// # Panics
+ ///
+ /// We will not panic for any correct implementation of `Contiguous`, but
+ /// *may* panic if we detect an incorrect one.
+ ///
+ /// This is undefined behavior regardless, so it could have been the nasal
+ /// demons at that point anyway ;).
+ #[inline]
+ fn into_integer(self) -> Self::Int {
+ // Guard against an illegal implementation of Contiguous. Annoyingly we
+ // can't rely on `transmute` to do the size check for us (see
+ // `from_integer's comment`), but whatever, this gets compiled into
+ // nothing in release. Note that we don't check the result of cast
+ assert!(size_of::<Self>() == size_of::<Self::Int>());
+
+ // SAFETY: The unsafe contract requires that these have identical
+ // representations, and that the range be entirely valid. Using
+ // transmute! instead of transmute here is annoying, but is required
+ // as `Self` and `Self::Int` have unspecified sizes still.
+ unsafe { transmute!(self) }
+ }
+}
+
+macro_rules! impl_contiguous {
+ ($($src:ty as $repr:ident in [$min:expr, $max:expr];)*) => {$(
+ unsafe impl Contiguous for $src {
+ type Int = $repr;
+ const MAX_VALUE: $repr = $max;
+ const MIN_VALUE: $repr = $min;
+ }
+ )*};
+}
+
+impl_contiguous! {
+ bool as u8 in [0, 1];
+
+ u8 as u8 in [0, u8::max_value()];
+ u16 as u16 in [0, u16::max_value()];
+ u32 as u32 in [0, u32::max_value()];
+ u64 as u64 in [0, u64::max_value()];
+ u128 as u128 in [0, u128::max_value()];
+ usize as usize in [0, usize::max_value()];
+
+ i8 as i8 in [i8::min_value(), i8::max_value()];
+ i16 as i16 in [i16::min_value(), i16::max_value()];
+ i32 as i32 in [i32::min_value(), i32::max_value()];
+ i64 as i64 in [i64::min_value(), i64::max_value()];
+ i128 as i128 in [i128::min_value(), i128::max_value()];
+ isize as isize in [isize::min_value(), isize::max_value()];
+
+ NonZeroU8 as u8 in [1, u8::max_value()];
+ NonZeroU16 as u16 in [1, u16::max_value()];
+ NonZeroU32 as u32 in [1, u32::max_value()];
+ NonZeroU64 as u64 in [1, u64::max_value()];
+ NonZeroU128 as u128 in [1, u128::max_value()];
+ NonZeroUsize as usize in [1, usize::max_value()];
+}
diff --git a/src/internal.rs b/src/internal.rs
new file mode 100644
index 0000000..6068d0e
--- /dev/null
+++ b/src/internal.rs
@@ -0,0 +1,382 @@
+//! Internal implementation of casting functions not bound by marker traits
+//! and therefore marked as unsafe. This is used so that we don't need to
+//! duplicate the business logic contained in these functions between the
+//! versions exported in the crate root, `checked`, and `relaxed` modules.
+#![allow(unused_unsafe)]
+
+use crate::PodCastError;
+use core::{marker::*, mem::*};
+
+/*
+
+Note(Lokathor): We've switched all of the `unwrap` to `match` because there is
+apparently a bug: https://github.com/rust-lang/rust/issues/68667
+and it doesn't seem to show up in simple godbolt examples but has been reported
+as having an impact when there's a cast mixed in with other more complicated
+code around it. Rustc/LLVM ends up missing that the `Err` can't ever happen for
+particular type combinations, and then it doesn't fully eliminated the panic
+possibility code branch.
+
+*/
+
+/// Immediately panics.
+#[cfg(not(target_arch = "spirv"))]
+#[cold]
+#[inline(never)]
+pub(crate) fn something_went_wrong<D: core::fmt::Display>(
+ _src: &str, _err: D,
+) -> ! {
+ // Note(Lokathor): Keeping the panic here makes the panic _formatting_ go
+ // here too, which helps assembly readability and also helps keep down
+ // the inline pressure.
+ panic!("{src}>{err}", src = _src, err = _err);
+}
+
+/// Immediately panics.
+#[cfg(target_arch = "spirv")]
+#[cold]
+#[inline(never)]
+pub(crate) fn something_went_wrong<D>(_src: &str, _err: D) -> ! {
+ // Note: On the spirv targets from [rust-gpu](https://github.com/EmbarkStudios/rust-gpu)
+ // panic formatting cannot be used. We we just give a generic error message
+ // The chance that the panicking version of these functions will ever get
+ // called on spir-v targets with invalid inputs is small, but giving a
+ // simple error message is better than no error message at all.
+ panic!("Called a panicing helper from bytemuck which paniced");
+}
+
+/// Re-interprets `&T` as `&[u8]`.
+///
+/// Any ZST becomes an empty slice, and in that case the pointer value of that
+/// empty slice might not match the pointer value of the input reference.
+#[inline(always)]
+pub(crate) unsafe fn bytes_of<T: Copy>(t: &T) -> &[u8] {
+ if size_of::<T>() == 0 {
+ &[]
+ } else {
+ match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
+ Ok(s) => s,
+ Err(_) => unreachable!(),
+ }
+ }
+}
+
+/// Re-interprets `&mut T` as `&mut [u8]`.
+///
+/// Any ZST becomes an empty slice, and in that case the pointer value of that
+/// empty slice might not match the pointer value of the input reference.
+#[inline]
+pub(crate) unsafe fn bytes_of_mut<T: Copy>(t: &mut T) -> &mut [u8] {
+ if size_of::<T>() == 0 {
+ &mut []
+ } else {
+ match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
+ Ok(s) => s,
+ Err(_) => unreachable!(),
+ }
+ }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn from_bytes<T: Copy>(s: &[u8]) -> &T {
+ match try_from_bytes(s) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("from_bytes", e),
+ }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes_mut`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn from_bytes_mut<T: Copy>(s: &mut [u8]) -> &mut T {
+ match try_from_bytes_mut(s) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("from_bytes_mut", e),
+ }
+}
+
+/// Reads from the bytes as if they were a `T`.
+///
+/// ## Failure
+/// * If the `bytes` length is not equal to `size_of::<T>()`.
+#[inline]
+pub(crate) unsafe fn try_pod_read_unaligned<T: Copy>(
+ bytes: &[u8],
+) -> Result<T, PodCastError> {
+ if bytes.len() != size_of::<T>() {
+ Err(PodCastError::SizeMismatch)
+ } else {
+ Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
+ }
+}
+
+/// Reads the slice into a `T` value.
+///
+/// ## Panics
+/// * This is like `try_pod_read_unaligned` but will panic on failure.
+#[inline]
+pub(crate) unsafe fn pod_read_unaligned<T: Copy>(bytes: &[u8]) -> T {
+ match try_pod_read_unaligned(bytes) {
+ Ok(t) => t,
+ Err(e) => something_went_wrong("pod_read_unaligned", e),
+ }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+#[inline]
+pub(crate) unsafe fn try_from_bytes<T: Copy>(
+ s: &[u8],
+) -> Result<&T, PodCastError> {
+ if s.len() != size_of::<T>() {
+ Err(PodCastError::SizeMismatch)
+ } else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else {
+ Ok(unsafe { &*(s.as_ptr() as *const T) })
+ }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+#[inline]
+pub(crate) unsafe fn try_from_bytes_mut<T: Copy>(
+ s: &mut [u8],
+) -> Result<&mut T, PodCastError> {
+ if s.len() != size_of::<T>() {
+ Err(PodCastError::SizeMismatch)
+ } else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else {
+ Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
+ }
+}
+
+/// Cast `T` into `U`
+///
+/// ## Panics
+///
+/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
+#[inline]
+pub(crate) unsafe fn cast<A: Copy, B: Copy>(a: A) -> B {
+ if size_of::<A>() == size_of::<B>() {
+ unsafe { transmute!(a) }
+ } else {
+ something_went_wrong("cast", PodCastError::SizeMismatch)
+ }
+}
+
+/// Cast `&mut T` into `&mut U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_mut`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn cast_mut<A: Copy, B: Copy>(a: &mut A) -> &mut B {
+ if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
+ // Plz mr compiler, just notice that we can't ever hit Err in this case.
+ match try_cast_mut(a) {
+ Ok(b) => b,
+ Err(_) => unreachable!(),
+ }
+ } else {
+ match try_cast_mut(a) {
+ Ok(b) => b,
+ Err(e) => something_went_wrong("cast_mut", e),
+ }
+ }
+}
+
+/// Cast `&T` into `&U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_ref`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn cast_ref<A: Copy, B: Copy>(a: &A) -> &B {
+ if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
+ // Plz mr compiler, just notice that we can't ever hit Err in this case.
+ match try_cast_ref(a) {
+ Ok(b) => b,
+ Err(_) => unreachable!(),
+ }
+ } else {
+ match try_cast_ref(a) {
+ Ok(b) => b,
+ Err(e) => something_went_wrong("cast_ref", e),
+ }
+ }
+}
+
+/// Cast `&[A]` into `&[B]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn cast_slice<A: Copy, B: Copy>(a: &[A]) -> &[B] {
+ match try_cast_slice(a) {
+ Ok(b) => b,
+ Err(e) => something_went_wrong("cast_slice", e),
+ }
+}
+
+/// Cast `&mut [T]` into `&mut [U]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice_mut`] but will panic on error.
+#[inline]
+pub(crate) unsafe fn cast_slice_mut<A: Copy, B: Copy>(a: &mut [A]) -> &mut [B] {
+ match try_cast_slice_mut(a) {
+ Ok(b) => b,
+ Err(e) => something_went_wrong("cast_slice_mut", e),
+ }
+}
+
+/// Try to cast `T` into `U`.
+///
+/// Note that for this particular type of cast, alignment isn't a factor. The
+/// input value is semantically copied into the function and then returned to a
+/// new memory location which will have whatever the required alignment of the
+/// output type is.
+///
+/// ## Failure
+///
+/// * If the types don't have the same size this fails.
+#[inline]
+pub(crate) unsafe fn try_cast<A: Copy, B: Copy>(
+ a: A,
+) -> Result<B, PodCastError> {
+ if size_of::<A>() == size_of::<B>() {
+ Ok(unsafe { transmute!(a) })
+ } else {
+ Err(PodCastError::SizeMismatch)
+ }
+}
+
+/// Try to convert a `&T` into `&U`.
+///
+/// ## Failure
+///
+/// * If the reference isn't aligned in the new type
+/// * If the source type and target type aren't the same size.
+#[inline]
+pub(crate) unsafe fn try_cast_ref<A: Copy, B: Copy>(
+ a: &A,
+) -> Result<&B, PodCastError> {
+ // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
+ // after monomorphization.
+ if align_of::<B>() > align_of::<A>()
+ && (a as *const A as usize) % align_of::<B>() != 0
+ {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else if size_of::<B>() == size_of::<A>() {
+ Ok(unsafe { &*(a as *const A as *const B) })
+ } else {
+ Err(PodCastError::SizeMismatch)
+ }
+}
+
+/// Try to convert a `&mut T` into `&mut U`.
+///
+/// As [`try_cast_ref`], but `mut`.
+#[inline]
+pub(crate) unsafe fn try_cast_mut<A: Copy, B: Copy>(
+ a: &mut A,
+) -> Result<&mut B, PodCastError> {
+ // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
+ // after monomorphization.
+ if align_of::<B>() > align_of::<A>()
+ && (a as *mut A as usize) % align_of::<B>() != 0
+ {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else if size_of::<B>() == size_of::<A>() {
+ Ok(unsafe { &mut *(a as *mut A as *mut B) })
+ } else {
+ Err(PodCastError::SizeMismatch)
+ }
+}
+
+/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
+///
+/// * `input.as_ptr() as usize == output.as_ptr() as usize`
+/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
+///
+/// ## Failure
+///
+/// * If the target type has a greater alignment requirement and the input slice
+/// isn't aligned.
+/// * If the target element type is a different size from the current element
+/// type, and the output slice wouldn't be a whole number of elements when
+/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
+/// that's a failure).
+/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
+/// and a non-ZST.
+#[inline]
+pub(crate) unsafe fn try_cast_slice<A: Copy, B: Copy>(
+ a: &[A],
+) -> Result<&[B], PodCastError> {
+ // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
+ // after monomorphization.
+ if align_of::<B>() > align_of::<A>()
+ && (a.as_ptr() as usize) % align_of::<B>() != 0
+ {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else if size_of::<B>() == size_of::<A>() {
+ Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, a.len()) })
+ } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
+ Err(PodCastError::SizeMismatch)
+ } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
+ let new_len = core::mem::size_of_val(a) / size_of::<B>();
+ Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, new_len) })
+ } else {
+ Err(PodCastError::OutputSliceWouldHaveSlop)
+ }
+}
+
+/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
+/// length).
+///
+/// As [`try_cast_slice`], but `&mut`.
+#[inline]
+pub(crate) unsafe fn try_cast_slice_mut<A: Copy, B: Copy>(
+ a: &mut [A],
+) -> Result<&mut [B], PodCastError> {
+ // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
+ // after monomorphization.
+ if align_of::<B>() > align_of::<A>()
+ && (a.as_mut_ptr() as usize) % align_of::<B>() != 0
+ {
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ } else if size_of::<B>() == size_of::<A>() {
+ Ok(unsafe {
+ core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, a.len())
+ })
+ } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
+ Err(PodCastError::SizeMismatch)
+ } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
+ let new_len = core::mem::size_of_val(a) / size_of::<B>();
+ Ok(unsafe {
+ core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, new_len)
+ })
+ } else {
+ Err(PodCastError::OutputSliceWouldHaveSlop)
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..d1bbca4
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,400 @@
+#![no_std]
+#![warn(missing_docs)]
+#![allow(clippy::match_like_matches_macro)]
+#![allow(clippy::uninlined_format_args)]
+#![cfg_attr(feature = "nightly_portable_simd", feature(portable_simd))]
+#![cfg_attr(feature = "nightly_stdsimd", feature(stdsimd))]
+
+//! This crate gives small utilities for casting between plain data types.
+//!
+//! ## Basics
+//!
+//! Data comes in five basic forms in Rust, so we have five basic casting
+//! functions:
+//!
+//! * `T` uses [`cast`]
+//! * `&T` uses [`cast_ref`]
+//! * `&mut T` uses [`cast_mut`]
+//! * `&[T]` uses [`cast_slice`]
+//! * `&mut [T]` uses [`cast_slice_mut`]
+//!
+//! Some casts will never fail (eg: `cast::<u32, f32>` always works), other
+//! casts might fail (eg: `cast_ref::<[u8; 4], u32>` will fail if the reference
+//! isn't already aligned to 4). Each casting function has a "try" version which
+//! will return a `Result`, and the "normal" version which will simply panic on
+//! invalid input.
+//!
+//! ## Using Your Own Types
+//!
+//! All the functions here are guarded by the [`Pod`] trait, which is a
+//! sub-trait of the [`Zeroable`] trait.
+//!
+//! If you're very sure that your type is eligible, you can implement those
+//! traits for your type and then they'll have full casting support. However,
+//! these traits are `unsafe`, and you should carefully read the requirements
+//! before adding the them to your own types.
+//!
+//! ## Features
+//!
+//! * This crate is core only by default, but if you're using Rust 1.36 or later
+//! you can enable the `extern_crate_alloc` cargo feature for some additional
+//! methods related to `Box` and `Vec`. Note that the `docs.rs` documentation
+//! is always built with `extern_crate_alloc` cargo feature enabled.
+
+#[cfg(all(target_arch = "aarch64", feature = "aarch64_simd"))]
+use core::arch::aarch64;
+#[cfg(all(target_arch = "wasm32", feature = "wasm_simd"))]
+use core::arch::wasm32;
+#[cfg(target_arch = "x86")]
+use core::arch::x86;
+#[cfg(target_arch = "x86_64")]
+use core::arch::x86_64;
+//
+use core::{marker::*, mem::*, num::*, ptr::*};
+
+// Used from macros to ensure we aren't using some locally defined name and
+// actually are referencing libcore. This also would allow pre-2018 edition
+// crates to use our macros, but I'm not sure how important that is.
+#[doc(hidden)]
+pub use ::core as __core;
+
+#[cfg(not(feature = "min_const_generics"))]
+macro_rules! impl_unsafe_marker_for_array {
+ ( $marker:ident , $( $n:expr ),* ) => {
+ $(unsafe impl<T> $marker for [T; $n] where T: $marker {})*
+ }
+}
+
+/// A macro to transmute between two types without requiring knowing size
+/// statically.
+macro_rules! transmute {
+ ($val:expr) => {
+ ::core::mem::transmute_copy(&::core::mem::ManuallyDrop::new($val))
+ };
+}
+
+/// A macro to implement marker traits for various simd types.
+/// #[allow(unused)] because the impls are only compiled on relevant platforms
+/// with relevant cargo features enabled.
+#[allow(unused)]
+macro_rules! impl_unsafe_marker_for_simd {
+ (unsafe impl $trait:ident for $platform:ident :: {}) => {};
+ (unsafe impl $trait:ident for $platform:ident :: { $first_type:ident $(, $types:ident)* $(,)? }) => {
+ unsafe impl $trait for $platform::$first_type {}
+ impl_unsafe_marker_for_simd!(unsafe impl $trait for $platform::{ $( $types ),* });
+ };
+}
+
+#[cfg(feature = "extern_crate_std")]
+extern crate std;
+
+#[cfg(feature = "extern_crate_alloc")]
+extern crate alloc;
+#[cfg(feature = "extern_crate_alloc")]
+pub mod allocation;
+#[cfg(feature = "extern_crate_alloc")]
+pub use allocation::*;
+
+mod anybitpattern;
+pub use anybitpattern::*;
+
+pub mod checked;
+pub use checked::CheckedBitPattern;
+
+mod internal;
+
+mod zeroable;
+pub use zeroable::*;
+mod zeroable_in_option;
+pub use zeroable_in_option::*;
+
+mod pod;
+pub use pod::*;
+mod pod_in_option;
+pub use pod_in_option::*;
+
+mod no_uninit;
+pub use no_uninit::*;
+
+mod contiguous;
+pub use contiguous::*;
+
+mod offset_of;
+pub use offset_of::*;
+
+mod transparent;
+pub use transparent::*;
+
+#[cfg(feature = "derive")]
+pub use bytemuck_derive::{
+ AnyBitPattern, ByteEq, ByteHash, CheckedBitPattern, Contiguous, NoUninit,
+ Pod, TransparentWrapper, Zeroable,
+};
+
+/// The things that can go wrong when casting between [`Pod`] data forms.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum PodCastError {
+ /// You tried to cast a slice to an element type with a higher alignment
+ /// requirement but the slice wasn't aligned.
+ TargetAlignmentGreaterAndInputNotAligned,
+ /// If the element size changes then the output slice changes length
+ /// accordingly. If the output slice wouldn't be a whole number of elements
+ /// then the conversion fails.
+ OutputSliceWouldHaveSlop,
+ /// When casting a slice you can't convert between ZST elements and non-ZST
+ /// elements. When casting an individual `T`, `&T`, or `&mut T` value the
+ /// source size and destination size must be an exact match.
+ SizeMismatch,
+ /// For this type of cast the alignments must be exactly the same and they
+ /// were not so now you're sad.
+ ///
+ /// This error is generated **only** by operations that cast allocated types
+ /// (such as `Box` and `Vec`), because in that case the alignment must stay
+ /// exact.
+ AlignmentMismatch,
+}
+#[cfg(not(target_arch = "spirv"))]
+impl core::fmt::Display for PodCastError {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ write!(f, "{:?}", self)
+ }
+}
+#[cfg(feature = "extern_crate_std")]
+impl std::error::Error for PodCastError {}
+
+/// Re-interprets `&T` as `&[u8]`.
+///
+/// Any ZST becomes an empty slice, and in that case the pointer value of that
+/// empty slice might not match the pointer value of the input reference.
+#[inline]
+pub fn bytes_of<T: NoUninit>(t: &T) -> &[u8] {
+ unsafe { internal::bytes_of(t) }
+}
+
+/// Re-interprets `&mut T` as `&mut [u8]`.
+///
+/// Any ZST becomes an empty slice, and in that case the pointer value of that
+/// empty slice might not match the pointer value of the input reference.
+#[inline]
+pub fn bytes_of_mut<T: NoUninit + AnyBitPattern>(t: &mut T) -> &mut [u8] {
+ unsafe { internal::bytes_of_mut(t) }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes`] but will panic on error.
+#[inline]
+pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
+ unsafe { internal::from_bytes(s) }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Panics
+///
+/// This is [`try_from_bytes_mut`] but will panic on error.
+#[inline]
+pub fn from_bytes_mut<T: NoUninit + AnyBitPattern>(s: &mut [u8]) -> &mut T {
+ unsafe { internal::from_bytes_mut(s) }
+}
+
+/// Reads from the bytes as if they were a `T`.
+///
+/// ## Failure
+/// * If the `bytes` length is not equal to `size_of::<T>()`.
+#[inline]
+pub fn try_pod_read_unaligned<T: AnyBitPattern>(
+ bytes: &[u8],
+) -> Result<T, PodCastError> {
+ unsafe { internal::try_pod_read_unaligned(bytes) }
+}
+
+/// Reads the slice into a `T` value.
+///
+/// ## Panics
+/// * This is like `try_pod_read_unaligned` but will panic on failure.
+#[inline]
+pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
+ unsafe { internal::pod_read_unaligned(bytes) }
+}
+
+/// Re-interprets `&[u8]` as `&T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+#[inline]
+pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
+ unsafe { internal::try_from_bytes(s) }
+}
+
+/// Re-interprets `&mut [u8]` as `&mut T`.
+///
+/// ## Failure
+///
+/// * If the slice isn't aligned for the new type
+/// * If the slice's length isn’t exactly the size of the new type
+#[inline]
+pub fn try_from_bytes_mut<T: NoUninit + AnyBitPattern>(
+ s: &mut [u8],
+) -> Result<&mut T, PodCastError> {
+ unsafe { internal::try_from_bytes_mut(s) }
+}
+
+/// Cast `T` into `U`
+///
+/// ## Panics
+///
+/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
+#[inline]
+pub fn cast<A: NoUninit, B: AnyBitPattern>(a: A) -> B {
+ unsafe { internal::cast(a) }
+}
+
+/// Cast `&mut T` into `&mut U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_mut`] but will panic on error.
+#[inline]
+pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
+ a: &mut A,
+) -> &mut B {
+ unsafe { internal::cast_mut(a) }
+}
+
+/// Cast `&T` into `&U`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_ref`] but will panic on error.
+#[inline]
+pub fn cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> &B {
+ unsafe { internal::cast_ref(a) }
+}
+
+/// Cast `&[A]` into `&[B]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice`] but will panic on error.
+#[inline]
+pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
+ unsafe { internal::cast_slice(a) }
+}
+
+/// Cast `&mut [T]` into `&mut [U]`.
+///
+/// ## Panics
+///
+/// This is [`try_cast_slice_mut`] but will panic on error.
+#[inline]
+pub fn cast_slice_mut<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ a: &mut [A],
+) -> &mut [B] {
+ unsafe { internal::cast_slice_mut(a) }
+}
+
+/// As `align_to`, but safe because of the [`Pod`] bound.
+#[inline]
+pub fn pod_align_to<T: NoUninit, U: AnyBitPattern>(
+ vals: &[T],
+) -> (&[T], &[U], &[T]) {
+ unsafe { vals.align_to::<U>() }
+}
+
+/// As `align_to_mut`, but safe because of the [`Pod`] bound.
+#[inline]
+pub fn pod_align_to_mut<
+ T: NoUninit + AnyBitPattern,
+ U: NoUninit + AnyBitPattern,
+>(
+ vals: &mut [T],
+) -> (&mut [T], &mut [U], &mut [T]) {
+ unsafe { vals.align_to_mut::<U>() }
+}
+
+/// Try to cast `T` into `U`.
+///
+/// Note that for this particular type of cast, alignment isn't a factor. The
+/// input value is semantically copied into the function and then returned to a
+/// new memory location which will have whatever the required alignment of the
+/// output type is.
+///
+/// ## Failure
+///
+/// * If the types don't have the same size this fails.
+#[inline]
+pub fn try_cast<A: NoUninit, B: AnyBitPattern>(
+ a: A,
+) -> Result<B, PodCastError> {
+ unsafe { internal::try_cast(a) }
+}
+
+/// Try to convert a `&T` into `&U`.
+///
+/// ## Failure
+///
+/// * If the reference isn't aligned in the new type
+/// * If the source type and target type aren't the same size.
+#[inline]
+pub fn try_cast_ref<A: NoUninit, B: AnyBitPattern>(
+ a: &A,
+) -> Result<&B, PodCastError> {
+ unsafe { internal::try_cast_ref(a) }
+}
+
+/// Try to convert a `&mut T` into `&mut U`.
+///
+/// As [`try_cast_ref`], but `mut`.
+#[inline]
+pub fn try_cast_mut<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ a: &mut A,
+) -> Result<&mut B, PodCastError> {
+ unsafe { internal::try_cast_mut(a) }
+}
+
+/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
+///
+/// * `input.as_ptr() as usize == output.as_ptr() as usize`
+/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
+///
+/// ## Failure
+///
+/// * If the target type has a greater alignment requirement and the input slice
+/// isn't aligned.
+/// * If the target element type is a different size from the current element
+/// type, and the output slice wouldn't be a whole number of elements when
+/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
+/// that's a failure).
+/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
+/// and a non-ZST.
+#[inline]
+pub fn try_cast_slice<A: NoUninit, B: AnyBitPattern>(
+ a: &[A],
+) -> Result<&[B], PodCastError> {
+ unsafe { internal::try_cast_slice(a) }
+}
+
+/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
+/// length).
+///
+/// As [`try_cast_slice`], but `&mut`.
+#[inline]
+pub fn try_cast_slice_mut<
+ A: NoUninit + AnyBitPattern,
+ B: NoUninit + AnyBitPattern,
+>(
+ a: &mut [A],
+) -> Result<&mut [B], PodCastError> {
+ unsafe { internal::try_cast_slice_mut(a) }
+}
diff --git a/src/no_uninit.rs b/src/no_uninit.rs
new file mode 100644
index 0000000..cc94b52
--- /dev/null
+++ b/src/no_uninit.rs
@@ -0,0 +1,80 @@
+use crate::Pod;
+use core::num::{
+ NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize,
+ NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
+};
+
+/// Marker trait for "plain old data" types with no uninit (or padding) bytes.
+///
+/// The requirements for this is very similar to [`Pod`],
+/// except that it doesn't require that all bit patterns of the type are valid,
+/// i.e. it does not require the type to be [`Zeroable`][crate::Zeroable].
+/// This limits what you can do with a type of this kind, but also broadens the
+/// included types to things like C-style enums. Notably, you can only cast from
+/// *immutable* references to a [`NoUninit`] type into *immutable* references of
+/// any other type, no casting of mutable references or mutable references to
+/// slices etc.
+///
+/// [`Pod`] is a subset of [`NoUninit`], meaning that any `T: Pod` is also
+/// [`NoUninit`] but any `T: NoUninit` is not necessarily [`Pod`]. If possible,
+/// prefer implementing [`Pod`] directly. To get more [`Pod`]-like functionality
+/// for a type that is only [`NoUninit`], consider also implementing
+/// [`CheckedBitPattern`][crate::CheckedBitPattern].
+///
+/// # Derive
+///
+/// A `#[derive(NoUninit)]` macro is provided under the `derive` feature flag
+/// which will automatically validate the requirements of this trait and
+/// implement the trait for you for both enums and structs. This is the
+/// recommended method for implementing the trait, however it's also possible to
+/// do manually. If you implement it manually, you *must* carefully follow the
+/// below safety rules.
+///
+/// # Safety
+///
+/// The same as [`Pod`] except we disregard the rule about it must
+/// allow any bit pattern (i.e. it does not need to be
+/// [`Zeroable`][crate::Zeroable]). Still, this is a quite strong guarantee
+/// about a type, so *be careful* whem implementing it manually.
+///
+/// * The type must be inhabited (eg: no
+/// [Infallible](core::convert::Infallible)).
+/// * The type must not contain any uninit (or padding) bytes, either in the
+/// middle or on the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has
+/// padding in the middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which
+/// has padding on the end).
+/// * Structs need to have all fields also be `NoUninit`.
+/// * Structs need to be `repr(C)` or `repr(transparent)`. In the case of
+/// `repr(C)`, the `packed` and `align` repr modifiers can be used as long as
+/// all other rules end up being followed.
+/// * Enums need to have an explicit `#[repr(Int)]`
+/// * Enums must have only fieldless variants
+/// * It is disallowed for types to contain pointer types, `Cell`, `UnsafeCell`,
+/// atomics, and any other forms of interior mutability.
+/// * More precisely: A shared reference to the type must allow reads, and
+/// *only* reads. RustBelt's separation logic is based on the notion that a
+/// type is allowed to define a sharing predicate, its own invariant that must
+/// hold for shared references, and this predicate is the reasoning that allow
+/// it to deal with atomic and cells etc. We require the sharing predicate to
+/// be trivial and permit only read-only access.
+/// * There's probably more, don't mess it up (I mean it).
+pub unsafe trait NoUninit: Sized + Copy + 'static {}
+
+unsafe impl<T: Pod> NoUninit for T {}
+
+unsafe impl NoUninit for char {}
+
+unsafe impl NoUninit for bool {}
+
+unsafe impl NoUninit for NonZeroU8 {}
+unsafe impl NoUninit for NonZeroI8 {}
+unsafe impl NoUninit for NonZeroU16 {}
+unsafe impl NoUninit for NonZeroI16 {}
+unsafe impl NoUninit for NonZeroU32 {}
+unsafe impl NoUninit for NonZeroI32 {}
+unsafe impl NoUninit for NonZeroU64 {}
+unsafe impl NoUninit for NonZeroI64 {}
+unsafe impl NoUninit for NonZeroU128 {}
+unsafe impl NoUninit for NonZeroI128 {}
+unsafe impl NoUninit for NonZeroUsize {}
+unsafe impl NoUninit for NonZeroIsize {}
diff --git a/src/offset_of.rs b/src/offset_of.rs
new file mode 100644
index 0000000..3de2327
--- /dev/null
+++ b/src/offset_of.rs
@@ -0,0 +1,135 @@
+#![forbid(unsafe_code)]
+
+/// Find the offset in bytes of the given `$field` of `$Type`. Requires an
+/// already initialized `$instance` value to work with.
+///
+/// This is similar to the macro from [`memoffset`](https://docs.rs/memoffset),
+/// however it uses no `unsafe` code.
+///
+/// This macro has a 3-argument and 2-argument version.
+/// * In the 3-arg version you specify an instance of the type, the type itself,
+/// and the field name.
+/// * In the 2-arg version the macro will call the [`default`](Default::default)
+/// method to make a temporary instance of the type for you.
+///
+/// The output of this macro is the byte offset of the field (as a `usize`). The
+/// calculations of the macro are fixed across the entire program, but if the
+/// type used is `repr(Rust)` then they're *not* fixed across compilations or
+/// compilers.
+///
+/// ## Examples
+///
+/// ### 3-arg Usage
+///
+/// ```rust
+/// # use bytemuck::offset_of;
+/// // enums can't derive default, and for this example we don't pick one
+/// enum MyExampleEnum {
+/// A,
+/// B,
+/// C,
+/// }
+///
+/// // so now our struct here doesn't have Default
+/// #[repr(C)]
+/// struct MyNotDefaultType {
+/// pub counter: i32,
+/// pub some_field: MyExampleEnum,
+/// }
+///
+/// // but we provide an instance of the type and it's all good.
+/// let val = MyNotDefaultType { counter: 5, some_field: MyExampleEnum::A };
+/// assert_eq!(offset_of!(val, MyNotDefaultType, some_field), 4);
+/// ```
+///
+/// ### 2-arg Usage
+///
+/// ```rust
+/// # use bytemuck::offset_of;
+/// #[derive(Default)]
+/// #[repr(C)]
+/// struct Vertex {
+/// pub loc: [f32; 3],
+/// pub color: [f32; 3],
+/// }
+/// // if the type impls Default the macro can make its own default instance.
+/// assert_eq!(offset_of!(Vertex, loc), 0);
+/// assert_eq!(offset_of!(Vertex, color), 12);
+/// ```
+///
+/// # Usage with `#[repr(packed)]` structs
+///
+/// Attempting to compute the offset of a `#[repr(packed)]` struct with
+/// `bytemuck::offset_of!` requires an `unsafe` block. We hope to relax this in
+/// the future, but currently it is required to work around a soundness hole in
+/// Rust (See [rust-lang/rust#27060]).
+///
+/// [rust-lang/rust#27060]: https://github.com/rust-lang/rust/issues/27060
+///
+/// <p style="background:rgba(255,181,77,0.16);padding:0.75em;">
+/// <strong>Warning:</strong> This is only true for versions of bytemuck >
+/// 1.4.0. Previous versions of
+/// <code style="background:rgba(41,24,0,0.1);">bytemuck::offset_of!</code>
+/// will only emit a warning when used on the field of a packed struct in safe
+/// code, which can lead to unsoundness.
+/// </p>
+///
+/// For example, the following will fail to compile:
+///
+/// ```compile_fail
+/// #[repr(C, packed)]
+/// #[derive(Default)]
+/// struct Example {
+/// field: u32,
+/// }
+/// // Doesn't compile:
+/// let _offset = bytemuck::offset_of!(Example, field);
+/// ```
+///
+/// While the error message this generates will mention the
+/// `safe_packed_borrows` lint, the macro will still fail to compile even if
+/// that lint is `#[allow]`ed:
+///
+/// ```compile_fail
+/// # #[repr(C, packed)] #[derive(Default)] struct Example { field: u32 }
+/// // Still doesn't compile:
+/// #[allow(safe_packed_borrows)]
+/// {
+/// let _offset = bytemuck::offset_of!(Example, field);
+/// }
+/// ```
+///
+/// This *can* be worked around by using `unsafe`, but it is only sound to do so
+/// if you can guarantee that taking a reference to the field is sound.
+///
+/// In practice, this means it only works for fields of align(1) types, or if
+/// you know the field's offset in advance (defeating the point of `offset_of`)
+/// and can prove that the struct's alignment and the field's offset are enough
+/// to prove the field's alignment.
+///
+/// Once the `raw_ref` macros are available, a future version of this crate will
+/// use them to lift the limitations of packed structs. For the duration of the
+/// `1.x` version of this crate that will be behind an on-by-default cargo
+/// feature (to maintain minimum rust version support).
+#[macro_export]
+macro_rules! offset_of {
+ ($instance:expr, $Type:path, $field:tt) => {{
+ #[forbid(safe_packed_borrows)]
+ {
+ // This helps us guard against field access going through a Deref impl.
+ #[allow(clippy::unneeded_field_pattern)]
+ let $Type { $field: _, .. };
+ let reference: &$Type = &$instance;
+ let address = reference as *const _ as usize;
+ let field_pointer = &reference.$field as *const _ as usize;
+ // These asserts/unwraps are compiled away at release, and defend against
+ // the case where somehow a deref impl is still invoked.
+ let result = field_pointer.checked_sub(address).unwrap();
+ assert!(result <= $crate::__core::mem::size_of::<$Type>());
+ result
+ }
+ }};
+ ($Type:path, $field:tt) => {{
+ $crate::offset_of!(<$Type as Default>::default(), $Type, $field)
+ }};
+}
diff --git a/src/pod.rs b/src/pod.rs
new file mode 100644
index 0000000..2ea7f4b
--- /dev/null
+++ b/src/pod.rs
@@ -0,0 +1,148 @@
+use super::*;
+
+/// Marker trait for "plain old data".
+///
+/// The point of this trait is that once something is marked "plain old data"
+/// you can really go to town with the bit fiddling and bit casting. Therefore,
+/// it's a relatively strong claim to make about a type. Do not add this to your
+/// type casually.
+///
+/// **Reminder:** The results of casting around bytes between data types are
+/// _endian dependant_. Little-endian machines are the most common, but
+/// big-endian machines do exist (and big-endian is also used for "network
+/// order" bytes).
+///
+/// ## Safety
+///
+/// * The type must be inhabited (eg: no
+/// [Infallible](core::convert::Infallible)).
+/// * The type must allow any bit pattern (eg: no `bool` or `char`, which have
+/// illegal bit patterns).
+/// * The type must not contain any uninit (or padding) bytes, either in the
+/// middle or on the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has
+/// padding in the middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which
+/// has padding on the end).
+/// * The type needs to have all fields also be `Pod`.
+/// * The type needs to be `repr(C)` or `repr(transparent)`. In the case of
+/// `repr(C)`, the `packed` and `align` repr modifiers can be used as long as
+/// all other rules end up being followed.
+/// * It is disallowed for types to contain pointer types, `Cell`, `UnsafeCell`,
+/// atomics, and any other forms of interior mutability.
+/// * More precisely: A shared reference to the type must allow reads, and
+/// *only* reads. RustBelt's separation logic is based on the notion that a
+/// type is allowed to define a sharing predicate, its own invariant that must
+/// hold for shared references, and this predicate is the reasoning that allow
+/// it to deal with atomic and cells etc. We require the sharing predicate to
+/// be trivial and permit only read-only access.
+pub unsafe trait Pod: Zeroable + Copy + 'static {}
+
+unsafe impl Pod for () {}
+unsafe impl Pod for u8 {}
+unsafe impl Pod for i8 {}
+unsafe impl Pod for u16 {}
+unsafe impl Pod for i16 {}
+unsafe impl Pod for u32 {}
+unsafe impl Pod for i32 {}
+unsafe impl Pod for u64 {}
+unsafe impl Pod for i64 {}
+unsafe impl Pod for usize {}
+unsafe impl Pod for isize {}
+unsafe impl Pod for u128 {}
+unsafe impl Pod for i128 {}
+unsafe impl Pod for f32 {}
+unsafe impl Pod for f64 {}
+unsafe impl<T: Pod> Pod for Wrapping<T> {}
+
+#[cfg(feature = "unsound_ptr_pod_impl")]
+unsafe impl<T: 'static> Pod for *mut T {}
+#[cfg(feature = "unsound_ptr_pod_impl")]
+unsafe impl<T: 'static> Pod for *const T {}
+#[cfg(feature = "unsound_ptr_pod_impl")]
+unsafe impl<T: 'static> PodInOption for NonNull<T> {}
+
+unsafe impl<T: Pod> Pod for PhantomData<T> {}
+unsafe impl Pod for PhantomPinned {}
+unsafe impl<T: Pod> Pod for ManuallyDrop<T> {}
+
+// Note(Lokathor): MaybeUninit can NEVER be Pod.
+
+#[cfg(feature = "min_const_generics")]
+unsafe impl<T, const N: usize> Pod for [T; N] where T: Pod {}
+
+#[cfg(not(feature = "min_const_generics"))]
+impl_unsafe_marker_for_array!(
+ Pod, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 48, 64, 96, 128, 256,
+ 512, 1024, 2048, 4096
+);
+
+#[cfg(all(target_arch = "wasm32", feature = "wasm_simd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for wasm32::{v128}
+);
+
+#[cfg(all(target_arch = "aarch64", feature = "aarch64_simd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for aarch64::{
+ float32x2_t, float32x2x2_t, float32x2x3_t, float32x2x4_t, float32x4_t,
+ float32x4x2_t, float32x4x3_t, float32x4x4_t, float64x1_t, float64x1x2_t,
+ float64x1x3_t, float64x1x4_t, float64x2_t, float64x2x2_t, float64x2x3_t,
+ float64x2x4_t, int16x4_t, int16x4x2_t, int16x4x3_t, int16x4x4_t, int16x8_t,
+ int16x8x2_t, int16x8x3_t, int16x8x4_t, int32x2_t, int32x2x2_t, int32x2x3_t,
+ int32x2x4_t, int32x4_t, int32x4x2_t, int32x4x3_t, int32x4x4_t, int64x1_t,
+ int64x1x2_t, int64x1x3_t, int64x1x4_t, int64x2_t, int64x2x2_t, int64x2x3_t,
+ int64x2x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int8x8_t,
+ int8x8x2_t, int8x8x3_t, int8x8x4_t, poly16x4_t, poly16x4x2_t, poly16x4x3_t,
+ poly16x4x4_t, poly16x8_t, poly16x8x2_t, poly16x8x3_t, poly16x8x4_t,
+ poly64x1_t, poly64x1x2_t, poly64x1x3_t, poly64x1x4_t, poly64x2_t,
+ poly64x2x2_t, poly64x2x3_t, poly64x2x4_t, poly8x16_t, poly8x16x2_t,
+ poly8x16x3_t, poly8x16x4_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t, poly8x8x4_t,
+ uint16x4_t, uint16x4x2_t, uint16x4x3_t, uint16x4x4_t, uint16x8_t,
+ uint16x8x2_t, uint16x8x3_t, uint16x8x4_t, uint32x2_t, uint32x2x2_t,
+ uint32x2x3_t, uint32x2x4_t, uint32x4_t, uint32x4x2_t, uint32x4x3_t,
+ uint32x4x4_t, uint64x1_t, uint64x1x2_t, uint64x1x3_t, uint64x1x4_t,
+ uint64x2_t, uint64x2x2_t, uint64x2x3_t, uint64x2x4_t, uint8x16_t,
+ uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint8x8_t, uint8x8x2_t,
+ uint8x8x3_t, uint8x8x4_t,
+ }
+);
+
+#[cfg(target_arch = "x86")]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for x86::{
+ __m128i, __m128, __m128d,
+ __m256i, __m256, __m256d,
+ }
+);
+
+#[cfg(target_arch = "x86_64")]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for x86_64::{
+ __m128i, __m128, __m128d,
+ __m256i, __m256, __m256d,
+ }
+);
+
+#[cfg(feature = "nightly_portable_simd")]
+unsafe impl<T, const N: usize> Pod for core::simd::Simd<T, N>
+where
+ T: core::simd::SimdElement + Pod,
+ core::simd::LaneCount<N>: core::simd::SupportedLaneCount,
+{
+}
+
+#[cfg(all(target_arch = "x86", feature = "nightly_stdsimd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for x86::{
+ __m128bh, __m256bh, __m512,
+ __m512bh, __m512d, __m512i,
+ }
+);
+
+#[cfg(all(target_arch = "x86_64", feature = "nightly_stdsimd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Pod for x86_64::{
+ __m128bh, __m256bh, __m512,
+ __m512bh, __m512d, __m512i,
+ }
+);
diff --git a/src/pod_in_option.rs b/src/pod_in_option.rs
new file mode 100644
index 0000000..87ab93a
--- /dev/null
+++ b/src/pod_in_option.rs
@@ -0,0 +1,27 @@
+use super::*;
+
+// Note(Lokathor): This is the neat part!!
+unsafe impl<T: PodInOption> Pod for Option<T> {}
+
+/// Trait for types which are [Pod](Pod) when wrapped in
+/// [Option](core::option::Option).
+///
+/// ## Safety
+///
+/// * `Option<T>` must uphold the same invariants as [Pod](Pod).
+/// * **Reminder:** pointers are **not** pod! **Do not** mix this trait with a
+/// newtype over [NonNull](core::ptr::NonNull).
+pub unsafe trait PodInOption: ZeroableInOption + Copy + 'static {}
+
+unsafe impl PodInOption for NonZeroI8 {}
+unsafe impl PodInOption for NonZeroI16 {}
+unsafe impl PodInOption for NonZeroI32 {}
+unsafe impl PodInOption for NonZeroI64 {}
+unsafe impl PodInOption for NonZeroI128 {}
+unsafe impl PodInOption for NonZeroIsize {}
+unsafe impl PodInOption for NonZeroU8 {}
+unsafe impl PodInOption for NonZeroU16 {}
+unsafe impl PodInOption for NonZeroU32 {}
+unsafe impl PodInOption for NonZeroU64 {}
+unsafe impl PodInOption for NonZeroU128 {}
+unsafe impl PodInOption for NonZeroUsize {}
diff --git a/src/transparent.rs b/src/transparent.rs
new file mode 100644
index 0000000..11aa073
--- /dev/null
+++ b/src/transparent.rs
@@ -0,0 +1,288 @@
+use super::*;
+
+/// A trait which indicates that a type is a `#[repr(transparent)]` wrapper
+/// around the `Inner` value.
+///
+/// This allows safely copy transmuting between the `Inner` type and the
+/// `TransparentWrapper` type. Functions like `wrap_{}` convert from the inner
+/// type to the wrapper type and `peel_{}` functions do the inverse conversion
+/// from the wrapper type to the inner type. We deliberately do not call the
+/// wrapper-removing methods "unwrap" because at this point that word is too
+/// strongly tied to the Option/ Result methods.
+///
+/// # Safety
+///
+/// The safety contract of `TransparentWrapper` is relatively simple:
+///
+/// For a given `Wrapper` which implements `TransparentWrapper<Inner>`:
+///
+/// 1. `Wrapper` must be a wrapper around `Inner` with an identical data
+/// representations. This either means that it must be a
+/// `#[repr(transparent)]` struct which contains a either a field of type
+/// `Inner` (or a field of some other transparent wrapper for `Inner`) as
+/// the only non-ZST field.
+///
+/// 2. Any fields *other* than the `Inner` field must be trivially constructable
+/// ZSTs, for example `PhantomData`, `PhantomPinned`, etc. (When deriving
+/// `TransparentWrapper` on a type with ZST fields, the ZST fields must be
+/// [`Zeroable`]).
+///
+/// 3. The `Wrapper` may not impose additional alignment requirements over
+/// `Inner`.
+/// - Note: this is currently guaranteed by `repr(transparent)`, but there
+/// have been discussions of lifting it, so it's stated here explicitly.
+///
+/// 4. All functions on `TransparentWrapper` **may not** be overridden.
+///
+/// ## Caveats
+///
+/// If the wrapper imposes additional constraints upon the inner type which are
+/// required for safety, it's responsible for ensuring those still hold -- this
+/// generally requires preventing access to instances of the inner type, as
+/// implementing `TransparentWrapper<U> for T` means anybody can call
+/// `T::cast_ref(any_instance_of_u)`.
+///
+/// For example, it would be invalid to implement TransparentWrapper for `str`
+/// to implement `TransparentWrapper` around `[u8]` because of this.
+///
+/// # Examples
+///
+/// ## Basic
+///
+/// ```
+/// use bytemuck::TransparentWrapper;
+/// # #[derive(Default)]
+/// # struct SomeStruct(u32);
+///
+/// #[repr(transparent)]
+/// struct MyWrapper(SomeStruct);
+///
+/// unsafe impl TransparentWrapper<SomeStruct> for MyWrapper {}
+///
+/// // interpret a reference to &SomeStruct as a &MyWrapper
+/// let thing = SomeStruct::default();
+/// let inner_ref: &MyWrapper = MyWrapper::wrap_ref(&thing);
+///
+/// // Works with &mut too.
+/// let mut mut_thing = SomeStruct::default();
+/// let inner_mut: &mut MyWrapper = MyWrapper::wrap_mut(&mut mut_thing);
+///
+/// # let _ = (inner_ref, inner_mut); // silence warnings
+/// ```
+///
+/// ## Use with dynamically sized types
+///
+/// ```
+/// use bytemuck::TransparentWrapper;
+///
+/// #[repr(transparent)]
+/// struct Slice<T>([T]);
+///
+/// unsafe impl<T> TransparentWrapper<[T]> for Slice<T> {}
+///
+/// let s = Slice::wrap_ref(&[1u32, 2, 3]);
+/// assert_eq!(&s.0, &[1, 2, 3]);
+///
+/// let mut buf = [1, 2, 3u8];
+/// let sm = Slice::wrap_mut(&mut buf);
+/// ```
+///
+/// ## Deriving
+///
+/// When deriving, the non-wrapped fields must uphold all the normal requirements,
+/// and must also be `Zeroable`.
+///
+#[cfg_attr(feature = "derive", doc = "```")]
+#[cfg_attr(
+ not(feature = "derive"),
+ doc = "```ignore
+// This example requires the `derive` feature."
+)]
+/// use bytemuck::TransparentWrapper;
+/// use std::marker::PhantomData;
+///
+/// #[derive(TransparentWrapper)]
+/// #[repr(transparent)]
+/// #[transparent(usize)]
+/// struct Wrapper<T: ?Sized>(usize, PhantomData<T>); // PhantomData<T> implements Zeroable for all T
+/// ```
+///
+/// Here, an error will occur, because `MyZst` does not implement `Zeroable`.
+///
+#[cfg_attr(feature = "derive", doc = "```compile_fail")]
+#[cfg_attr(
+ not(feature = "derive"),
+ doc = "```ignore
+// This example requires the `derive` feature."
+)]
+/// use bytemuck::TransparentWrapper;
+/// struct MyZst;
+///
+/// #[derive(TransparentWrapper)]
+/// #[repr(transparent)]
+/// #[transparent(usize)]
+/// struct Wrapper(usize, MyZst); // MyZst does not implement Zeroable
+/// ```
+pub unsafe trait TransparentWrapper<Inner: ?Sized> {
+ /// Convert the inner type into the wrapper type.
+ #[inline]
+ fn wrap(s: Inner) -> Self
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ // SAFETY: The unsafe contract requires that `Self` and `Inner` have
+ // identical representations.
+ unsafe { transmute!(s) }
+ }
+
+ /// Convert a reference to the inner type into a reference to the wrapper
+ /// type.
+ #[inline]
+ fn wrap_ref(s: &Inner) -> &Self {
+ unsafe {
+ assert!(size_of::<*const Inner>() == size_of::<*const Self>());
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations.
+ let inner_ptr = s as *const Inner;
+ let wrapper_ptr: *const Self = transmute!(inner_ptr);
+ &*wrapper_ptr
+ }
+ }
+
+ /// Convert a mutable reference to the inner type into a mutable reference to
+ /// the wrapper type.
+ #[inline]
+ fn wrap_mut(s: &mut Inner) -> &mut Self {
+ unsafe {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations.
+ let inner_ptr = s as *mut Inner;
+ let wrapper_ptr: *mut Self = transmute!(inner_ptr);
+ &mut *wrapper_ptr
+ }
+ }
+
+ /// Convert a slice to the inner type into a slice to the wrapper type.
+ #[inline]
+ fn wrap_slice(s: &[Inner]) -> &[Self]
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ unsafe {
+ assert!(size_of::<*const Inner>() == size_of::<*const Self>());
+ assert!(align_of::<*const Inner>() == align_of::<*const Self>());
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations (size and alignment).
+ core::slice::from_raw_parts(s.as_ptr() as *const Self, s.len())
+ }
+ }
+
+ /// Convert a mutable slice to the inner type into a mutable slice to the
+ /// wrapper type.
+ #[inline]
+ fn wrap_slice_mut(s: &mut [Inner]) -> &mut [Self]
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ unsafe {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+ assert!(align_of::<*mut Inner>() == align_of::<*mut Self>());
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations (size and alignment).
+ core::slice::from_raw_parts_mut(s.as_mut_ptr() as *mut Self, s.len())
+ }
+ }
+
+ /// Convert the wrapper type into the inner type.
+ #[inline]
+ fn peel(s: Self) -> Inner
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ unsafe { transmute!(s) }
+ }
+
+ /// Convert a reference to the wrapper type into a reference to the inner
+ /// type.
+ #[inline]
+ fn peel_ref(s: &Self) -> &Inner {
+ unsafe {
+ assert!(size_of::<*const Inner>() == size_of::<*const Self>());
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations.
+ let wrapper_ptr = s as *const Self;
+ let inner_ptr: *const Inner = transmute!(wrapper_ptr);
+ &*inner_ptr
+ }
+ }
+
+ /// Convert a mutable reference to the wrapper type into a mutable reference
+ /// to the inner type.
+ #[inline]
+ fn peel_mut(s: &mut Self) -> &mut Inner {
+ unsafe {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+ // A pointer cast doesn't work here because rustc can't tell that
+ // the vtables match (because of the `?Sized` restriction relaxation).
+ // A `transmute` doesn't work because the sizes are unspecified.
+ //
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations.
+ let wrapper_ptr = s as *mut Self;
+ let inner_ptr: *mut Inner = transmute!(wrapper_ptr);
+ &mut *inner_ptr
+ }
+ }
+
+ /// Convert a slice to the wrapped type into a slice to the inner type.
+ #[inline]
+ fn peel_slice(s: &[Self]) -> &[Inner]
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ unsafe {
+ assert!(size_of::<*const Inner>() == size_of::<*const Self>());
+ assert!(align_of::<*const Inner>() == align_of::<*const Self>());
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations (size and alignment).
+ core::slice::from_raw_parts(s.as_ptr() as *const Inner, s.len())
+ }
+ }
+
+ /// Convert a mutable slice to the wrapped type into a mutable slice to the
+ /// inner type.
+ #[inline]
+ fn peel_slice_mut(s: &mut [Self]) -> &mut [Inner]
+ where
+ Self: Sized,
+ Inner: Sized,
+ {
+ unsafe {
+ assert!(size_of::<*mut Inner>() == size_of::<*mut Self>());
+ assert!(align_of::<*mut Inner>() == align_of::<*mut Self>());
+ // SAFETY: The unsafe contract requires that these two have
+ // identical representations (size and alignment).
+ core::slice::from_raw_parts_mut(s.as_mut_ptr() as *mut Inner, s.len())
+ }
+ }
+}
+
+unsafe impl<T> TransparentWrapper<T> for core::num::Wrapping<T> {}
diff --git a/src/zeroable.rs b/src/zeroable.rs
new file mode 100644
index 0000000..5f19b98
--- /dev/null
+++ b/src/zeroable.rs
@@ -0,0 +1,235 @@
+use super::*;
+
+/// Trait for types that can be safely created with
+/// [`zeroed`](core::mem::zeroed).
+///
+/// An all-zeroes value may or may not be the same value as the
+/// [Default](core::default::Default) value of the type.
+///
+/// ## Safety
+///
+/// * Your type must be inhabited (eg: no
+/// [Infallible](core::convert::Infallible)).
+/// * Your type must be allowed to be an "all zeroes" bit pattern (eg: no
+/// [`NonNull<T>`](core::ptr::NonNull)).
+///
+/// ## Features
+///
+/// Some `impl`s are feature gated due to the MSRV policy:
+///
+/// * `MaybeUninit<T>` was not available in 1.34.0, but is available under the
+/// `zeroable_maybe_uninit` feature flag.
+/// * `Atomic*` types require Rust 1.60.0 or later to work on certain platforms, but is available
+/// under the `zeroable_atomics` feature flag.
+/// * `[T; N]` for arbitrary `N` requires the `min_const_generics` feature flag.
+pub unsafe trait Zeroable: Sized {
+ /// Calls [`zeroed`](core::mem::zeroed).
+ ///
+ /// This is a trait method so that you can write `MyType::zeroed()` in your
+ /// code. It is a contract of this trait that if you implement it on your type
+ /// you **must not** override this method.
+ #[inline]
+ fn zeroed() -> Self {
+ unsafe { core::mem::zeroed() }
+ }
+}
+unsafe impl Zeroable for () {}
+unsafe impl Zeroable for bool {}
+unsafe impl Zeroable for char {}
+unsafe impl Zeroable for u8 {}
+unsafe impl Zeroable for i8 {}
+unsafe impl Zeroable for u16 {}
+unsafe impl Zeroable for i16 {}
+unsafe impl Zeroable for u32 {}
+unsafe impl Zeroable for i32 {}
+unsafe impl Zeroable for u64 {}
+unsafe impl Zeroable for i64 {}
+unsafe impl Zeroable for usize {}
+unsafe impl Zeroable for isize {}
+unsafe impl Zeroable for u128 {}
+unsafe impl Zeroable for i128 {}
+unsafe impl Zeroable for f32 {}
+unsafe impl Zeroable for f64 {}
+unsafe impl<T: Zeroable> Zeroable for Wrapping<T> {}
+unsafe impl<T: Zeroable> Zeroable for core::cmp::Reverse<T> {}
+
+// Note: we can't implement this for all `T: ?Sized` types because it would
+// create NULL pointers for vtables.
+// Maybe one day this could be changed to be implemented for
+// `T: ?Sized where <T as core::ptr::Pointee>::Metadata: Zeroable`.
+unsafe impl<T> Zeroable for *mut T {}
+unsafe impl<T> Zeroable for *const T {}
+unsafe impl<T> Zeroable for *mut [T] {}
+unsafe impl<T> Zeroable for *const [T] {}
+unsafe impl Zeroable for *mut str {}
+unsafe impl Zeroable for *const str {}
+
+unsafe impl<T: ?Sized> Zeroable for PhantomData<T> {}
+unsafe impl Zeroable for PhantomPinned {}
+unsafe impl<T: Zeroable> Zeroable for ManuallyDrop<T> {}
+unsafe impl<T: Zeroable> Zeroable for core::cell::UnsafeCell<T> {}
+unsafe impl<T: Zeroable> Zeroable for core::cell::Cell<T> {}
+
+#[cfg(feature = "zeroable_atomics")]
+mod atomic_impls {
+ use super::Zeroable;
+
+ #[cfg(target_has_atomic = "8")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicBool {}
+ #[cfg(target_has_atomic = "8")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicU8 {}
+ #[cfg(target_has_atomic = "8")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicI8 {}
+
+ #[cfg(target_has_atomic = "16")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicU16 {}
+ #[cfg(target_has_atomic = "16")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicI16 {}
+
+ #[cfg(target_has_atomic = "32")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicU32 {}
+ #[cfg(target_has_atomic = "32")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicI32 {}
+
+ #[cfg(target_has_atomic = "64")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicU64 {}
+ #[cfg(target_has_atomic = "64")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicI64 {}
+
+ #[cfg(target_has_atomic = "ptr")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicUsize {}
+ #[cfg(target_has_atomic = "ptr")]
+ unsafe impl Zeroable for core::sync::atomic::AtomicIsize {}
+
+ #[cfg(target_has_atomic = "ptr")]
+ unsafe impl<T> Zeroable for core::sync::atomic::AtomicPtr<T> {}
+}
+
+#[cfg(feature = "zeroable_maybe_uninit")]
+unsafe impl<T> Zeroable for core::mem::MaybeUninit<T> {}
+
+unsafe impl<A: Zeroable> Zeroable for (A,) {}
+unsafe impl<A: Zeroable, B: Zeroable> Zeroable for (A, B) {}
+unsafe impl<A: Zeroable, B: Zeroable, C: Zeroable> Zeroable for (A, B, C) {}
+unsafe impl<A: Zeroable, B: Zeroable, C: Zeroable, D: Zeroable> Zeroable
+ for (A, B, C, D)
+{
+}
+unsafe impl<A: Zeroable, B: Zeroable, C: Zeroable, D: Zeroable, E: Zeroable>
+ Zeroable for (A, B, C, D, E)
+{
+}
+unsafe impl<
+ A: Zeroable,
+ B: Zeroable,
+ C: Zeroable,
+ D: Zeroable,
+ E: Zeroable,
+ F: Zeroable,
+ > Zeroable for (A, B, C, D, E, F)
+{
+}
+unsafe impl<
+ A: Zeroable,
+ B: Zeroable,
+ C: Zeroable,
+ D: Zeroable,
+ E: Zeroable,
+ F: Zeroable,
+ G: Zeroable,
+ > Zeroable for (A, B, C, D, E, F, G)
+{
+}
+unsafe impl<
+ A: Zeroable,
+ B: Zeroable,
+ C: Zeroable,
+ D: Zeroable,
+ E: Zeroable,
+ F: Zeroable,
+ G: Zeroable,
+ H: Zeroable,
+ > Zeroable for (A, B, C, D, E, F, G, H)
+{
+}
+
+#[cfg(feature = "min_const_generics")]
+unsafe impl<T, const N: usize> Zeroable for [T; N] where T: Zeroable {}
+
+#[cfg(not(feature = "min_const_generics"))]
+impl_unsafe_marker_for_array!(
+ Zeroable, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
+ 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 48, 64, 96, 128, 256,
+ 512, 1024, 2048, 4096
+);
+
+#[cfg(all(target_arch = "wasm32", feature = "wasm_simd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for wasm32::{v128}
+);
+
+#[cfg(all(target_arch = "aarch64", feature = "aarch64_simd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for aarch64::{
+ float32x2_t, float32x2x2_t, float32x2x3_t, float32x2x4_t, float32x4_t,
+ float32x4x2_t, float32x4x3_t, float32x4x4_t, float64x1_t, float64x1x2_t,
+ float64x1x3_t, float64x1x4_t, float64x2_t, float64x2x2_t, float64x2x3_t,
+ float64x2x4_t, int16x4_t, int16x4x2_t, int16x4x3_t, int16x4x4_t, int16x8_t,
+ int16x8x2_t, int16x8x3_t, int16x8x4_t, int32x2_t, int32x2x2_t, int32x2x3_t,
+ int32x2x4_t, int32x4_t, int32x4x2_t, int32x4x3_t, int32x4x4_t, int64x1_t,
+ int64x1x2_t, int64x1x3_t, int64x1x4_t, int64x2_t, int64x2x2_t, int64x2x3_t,
+ int64x2x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int8x8_t,
+ int8x8x2_t, int8x8x3_t, int8x8x4_t, poly16x4_t, poly16x4x2_t, poly16x4x3_t,
+ poly16x4x4_t, poly16x8_t, poly16x8x2_t, poly16x8x3_t, poly16x8x4_t,
+ poly64x1_t, poly64x1x2_t, poly64x1x3_t, poly64x1x4_t, poly64x2_t,
+ poly64x2x2_t, poly64x2x3_t, poly64x2x4_t, poly8x16_t, poly8x16x2_t,
+ poly8x16x3_t, poly8x16x4_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t, poly8x8x4_t,
+ uint16x4_t, uint16x4x2_t, uint16x4x3_t, uint16x4x4_t, uint16x8_t,
+ uint16x8x2_t, uint16x8x3_t, uint16x8x4_t, uint32x2_t, uint32x2x2_t,
+ uint32x2x3_t, uint32x2x4_t, uint32x4_t, uint32x4x2_t, uint32x4x3_t,
+ uint32x4x4_t, uint64x1_t, uint64x1x2_t, uint64x1x3_t, uint64x1x4_t,
+ uint64x2_t, uint64x2x2_t, uint64x2x3_t, uint64x2x4_t, uint8x16_t,
+ uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint8x8_t, uint8x8x2_t,
+ uint8x8x3_t, uint8x8x4_t,
+ }
+);
+
+#[cfg(target_arch = "x86")]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for x86::{
+ __m128i, __m128, __m128d,
+ __m256i, __m256, __m256d,
+ }
+);
+
+#[cfg(target_arch = "x86_64")]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for x86_64::{
+ __m128i, __m128, __m128d,
+ __m256i, __m256, __m256d,
+ }
+);
+
+#[cfg(feature = "nightly_portable_simd")]
+unsafe impl<T, const N: usize> Zeroable for core::simd::Simd<T, N>
+where
+ T: core::simd::SimdElement + Zeroable,
+ core::simd::LaneCount<N>: core::simd::SupportedLaneCount,
+{
+}
+
+#[cfg(all(target_arch = "x86", feature = "nightly_stdsimd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for x86::{
+ __m128bh, __m256bh, __m512,
+ __m512bh, __m512d, __m512i,
+ }
+);
+
+#[cfg(all(target_arch = "x86_64", feature = "nightly_stdsimd"))]
+impl_unsafe_marker_for_simd!(
+ unsafe impl Zeroable for x86_64::{
+ __m128bh, __m256bh, __m512,
+ __m512bh, __m512d, __m512i,
+ }
+);
diff --git a/src/zeroable_in_option.rs b/src/zeroable_in_option.rs
new file mode 100644
index 0000000..1ee2c7b
--- /dev/null
+++ b/src/zeroable_in_option.rs
@@ -0,0 +1,34 @@
+use super::*;
+
+// Note(Lokathor): This is the neat part!!
+unsafe impl<T: ZeroableInOption> Zeroable for Option<T> {}
+
+/// Trait for types which are [Zeroable](Zeroable) when wrapped in
+/// [Option](core::option::Option).
+///
+/// ## Safety
+///
+/// * `Option<YourType>` must uphold the same invariants as
+/// [Zeroable](Zeroable).
+pub unsafe trait ZeroableInOption: Sized {}
+
+unsafe impl ZeroableInOption for NonZeroI8 {}
+unsafe impl ZeroableInOption for NonZeroI16 {}
+unsafe impl ZeroableInOption for NonZeroI32 {}
+unsafe impl ZeroableInOption for NonZeroI64 {}
+unsafe impl ZeroableInOption for NonZeroI128 {}
+unsafe impl ZeroableInOption for NonZeroIsize {}
+unsafe impl ZeroableInOption for NonZeroU8 {}
+unsafe impl ZeroableInOption for NonZeroU16 {}
+unsafe impl ZeroableInOption for NonZeroU32 {}
+unsafe impl ZeroableInOption for NonZeroU64 {}
+unsafe impl ZeroableInOption for NonZeroU128 {}
+unsafe impl ZeroableInOption for NonZeroUsize {}
+
+// Note: this does not create NULL vtable because we get `None` anyway.
+unsafe impl<T: ?Sized> ZeroableInOption for NonNull<T> {}
+unsafe impl<T: ?Sized> ZeroableInOption for &'_ T {}
+unsafe impl<T: ?Sized> ZeroableInOption for &'_ mut T {}
+
+#[cfg(feature = "extern_crate_alloc")]
+unsafe impl<T: ?Sized> ZeroableInOption for alloc::boxed::Box<T> {}
diff --git a/tests/array_tests.rs b/tests/array_tests.rs
new file mode 100644
index 0000000..552de08
--- /dev/null
+++ b/tests/array_tests.rs
@@ -0,0 +1,12 @@
+#[test]
+pub fn test_cast_array() {
+ let x = [0u32, 1u32, 2u32];
+ let _: [u16; 6] = bytemuck::cast(x);
+}
+
+#[cfg(feature = "min_const_generics")]
+#[test]
+pub fn test_cast_long_array() {
+ let x = [0u32; 65];
+ let _: [u16; 130] = bytemuck::cast(x);
+}
diff --git a/tests/cast_slice_tests.rs b/tests/cast_slice_tests.rs
new file mode 100644
index 0000000..2838d46
--- /dev/null
+++ b/tests/cast_slice_tests.rs
@@ -0,0 +1,194 @@
+use core::mem::size_of;
+
+use bytemuck::*;
+
+#[test]
+fn test_try_cast_slice() {
+ // some align4 data
+ let u32_slice: &[u32] = &[4, 5, 6];
+ // the same data as align1
+ let the_bytes: &[u8] = try_cast_slice(u32_slice).unwrap();
+
+ assert_eq!(
+ u32_slice.as_ptr() as *const u32 as usize,
+ the_bytes.as_ptr() as *const u8 as usize
+ );
+ assert_eq!(
+ u32_slice.len() * size_of::<u32>(),
+ the_bytes.len() * size_of::<u8>()
+ );
+
+ // by taking one byte off the front, we're definitely mis-aligned for u32.
+ let mis_aligned_bytes = &the_bytes[1..];
+ assert_eq!(
+ try_cast_slice::<u8, u32>(mis_aligned_bytes),
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ );
+
+ // by taking one byte off the end, we're aligned but would have slop bytes for
+ // u32
+ let the_bytes_len_minus1 = the_bytes.len() - 1;
+ let slop_bytes = &the_bytes[..the_bytes_len_minus1];
+ assert_eq!(
+ try_cast_slice::<u8, u32>(slop_bytes),
+ Err(PodCastError::OutputSliceWouldHaveSlop)
+ );
+
+ // if we don't mess with it we can up-alignment cast
+ try_cast_slice::<u8, u32>(the_bytes).unwrap();
+}
+
+#[test]
+fn test_try_cast_slice_mut() {
+ // some align4 data
+ let u32_slice: &mut [u32] = &mut [4, 5, 6];
+ let u32_len = u32_slice.len();
+ let u32_ptr = u32_slice.as_ptr();
+
+ // the same data as align1
+ let the_bytes: &mut [u8] = try_cast_slice_mut(u32_slice).unwrap();
+ let the_bytes_len = the_bytes.len();
+ let the_bytes_ptr = the_bytes.as_ptr();
+
+ assert_eq!(
+ u32_ptr as *const u32 as usize,
+ the_bytes_ptr as *const u8 as usize
+ );
+ assert_eq!(u32_len * size_of::<u32>(), the_bytes_len * size_of::<u8>());
+
+ // by taking one byte off the front, we're definitely mis-aligned for u32.
+ let mis_aligned_bytes = &mut the_bytes[1..];
+ assert_eq!(
+ try_cast_slice_mut::<u8, u32>(mis_aligned_bytes),
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ );
+
+ // by taking one byte off the end, we're aligned but would have slop bytes for
+ // u32
+ let the_bytes_len_minus1 = the_bytes.len() - 1;
+ let slop_bytes = &mut the_bytes[..the_bytes_len_minus1];
+ assert_eq!(
+ try_cast_slice_mut::<u8, u32>(slop_bytes),
+ Err(PodCastError::OutputSliceWouldHaveSlop)
+ );
+
+ // if we don't mess with it we can up-alignment cast
+ try_cast_slice_mut::<u8, u32>(the_bytes).unwrap();
+}
+
+#[test]
+fn test_types() {
+ let _: i32 = cast(1.0_f32);
+ let _: &mut i32 = cast_mut(&mut 1.0_f32);
+ let _: &i32 = cast_ref(&1.0_f32);
+ let _: &[i32] = cast_slice(&[1.0_f32]);
+ let _: &mut [i32] = cast_slice_mut(&mut [1.0_f32]);
+ //
+ let _: Result<i32, PodCastError> = try_cast(1.0_f32);
+ let _: Result<&mut i32, PodCastError> = try_cast_mut(&mut 1.0_f32);
+ let _: Result<&i32, PodCastError> = try_cast_ref(&1.0_f32);
+ let _: Result<&[i32], PodCastError> = try_cast_slice(&[1.0_f32]);
+ let _: Result<&mut [i32], PodCastError> = try_cast_slice_mut(&mut [1.0_f32]);
+}
+
+#[test]
+fn test_bytes_of() {
+ assert_eq!(bytes_of(&0xaabbccdd_u32), &0xaabbccdd_u32.to_ne_bytes());
+ assert_eq!(
+ bytes_of_mut(&mut 0xaabbccdd_u32),
+ &mut 0xaabbccdd_u32.to_ne_bytes()
+ );
+ let mut a = 0xaabbccdd_u32;
+ let a_addr = &a as *const _ as usize;
+ // ensure addresses match.
+ assert_eq!(bytes_of(&a).as_ptr() as usize, a_addr);
+ assert_eq!(bytes_of_mut(&mut a).as_ptr() as usize, a_addr);
+}
+
+#[test]
+fn test_try_from_bytes() {
+ let u32s = [0xaabbccdd, 0x11223344_u32];
+ let bytes = bytemuck::cast_slice::<u32, u8>(&u32s);
+ assert_eq!(try_from_bytes::<u32>(&bytes[..4]), Ok(&u32s[0]));
+ assert_eq!(
+ try_from_bytes::<u32>(&bytes[..5]),
+ Err(PodCastError::SizeMismatch)
+ );
+ assert_eq!(
+ try_from_bytes::<u32>(&bytes[..3]),
+ Err(PodCastError::SizeMismatch)
+ );
+ assert_eq!(
+ try_from_bytes::<u32>(&bytes[1..5]),
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ );
+}
+
+#[test]
+fn test_try_from_bytes_mut() {
+ let mut abcd = 0xaabbccdd;
+ let mut u32s = [abcd, 0x11223344_u32];
+ let bytes = bytemuck::cast_slice_mut::<u32, u8>(&mut u32s);
+ assert_eq!(try_from_bytes_mut::<u32>(&mut bytes[..4]), Ok(&mut abcd));
+ assert_eq!(try_from_bytes_mut::<u32>(&mut bytes[..4]), Ok(&mut abcd));
+ assert_eq!(
+ try_from_bytes_mut::<u32>(&mut bytes[..5]),
+ Err(PodCastError::SizeMismatch)
+ );
+ assert_eq!(
+ try_from_bytes_mut::<u32>(&mut bytes[..3]),
+ Err(PodCastError::SizeMismatch)
+ );
+ assert_eq!(
+ try_from_bytes::<u32>(&bytes[1..5]),
+ Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
+ );
+}
+
+#[test]
+fn test_from_bytes() {
+ let abcd = 0xaabbccdd_u32;
+ let aligned_bytes = bytemuck::bytes_of(&abcd);
+ assert_eq!(from_bytes::<u32>(aligned_bytes), &abcd);
+ assert!(core::ptr::eq(from_bytes(aligned_bytes), &abcd));
+}
+
+#[test]
+fn test_from_bytes_mut() {
+ let mut a = 0xaabbccdd_u32;
+ let a_addr = &a as *const _ as usize;
+ let aligned_bytes = bytemuck::bytes_of_mut(&mut a);
+ assert_eq!(*from_bytes_mut::<u32>(aligned_bytes), 0xaabbccdd_u32);
+ assert_eq!(
+ from_bytes_mut::<u32>(aligned_bytes) as *const u32 as usize,
+ a_addr
+ );
+}
+
+// like #[should_panic], but can be a part of another test, instead of requiring
+// it to be it's own test.
+macro_rules! should_panic {
+ ($ex:expr) => {
+ assert!(
+ std::panic::catch_unwind(|| {
+ let _ = $ex;
+ })
+ .is_err(),
+ concat!("should have panicked: `", stringify!($ex), "`")
+ );
+ };
+}
+
+#[test]
+fn test_panics() {
+ should_panic!(cast_slice::<u8, u32>(&[1u8, 2u8]));
+ should_panic!(cast_slice_mut::<u8, u32>(&mut [1u8, 2u8]));
+ should_panic!(from_bytes::<u32>(&[1u8, 2]));
+ should_panic!(from_bytes::<u32>(&[1u8, 2, 3, 4, 5]));
+ should_panic!(from_bytes_mut::<u32>(&mut [1u8, 2]));
+ should_panic!(from_bytes_mut::<u32>(&mut [1u8, 2, 3, 4, 5]));
+ // use cast_slice on some u32s to get some align>=4 bytes, so we can know
+ // we'll give from_bytes unaligned ones.
+ let aligned_bytes = bytemuck::cast_slice::<u32, u8>(&[0, 0]);
+ should_panic!(from_bytes::<u32>(&aligned_bytes[1..5]));
+}
diff --git a/tests/checked_tests.rs b/tests/checked_tests.rs
new file mode 100644
index 0000000..19e6348
--- /dev/null
+++ b/tests/checked_tests.rs
@@ -0,0 +1,416 @@
+use core::{
+ mem::size_of,
+ num::{NonZeroU32, NonZeroU8},
+};
+
+use bytemuck::{checked::CheckedCastError, *};
+
+#[test]
+fn test_try_cast_slice() {
+ // some align4 data
+ let nonzero_u32_slice: &[NonZeroU32] = &[
+ NonZeroU32::new(4).unwrap(),
+ NonZeroU32::new(5).unwrap(),
+ NonZeroU32::new(6).unwrap(),
+ ];
+
+ // contains bytes with invalid bitpattern for NonZeroU8
+ assert_eq!(
+ checked::try_cast_slice::<NonZeroU32, NonZeroU8>(nonzero_u32_slice),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+
+ // the same data as align1
+ let the_bytes: &[u8] = checked::try_cast_slice(nonzero_u32_slice).unwrap();
+
+ assert_eq!(
+ nonzero_u32_slice.as_ptr() as *const NonZeroU32 as usize,
+ the_bytes.as_ptr() as *const u8 as usize
+ );
+ assert_eq!(
+ nonzero_u32_slice.len() * size_of::<NonZeroU32>(),
+ the_bytes.len() * size_of::<u8>()
+ );
+
+ // by taking one byte off the front, we're definitely mis-aligned for
+ // NonZeroU32.
+ let mis_aligned_bytes = &the_bytes[1..];
+ assert_eq!(
+ checked::try_cast_slice::<u8, NonZeroU32>(mis_aligned_bytes),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+
+ // by taking one byte off the end, we're aligned but would have slop bytes for
+ // NonZeroU32
+ let the_bytes_len_minus1 = the_bytes.len() - 1;
+ let slop_bytes = &the_bytes[..the_bytes_len_minus1];
+ assert_eq!(
+ checked::try_cast_slice::<u8, NonZeroU32>(slop_bytes),
+ Err(CheckedCastError::PodCastError(PodCastError::OutputSliceWouldHaveSlop))
+ );
+
+ // if we don't mess with it we can up-alignment cast
+ checked::try_cast_slice::<u8, NonZeroU32>(the_bytes).unwrap();
+}
+
+#[test]
+fn test_try_cast_slice_mut() {
+ // some align4 data
+ let u32_slice: &mut [u32] = &mut [4, 5, 6];
+
+ // contains bytes with invalid bitpattern for NonZeroU8
+ assert_eq!(
+ checked::try_cast_slice_mut::<u32, NonZeroU8>(u32_slice),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+
+ // some align4 data
+ let u32_slice: &mut [u32] = &mut [0x4444_4444, 0x5555_5555, 0x6666_6666];
+ let u32_len = u32_slice.len();
+ let u32_ptr = u32_slice.as_ptr();
+
+ // the same data as align1, nonzero bytes
+ let the_nonzero_bytes: &mut [NonZeroU8] =
+ checked::try_cast_slice_mut(u32_slice).unwrap();
+ let the_nonzero_bytes_len = the_nonzero_bytes.len();
+ let the_nonzero_bytes_ptr = the_nonzero_bytes.as_ptr();
+
+ assert_eq!(
+ u32_ptr as *const u32 as usize,
+ the_nonzero_bytes_ptr as *const NonZeroU8 as usize
+ );
+ assert_eq!(
+ u32_len * size_of::<u32>(),
+ the_nonzero_bytes_len * size_of::<NonZeroU8>()
+ );
+
+ // the same data as align1
+ let the_bytes: &mut [u8] = checked::try_cast_slice_mut(u32_slice).unwrap();
+ let the_bytes_len = the_bytes.len();
+ let the_bytes_ptr = the_bytes.as_ptr();
+
+ assert_eq!(
+ u32_ptr as *const u32 as usize,
+ the_bytes_ptr as *const u8 as usize
+ );
+ assert_eq!(
+ u32_len * size_of::<u32>(),
+ the_bytes_len * size_of::<NonZeroU8>()
+ );
+
+ // by taking one byte off the front, we're definitely mis-aligned for u32.
+ let mis_aligned_bytes = &mut the_bytes[1..];
+ assert_eq!(
+ checked::try_cast_slice_mut::<u8, NonZeroU32>(mis_aligned_bytes),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+
+ // by taking one byte off the end, we're aligned but would have slop bytes for
+ // NonZeroU32
+ let the_bytes_len_minus1 = the_bytes.len() - 1;
+ let slop_bytes = &mut the_bytes[..the_bytes_len_minus1];
+ assert_eq!(
+ checked::try_cast_slice_mut::<u8, NonZeroU32>(slop_bytes),
+ Err(CheckedCastError::PodCastError(PodCastError::OutputSliceWouldHaveSlop))
+ );
+
+ // if we don't mess with it we can up-alignment cast, since there are no
+ // zeroes in the original slice
+ checked::try_cast_slice_mut::<u8, NonZeroU32>(the_bytes).unwrap();
+}
+
+#[test]
+fn test_types() {
+ let _: NonZeroU32 = checked::cast(1.0_f32);
+ let _: &mut NonZeroU32 = checked::cast_mut(&mut 1.0_f32);
+ let _: &NonZeroU32 = checked::cast_ref(&1.0_f32);
+ let _: &[NonZeroU32] = checked::cast_slice(&[1.0_f32]);
+ let _: &mut [NonZeroU32] = checked::cast_slice_mut(&mut [1.0_f32]);
+ //
+ let _: Result<NonZeroU32, CheckedCastError> = checked::try_cast(1.0_f32);
+ let _: Result<&mut NonZeroU32, CheckedCastError> =
+ checked::try_cast_mut(&mut 1.0_f32);
+ let _: Result<&NonZeroU32, CheckedCastError> =
+ checked::try_cast_ref(&1.0_f32);
+ let _: Result<&[NonZeroU32], CheckedCastError> =
+ checked::try_cast_slice(&[1.0_f32]);
+ let _: Result<&mut [NonZeroU32], CheckedCastError> =
+ checked::try_cast_slice_mut(&mut [1.0_f32]);
+}
+
+#[test]
+fn test_try_pod_read_unaligned() {
+ let u32s = [0xaabbccdd, 0x11223344_u32];
+ let bytes = bytemuck::checked::cast_slice::<u32, u8>(&u32s);
+
+ #[cfg(target_endian = "big")]
+ assert_eq!(
+ checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
+ Ok(NonZeroU32::new(0xbbccdd11).unwrap())
+ );
+ #[cfg(target_endian = "little")]
+ assert_eq!(
+ checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
+ Ok(NonZeroU32::new(0x44aabbcc).unwrap())
+ );
+
+ let u32s = [0; 2];
+ let bytes = bytemuck::checked::cast_slice::<u32, u8>(&u32s);
+
+ assert_eq!(
+ checked::try_pod_read_unaligned::<NonZeroU32>(&bytes[1..5]),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+}
+
+#[test]
+fn test_try_from_bytes() {
+ let nonzero_u32s = [
+ NonZeroU32::new(0xaabbccdd).unwrap(),
+ NonZeroU32::new(0x11223344).unwrap(),
+ ];
+ let bytes = bytemuck::checked::cast_slice::<NonZeroU32, u8>(&nonzero_u32s);
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..4]),
+ Ok(&nonzero_u32s[0])
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..5]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..3]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+
+ let zero_u32s = [0, 0x11223344_u32];
+ let bytes = bytemuck::checked::cast_slice::<u32, u8>(&zero_u32s);
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..4]),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[4..]),
+ Ok(&NonZeroU32::new(zero_u32s[1]).unwrap())
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..5]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[..3]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+}
+
+#[test]
+fn test_try_from_bytes_mut() {
+ let a = 0xaabbccdd_u32;
+ let b = 0x11223344_u32;
+ let mut u32s = [a, b];
+ let bytes = bytemuck::checked::cast_slice_mut::<u32, u8>(&mut u32s);
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..4]),
+ Ok(&mut NonZeroU32::new(a).unwrap())
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[4..]),
+ Ok(&mut NonZeroU32::new(b).unwrap())
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..5]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..3]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+
+ let mut u32s = [0, b];
+ let bytes = bytemuck::checked::cast_slice_mut::<u32, u8>(&mut u32s);
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..4]),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[4..]),
+ Ok(&mut NonZeroU32::new(b).unwrap())
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..5]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes_mut::<NonZeroU32>(&mut bytes[..3]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+ assert_eq!(
+ checked::try_from_bytes::<NonZeroU32>(&bytes[1..5]),
+ Err(CheckedCastError::PodCastError(
+ PodCastError::TargetAlignmentGreaterAndInputNotAligned
+ ))
+ );
+}
+
+#[test]
+fn test_from_bytes() {
+ let abcd = 0xaabbccdd_u32;
+ let aligned_bytes = bytemuck::bytes_of(&abcd);
+ assert_eq!(
+ checked::from_bytes::<NonZeroU32>(aligned_bytes),
+ &NonZeroU32::new(abcd).unwrap()
+ );
+ assert!(core::ptr::eq(
+ checked::from_bytes(aligned_bytes) as *const NonZeroU32 as *const u32,
+ &abcd
+ ));
+}
+
+#[test]
+fn test_from_bytes_mut() {
+ let mut a = 0xaabbccdd_u32;
+ let a_addr = &a as *const _ as usize;
+ let aligned_bytes = bytemuck::bytes_of_mut(&mut a);
+ assert_eq!(
+ *checked::from_bytes_mut::<NonZeroU32>(aligned_bytes),
+ NonZeroU32::new(0xaabbccdd).unwrap()
+ );
+ assert_eq!(
+ checked::from_bytes_mut::<NonZeroU32>(aligned_bytes) as *const NonZeroU32
+ as usize,
+ a_addr
+ );
+}
+
+// like #[should_panic], but can be a part of another test, instead of requiring
+// it to be it's own test.
+macro_rules! should_panic {
+ ($ex:expr) => {
+ assert!(
+ std::panic::catch_unwind(|| {
+ let _ = $ex;
+ })
+ .is_err(),
+ concat!("should have panicked: `", stringify!($ex), "`")
+ );
+ };
+}
+
+#[test]
+fn test_panics() {
+ should_panic!(checked::cast::<u32, NonZeroU32>(0));
+ should_panic!(checked::cast_ref::<u32, NonZeroU32>(&0));
+ should_panic!(checked::cast_mut::<u32, NonZeroU32>(&mut 0));
+ should_panic!(checked::cast_slice::<u8, NonZeroU32>(&[1u8, 2u8]));
+ should_panic!(checked::cast_slice_mut::<u8, NonZeroU32>(&mut [1u8, 2u8]));
+ should_panic!(checked::from_bytes::<NonZeroU32>(&[1u8, 2]));
+ should_panic!(checked::from_bytes::<NonZeroU32>(&[1u8, 2, 3, 4, 5]));
+ should_panic!(checked::from_bytes_mut::<NonZeroU32>(&mut [1u8, 2]));
+ should_panic!(checked::from_bytes_mut::<NonZeroU32>(&mut [1u8, 2, 3, 4, 5]));
+ // use cast_slice on some u32s to get some align>=4 bytes, so we can know
+ // we'll give from_bytes unaligned ones.
+ let aligned_bytes = bytemuck::cast_slice::<u32, u8>(&[0, 0]);
+ should_panic!(checked::from_bytes::<NonZeroU32>(aligned_bytes));
+ should_panic!(checked::from_bytes::<NonZeroU32>(&aligned_bytes[1..5]));
+ should_panic!(checked::pod_read_unaligned::<NonZeroU32>(
+ &aligned_bytes[1..5]
+ ));
+}
+
+#[test]
+fn test_char() {
+ assert_eq!(checked::try_cast::<u32, char>(0), Ok('\0'));
+ assert_eq!(checked::try_cast::<u32, char>(0xd7ff), Ok('\u{d7ff}'));
+ assert_eq!(
+ checked::try_cast::<u32, char>(0xd800),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_cast::<u32, char>(0xdfff),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(checked::try_cast::<u32, char>(0xe000), Ok('\u{e000}'));
+ assert_eq!(checked::try_cast::<u32, char>(0x10ffff), Ok('\u{10ffff}'));
+ assert_eq!(
+ checked::try_cast::<u32, char>(0x110000),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_cast::<u32, char>(-1i32 as u32),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+}
+
+#[test]
+fn test_bool() {
+ assert_eq!(checked::try_cast::<u8, bool>(0), Ok(false));
+ assert_eq!(checked::try_cast::<u8, bool>(1), Ok(true));
+ for i in 2..=255 {
+ assert_eq!(
+ checked::try_cast::<u8, bool>(i),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ }
+
+ assert_eq!(checked::try_from_bytes::<bool>(&[1]), Ok(&true));
+ assert_eq!(
+ checked::try_from_bytes::<bool>(&[3]),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_from_bytes::<bool>(&[0, 1]),
+ Err(CheckedCastError::PodCastError(PodCastError::SizeMismatch))
+ );
+}
+
+#[test]
+fn test_all_nonzero() {
+ use core::num::*;
+ macro_rules! test_nonzero {
+ ($nonzero:ty: $primitive:ty) => {
+ assert_eq!(
+ checked::try_cast::<$primitive, $nonzero>(0),
+ Err(CheckedCastError::InvalidBitPattern)
+ );
+ assert_eq!(
+ checked::try_cast::<$primitive, $nonzero>(1),
+ Ok(<$nonzero>::new(1).unwrap())
+ );
+ };
+ }
+
+ test_nonzero!(NonZeroU8: u8);
+ test_nonzero!(NonZeroI8: i8);
+ test_nonzero!(NonZeroU16: u16);
+ test_nonzero!(NonZeroI16: i16);
+ test_nonzero!(NonZeroU32: u32);
+ test_nonzero!(NonZeroI32: i32);
+ test_nonzero!(NonZeroU64: u64);
+ test_nonzero!(NonZeroI64: i64);
+ test_nonzero!(NonZeroU128: u128);
+ test_nonzero!(NonZeroI128: i128);
+ test_nonzero!(NonZeroUsize: usize);
+ test_nonzero!(NonZeroIsize: isize);
+}
diff --git a/tests/derive.rs b/tests/derive.rs
new file mode 100644
index 0000000..c7da6cc
--- /dev/null
+++ b/tests/derive.rs
@@ -0,0 +1,77 @@
+#![cfg(feature = "derive")]
+#![allow(dead_code)]
+
+use bytemuck::{ByteEq, ByteHash, Pod, TransparentWrapper, Zeroable};
+use std::marker::PhantomData;
+
+#[derive(Copy, Clone, Pod, Zeroable, ByteEq, ByteHash)]
+#[repr(C)]
+struct Test {
+ a: u16,
+ b: u16,
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+struct TransparentSingle {
+ a: u16,
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+#[transparent(u16)]
+struct TransparentWithZeroSized {
+ a: u16,
+ b: (),
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+struct TransparentWithGeneric<T: ?Sized> {
+ a: T,
+}
+
+/// Ensuring that no additional bounds are emitted.
+/// See https://github.com/Lokathor/bytemuck/issues/145
+fn test_generic<T>(x: T) -> TransparentWithGeneric<T> {
+ TransparentWithGeneric::wrap(x)
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+#[transparent(T)]
+struct TransparentWithGenericAndZeroSized<T: ?Sized> {
+ a: (),
+ b: T,
+}
+
+/// Ensuring that no additional bounds are emitted.
+/// See https://github.com/Lokathor/bytemuck/issues/145
+fn test_generic_with_zst<T>(x: T) -> TransparentWithGenericAndZeroSized<T> {
+ TransparentWithGenericAndZeroSized::wrap(x)
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+struct TransparentUnsized {
+ a: dyn std::fmt::Debug,
+}
+
+type DynDebug = dyn std::fmt::Debug;
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+#[transparent(DynDebug)]
+struct TransparentUnsizedWithZeroSized {
+ a: (),
+ b: DynDebug,
+}
+
+#[derive(TransparentWrapper)]
+#[repr(transparent)]
+#[transparent(DynDebug)]
+struct TransparentUnsizedWithGenericZeroSizeds<T: ?Sized, U: ?Sized> {
+ a: PhantomData<T>,
+ b: PhantomData<U>,
+ c: DynDebug,
+}
diff --git a/tests/doc_tests.rs b/tests/doc_tests.rs
new file mode 100644
index 0000000..cafef98
--- /dev/null
+++ b/tests/doc_tests.rs
@@ -0,0 +1,123 @@
+#![allow(clippy::disallowed_names)]
+
+//! Cargo miri doesn't run doctests yet, so we duplicate these here. It's
+//! probably not that important to sweat keeping these perfectly up to date, but
+//! we should try to catch the cases where the primary tests are doctests.
+use bytemuck::*;
+
+// Miri doesn't run on doctests, so... copypaste to the rescue.
+#[test]
+fn test_transparent_slice() {
+ #[repr(transparent)]
+ struct Slice<T>([T]);
+
+ unsafe impl<T> TransparentWrapper<[T]> for Slice<T> {}
+
+ let s = Slice::wrap_ref(&[1u32, 2, 3]);
+ assert_eq!(&s.0, &[1, 2, 3]);
+
+ let mut buf = [1, 2, 3u8];
+ let _sm = Slice::wrap_mut(&mut buf);
+}
+
+#[test]
+fn test_transparent_basic() {
+ #[derive(Default)]
+ struct SomeStruct(u32);
+
+ #[repr(transparent)]
+ struct MyWrapper(SomeStruct);
+
+ unsafe impl TransparentWrapper<SomeStruct> for MyWrapper {}
+
+ // interpret a reference to &SomeStruct as a &MyWrapper
+ let thing = SomeStruct::default();
+ let wrapped_ref: &MyWrapper = MyWrapper::wrap_ref(&thing);
+
+ // Works with &mut too.
+ let mut mut_thing = SomeStruct::default();
+ let wrapped_mut: &mut MyWrapper = MyWrapper::wrap_mut(&mut mut_thing);
+ let _ = (wrapped_ref, wrapped_mut);
+}
+
+// Work around miri not running doctests
+#[test]
+fn test_contiguous_doc() {
+ #[repr(u8)]
+ #[derive(Debug, Copy, Clone, PartialEq)]
+ enum Foo {
+ A = 0,
+ B = 1,
+ C = 2,
+ D = 3,
+ E = 4,
+ }
+ unsafe impl Contiguous for Foo {
+ type Int = u8;
+ const MIN_VALUE: u8 = Foo::A as u8;
+ const MAX_VALUE: u8 = Foo::E as u8;
+ }
+
+ assert_eq!(Foo::from_integer(3).unwrap(), Foo::D);
+ assert_eq!(Foo::from_integer(8), None);
+ assert_eq!(Foo::C.into_integer(), 2);
+ assert_eq!(Foo::B.into_integer(), Foo::B as u8);
+}
+
+#[test]
+fn test_offsetof_vertex() {
+ #[repr(C)]
+ struct Vertex {
+ pos: [f32; 2],
+ uv: [u16; 2],
+ color: [u8; 4],
+ }
+ unsafe impl Zeroable for Vertex {}
+
+ let pos = offset_of!(Zeroable::zeroed(), Vertex, pos);
+ let uv = offset_of!(Zeroable::zeroed(), Vertex, uv);
+ let color = offset_of!(Zeroable::zeroed(), Vertex, color);
+
+ assert_eq!(pos, 0);
+ assert_eq!(uv, 8);
+ assert_eq!(color, 12);
+}
+
+#[test]
+fn test_offsetof_nonpod() {
+ #[derive(Default)]
+ struct Foo {
+ a: u8,
+ b: &'static str,
+ c: i32,
+ }
+
+ let a_offset = offset_of!(Default::default(), Foo, a);
+ let b_offset = offset_of!(Default::default(), Foo, b);
+ let c_offset = offset_of!(Default::default(), Foo, c);
+
+ assert_ne!(a_offset, b_offset);
+ assert_ne!(b_offset, c_offset);
+ // We can't check against hardcoded values for a repr(Rust) type,
+ // but prove to ourself this way.
+
+ let foo = Foo::default();
+ // Note: offsets are in bytes.
+ let as_bytes = &foo as *const _ as *const u8;
+
+ // We're using wrapping_offset here because it's not worth
+ // the unsafe block, but it would be valid to use `add` instead,
+ // as it cannot overflow.
+ assert_eq!(
+ &foo.a as *const _ as usize,
+ as_bytes.wrapping_add(a_offset) as usize
+ );
+ assert_eq!(
+ &foo.b as *const _ as usize,
+ as_bytes.wrapping_add(b_offset) as usize
+ );
+ assert_eq!(
+ &foo.c as *const _ as usize,
+ as_bytes.wrapping_add(c_offset) as usize
+ );
+}
diff --git a/tests/offset_of_tests.rs b/tests/offset_of_tests.rs
new file mode 100644
index 0000000..b462237
--- /dev/null
+++ b/tests/offset_of_tests.rs
@@ -0,0 +1,60 @@
+#![allow(clippy::disallowed_names)]
+use bytemuck::{offset_of, Zeroable};
+
+#[test]
+fn test_offset_of_vertex() {
+ #[repr(C)]
+ struct Vertex {
+ pos: [f32; 2],
+ uv: [u16; 2],
+ color: [u8; 4],
+ }
+ unsafe impl Zeroable for Vertex {}
+
+ let pos = offset_of!(Zeroable::zeroed(), Vertex, pos);
+ let uv = offset_of!(Zeroable::zeroed(), Vertex, uv);
+ let color = offset_of!(Zeroable::zeroed(), Vertex, color);
+
+ assert_eq!(pos, 0);
+ assert_eq!(uv, 8);
+ assert_eq!(color, 12);
+}
+
+#[test]
+fn test_offset_of_foo() {
+ #[derive(Default)]
+ struct Foo {
+ a: u8,
+ b: &'static str,
+ c: i32,
+ }
+
+ let a_offset = offset_of!(Default::default(), Foo, a);
+ let b_offset = offset_of!(Default::default(), Foo, b);
+ let c_offset = offset_of!(Default::default(), Foo, c);
+
+ assert_ne!(a_offset, b_offset);
+ assert_ne!(b_offset, c_offset);
+ // We can't check against hardcoded values for a repr(Rust) type,
+ // but prove to ourself this way.
+
+ let foo = Foo::default();
+ // Note: offsets are in bytes.
+ let as_bytes = &foo as *const _ as *const u8;
+
+ // we're using wrapping_offset here because it's not worth
+ // the unsafe block, but it would be valid to use `add` instead,
+ // as it cannot overflow.
+ assert_eq!(
+ &foo.a as *const _ as usize,
+ as_bytes.wrapping_add(a_offset) as usize
+ );
+ assert_eq!(
+ &foo.b as *const _ as usize,
+ as_bytes.wrapping_add(b_offset) as usize
+ );
+ assert_eq!(
+ &foo.c as *const _ as usize,
+ as_bytes.wrapping_add(c_offset) as usize
+ );
+}
diff --git a/tests/std_tests.rs b/tests/std_tests.rs
new file mode 100644
index 0000000..79adcb5
--- /dev/null
+++ b/tests/std_tests.rs
@@ -0,0 +1,46 @@
+#![allow(clippy::uninlined_format_args)]
+//! The integration tests seem to always have `std` linked, so things that would
+//! depend on that can go here.
+
+use bytemuck::*;
+
+#[test]
+fn test_transparent_vtabled() {
+ use core::fmt::Display;
+
+ #[repr(transparent)]
+ struct DisplayTraitObj(dyn Display);
+
+ unsafe impl TransparentWrapper<dyn Display> for DisplayTraitObj {}
+
+ impl Display for DisplayTraitObj {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ self.0.fmt(f)
+ }
+ }
+
+ let v = DisplayTraitObj::wrap_ref(&5i32);
+ let s = format!("{}", v);
+ assert_eq!(s, "5");
+
+ let mut x = 100i32;
+ let v_mut = DisplayTraitObj::wrap_mut(&mut x);
+ let s = format!("{}", v_mut);
+ assert_eq!(s, "100");
+}
+
+#[test]
+#[cfg(feature = "extern_crate_alloc")]
+fn test_large_box_alloc() {
+ type SuperPage = [[u8; 4096]; 4096];
+ let _: Box<SuperPage> = try_zeroed_box().unwrap();
+}
+
+#[test]
+#[cfg(feature = "extern_crate_alloc")]
+fn test_zero_sized_box_alloc() {
+ #[repr(align(4096))]
+ struct Empty;
+ unsafe impl Zeroable for Empty {}
+ let _: Box<Empty> = try_zeroed_box().unwrap();
+}
diff --git a/tests/transparent.rs b/tests/transparent.rs
new file mode 100644
index 0000000..ad34d92
--- /dev/null
+++ b/tests/transparent.rs
@@ -0,0 +1,116 @@
+// Currently this test doesn't actually check the output of the functions.
+// It's only here for miri to check for any potential undefined behaviour.
+// TODO: check function results
+
+#[test]
+fn test_transparent_wrapper() {
+ // An external type defined in a different crate.
+ #[derive(Debug, Copy, Clone, Default)]
+ struct Foreign(u8);
+
+ use bytemuck::TransparentWrapper;
+
+ #[derive(Debug, Copy, Clone)]
+ #[repr(transparent)]
+ struct Wrapper(Foreign);
+
+ unsafe impl TransparentWrapper<Foreign> for Wrapper {}
+
+ // Traits can be implemented on crate-local wrapper.
+ unsafe impl bytemuck::Zeroable for Wrapper {}
+ unsafe impl bytemuck::Pod for Wrapper {}
+
+ impl PartialEq<u8> for Foreign {
+ fn eq(&self, &other: &u8) -> bool {
+ self.0 == other
+ }
+ }
+
+ impl PartialEq<u8> for Wrapper {
+ fn eq(&self, &other: &u8) -> bool {
+ self.0 == other
+ }
+ }
+
+ let _: u8 = bytemuck::cast(Wrapper::wrap(Foreign::default()));
+ let _: Foreign = Wrapper::peel(bytemuck::cast(u8::default()));
+
+ let _: &u8 = bytemuck::cast_ref(Wrapper::wrap_ref(&Foreign::default()));
+ let _: &Foreign = Wrapper::peel_ref(bytemuck::cast_ref(&u8::default()));
+
+ let _: &mut u8 =
+ bytemuck::cast_mut(Wrapper::wrap_mut(&mut Foreign::default()));
+ let _: &mut Foreign =
+ Wrapper::peel_mut(bytemuck::cast_mut(&mut u8::default()));
+
+ let _: &[u8] =
+ bytemuck::cast_slice(Wrapper::wrap_slice(&[Foreign::default()]));
+ let _: &[Foreign] =
+ Wrapper::peel_slice(bytemuck::cast_slice(&[u8::default()]));
+
+ let _: &mut [u8] =
+ bytemuck::cast_slice_mut(Wrapper::wrap_slice_mut(
+ &mut [Foreign::default()],
+ ));
+ let _: &mut [Foreign] =
+ Wrapper::peel_slice_mut(bytemuck::cast_slice_mut(&mut [u8::default()]));
+
+ let _: &[u8] = bytemuck::bytes_of(Wrapper::wrap_ref(&Foreign::default()));
+ let _: &Foreign = Wrapper::peel_ref(bytemuck::from_bytes(&[u8::default()]));
+
+ let _: &mut [u8] =
+ bytemuck::bytes_of_mut(Wrapper::wrap_mut(&mut Foreign::default()));
+ let _: &mut Foreign =
+ Wrapper::peel_mut(bytemuck::from_bytes_mut(&mut [u8::default()]));
+
+ // not sure if this is the right usage
+ let _ =
+ bytemuck::pod_align_to::<_, u8>(Wrapper::wrap_slice(&[Foreign::default()]));
+ // counterpart?
+
+ // not sure if this is the right usage
+ let _ = bytemuck::pod_align_to_mut::<_, u8>(Wrapper::wrap_slice_mut(&mut [
+ Foreign::default(),
+ ]));
+ // counterpart?
+
+ #[cfg(feature = "extern_crate_alloc")]
+ {
+ use bytemuck::allocation::TransparentWrapperAlloc;
+ use std::rc::Rc;
+
+ let a: Vec<Foreign> = vec![Foreign::default(); 2];
+
+ let b: Vec<Wrapper> = Wrapper::wrap_vec(a);
+ assert_eq!(b, [0, 0]);
+
+ let c: Vec<Foreign> = Wrapper::peel_vec(b);
+ assert_eq!(c, [0, 0]);
+
+ let d: Box<Foreign> = Box::new(Foreign::default());
+
+ let e: Box<Wrapper> = Wrapper::wrap_box(d);
+ assert_eq!(&*e, &0);
+ let f: Box<Foreign> = Wrapper::peel_box(e);
+ assert_eq!(&*f, &0);
+
+ let g: Rc<Foreign> = Rc::new(Foreign::default());
+
+ let h: Rc<Wrapper> = Wrapper::wrap_rc(g);
+ assert_eq!(&*h, &0);
+ let i: Rc<Foreign> = Wrapper::peel_rc(h);
+ assert_eq!(&*i, &0);
+
+ #[cfg(target_has_atomic = "ptr")]
+ {
+ use std::sync::Arc;
+
+ let j: Arc<Foreign> = Arc::new(Foreign::default());
+
+ let k: Arc<Wrapper> = Wrapper::wrap_arc(j);
+ assert_eq!(&*k, &0);
+ let l: Arc<Foreign> = Wrapper::peel_arc(k);
+ assert_eq!(&*l, &0);
+ }
+ }
+}
diff --git a/tests/wrapper_forgets.rs b/tests/wrapper_forgets.rs
new file mode 100644
index 0000000..da3404f
--- /dev/null
+++ b/tests/wrapper_forgets.rs
@@ -0,0 +1,13 @@
+use bytemuck::TransparentWrapper;
+
+#[repr(transparent)]
+struct Wrap(Box<u32>);
+
+// SAFETY: it's #[repr(transparent)]
+unsafe impl TransparentWrapper<Box<u32>> for Wrap {}
+
+fn main() {
+ let value = Box::new(5);
+ // This used to duplicate the wrapped value, creating a double free :(
+ Wrap::wrap(value);
+}