ref-cast-1.0.23/.cargo_vcs_info.json0000644000000001360000000000100126230ustar { "git": { "sha1": "06c520cd555920951cc1939fcb0c5d855b61134c" }, "path_in_vcs": "" }ref-cast-1.0.23/.github/FUNDING.yml000064400000000000000000000000201046102023000145600ustar 00000000000000github: dtolnay ref-cast-1.0.23/.github/workflows/ci.yml000064400000000000000000000051661046102023000161360ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.70.0] timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test --workspace msrv: name: Rust 1.56.0 needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@1.56.0 - run: cargo check minimal: name: Minimal versions needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - run: cargo generate-lockfile -Z minimal-versions - run: cargo check --locked doc: name: Documentation needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --workspace --tests -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 ref-cast-1.0.23/.gitignore000064400000000000000000000000221046102023000133750ustar 00000000000000target Cargo.lock ref-cast-1.0.23/Cargo.toml0000644000000031040000000000100106170ustar # 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 = "2021" rust-version = "1.56" name = "ref-cast" version = "1.0.23" authors = ["David Tolnay "] build = "build.rs" autobins = false autoexamples = false autotests = false autobenches = false description = "Safely cast &T to &U where the struct U contains a single field of type T." documentation = "https://docs.rs/ref-cast" readme = "README.md" categories = [ "rust-patterns", "no-std", "no-std::no-alloc", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/ref-cast" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "ref_cast" path = "src/lib.rs" doc-scrape-examples = false [[test]] name = "test_custom" path = "tests/test_custom.rs" [[test]] name = "test_trivial" path = "tests/test_trivial.rs" [[test]] name = "compiletest" path = "tests/compiletest.rs" [dependencies.ref-cast-impl] version = "=1.0.23" [dev-dependencies.ref-cast-test-suite] version = "0" [dev-dependencies.rustversion] version = "1.0.13" [dev-dependencies.trybuild] version = "1.0.81" features = ["diff"] ref-cast-1.0.23/Cargo.toml.orig000064400000000000000000000015711046102023000143060ustar 00000000000000[package] name = "ref-cast" version = "1.0.23" authors = ["David Tolnay "] categories = ["rust-patterns", "no-std", "no-std::no-alloc"] description = "Safely cast &T to &U where the struct U contains a single field of type T." documentation = "https://docs.rs/ref-cast" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/ref-cast" rust-version = "1.56" [dependencies] ref-cast-impl = { version = "=1.0.23", path = "derive" } [dev-dependencies] ref-cast-test-suite = { version = "0", path = "tests/helper" } rustversion = "1.0.13" trybuild = { version = "1.0.81", features = ["diff"] } [workspace] members = ["derive", "tests/helper"] [lib] doc-scrape-examples = false [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] [patch.crates-io] ref-cast = { path = "." } ref-cast-1.0.23/LICENSE-APACHE000064400000000000000000000227731046102023000133520ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ref-cast-1.0.23/LICENSE-MIT000064400000000000000000000017771046102023000130630ustar 00000000000000Permission 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 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. ref-cast-1.0.23/README.md000064400000000000000000000065271046102023000127040ustar 00000000000000RefCast ======= [github](https://github.com/dtolnay/ref-cast) [crates.io](https://crates.io/crates/ref-cast) [docs.rs](https://docs.rs/ref-cast) [build status](https://github.com/dtolnay/ref-cast/actions?query=branch%3Amaster) Safely cast `&T` to `&U` where the struct `U` contains a single field of type `T`. ```toml [dependencies] ref-cast = "1.0" ``` ## Basic example ```rust use ref_cast::RefCast; #[derive(RefCast)] #[repr(transparent)] struct U(String); fn main() { let s = String::new(); // Safely cast from `&String` to `&U`. let u = U::ref_cast(&s); } ``` Note that `#[repr(transparent)]` is required in order for the conversion to be sound. The derive macro will refuse to compile if that is not present. ## Realistic example Suppose we have a multidimensional array represented in a flat buffer in row-major order for performance reasons, but we want to expose an indexing operation that works in column-major order because it is more intuitive in the context of our application. ```rust const MAP_WIDTH: usize = 4; struct Tile(u8); struct TileMap { storage: Vec, } // `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`. ``` The signature of the [`Index`] trait in Rust is such that the output is forced to be borrowed from the type being indexed. So something like the following is not going to work. [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html ```rust struct Column<'a> { tilemap: &'a TileMap, x: usize, } // Does not work! The output of Index must be a reference that is // borrowed from self. Here the type Column is not a reference. impl Index for TileMap { fn index(&self, x: usize) -> Column { assert!(x < MAP_WIDTH); Column { tilemap: self, x } } } impl<'a> Index for Column<'a> { fn index(&self, y: usize) -> &Tile { &self.tilemap.storage[y * MAP_WIDTH + self.x] } } ``` Here is a working approach using `RefCast`. ```rust #[derive(RefCast)] #[repr(transparent)] struct Strided([Tile]); // Implement `tilemap[x][y]` as `tilemap[x..][y * MAP_WIDTH]`. impl Index for TileMap { type Output = Strided; fn index(&self, x: usize) -> &Self::Output { assert!(x < MAP_WIDTH); Strided::ref_cast(&self.storage[x..]) } } impl Index for Strided { type Output = Tile; fn index(&self, y: usize) -> &Self::Output { &self.0[y * MAP_WIDTH] } } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ref-cast-1.0.23/build.rs000064400000000000000000000016211046102023000130600ustar 00000000000000use std::env; use std::process::Command; use std::str; fn main() { println!("cargo:rerun-if-changed=build.rs"); let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; if minor >= 80 { println!("cargo:rustc-check-cfg=cfg(no_intrinsic_type_name)"); println!("cargo:rustc-check-cfg=cfg(no_phantom_pinned)"); } if minor < 33 { println!("cargo:rustc-cfg=no_phantom_pinned"); } if minor < 38 { println!("cargo:rustc-cfg=no_intrinsic_type_name"); } } fn rustc_minor_version() -> Option { let rustc = env::var_os("RUSTC")?; let output = Command::new(rustc).arg("--version").output().ok()?; let version = str::from_utf8(&output.stdout).ok()?; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } pieces.next()?.parse().ok() } ref-cast-1.0.23/src/custom.rs000064400000000000000000000022071046102023000140630ustar 00000000000000// Not public API. Use #[derive(RefCastCustom)] and #[ref_cast_custom]. #[doc(hidden)] pub unsafe trait RefCastCustom { type CurrentCrate; fn __static_assert() {} } #[doc(hidden)] pub unsafe trait RefCastOkay: Sealed { type CurrentCrate; type Target: ?Sized; } unsafe impl<'a, From, To> RefCastOkay<&'a From> for &'a To where From: ?Sized, To: ?Sized + RefCastCustom, { type CurrentCrate = To::CurrentCrate; type Target = To; } unsafe impl<'a, From, To> RefCastOkay<&'a mut From> for &'a mut To where From: ?Sized, To: ?Sized + RefCastCustom, { type CurrentCrate = To::CurrentCrate; type Target = To; } #[doc(hidden)] pub trait Sealed {} impl<'a, From, To> Sealed<&'a From> for &'a To where From: ?Sized, To: ?Sized + RefCastCustom, { } impl<'a, From, To> Sealed<&'a mut From> for &'a mut To where From: ?Sized, To: ?Sized + RefCastCustom, { } #[doc(hidden)] pub type CurrentCrate = >::CurrentCrate; #[doc(hidden)] pub fn ref_cast_custom(_arg: From) where To: RefCastOkay, { } ref-cast-1.0.23/src/layout.rs000064400000000000000000000030701046102023000140650ustar 00000000000000use core::mem; #[doc(hidden)] pub struct Layout(T); #[doc(hidden)] pub trait LayoutUnsized { const SIZE: usize = usize::MAX; const ALIGN: usize = usize::MAX; } impl LayoutUnsized for Layout {} impl Layout { pub const SIZE: usize = mem::size_of::(); pub const ALIGN: usize = mem::align_of::(); } #[doc(hidden)] #[inline] pub fn assert_layout( name: &'static str, outer_size: usize, inner_size: usize, outer_align: usize, inner_align: usize, ) { if outer_size != inner_size { #[cfg(no_intrinsic_type_name)] panic!( "unexpected size in cast to {}: {} != {}", name, outer_size, inner_size, ); #[cfg(not(no_intrinsic_type_name))] panic!( "unexpected size in cast from {} to {}: {} != {}", core::any::type_name::(), core::any::type_name::(), inner_size, outer_size, ); } if outer_align != inner_align { #[cfg(no_intrinsic_type_name)] panic!( "unexpected alignment in cast to {}: {} != {}", name, outer_align, inner_align, ); #[cfg(not(no_intrinsic_type_name))] panic!( "unexpected alignment in cast from {} to {}: {} != {}", core::any::type_name::(), core::any::type_name::(), inner_align, outer_align, ); } #[cfg(not(no_intrinsic_type_name))] let _ = name; } ref-cast-1.0.23/src/lib.rs000064400000000000000000000120671046102023000133240ustar 00000000000000//! [![github]](https://github.com/dtolnay/ref-cast) [![crates-io]](https://crates.io/crates/ref-cast) [![docs-rs]](https://docs.rs/ref-cast) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! This crate provides a derive macro for generating safe conversions from `&T` //! to `&U` where the struct `U` contains a single field of type `T`. //! //! # Basic example //! //! ``` //! use ref_cast::RefCast; //! //! #[derive(RefCast)] //! #[repr(transparent)] //! struct U(String); //! //! fn main() { //! let s = String::new(); //! //! // Safely cast from `&String` to `&U`. //! let u = U::ref_cast(&s); //! } //! ``` //! //! Note that `#[repr(transparent)]` is required in order for the conversion to //! be sound. The derive macro will refuse to compile if that is not present. //! //! # Realistic example //! //! Suppose we have a multidimensional array represented in a flat buffer in //! row-major order for performance reasons, but we want to expose an indexing //! operation that works in column-major order because it is more intuitive in //! the context of our application. //! //! ``` //! const MAP_WIDTH: usize = 4; //! //! struct Tile(u8); //! //! struct TileMap { //! storage: Vec, //! } //! //! // `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`. //! ``` //! //! The signature of the [`Index`] trait in Rust is such that the output is //! forced to be borrowed from the type being indexed. So something like the //! following is not going to work. //! //! [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html //! //! ``` //! # const MAP_WIDTH: usize = 4; //! # //! # struct Tile(u8); //! # //! # struct TileMap { //! # storage: Vec, //! # } //! # //! struct Column<'a> { //! tilemap: &'a TileMap, //! x: usize, //! } //! //! # mod index1 { //! # use super::{TileMap, Column, MAP_WIDTH}; //! # //! # trait Index { //! # fn index(&self, idx: Idx) -> Column; //! # } //! # //! // Does not work! The output of Index must be a reference that is //! // borrowed from self. Here the type Column is not a reference. //! impl Index for TileMap { //! fn index(&self, x: usize) -> Column { //! assert!(x < MAP_WIDTH); //! Column { tilemap: self, x } //! } //! } //! # } //! //! # mod index2 { //! # use super::{Column, Tile, MAP_WIDTH}; //! # use std::ops::Index; //! # //! impl<'a> Index for Column<'a> { //! # type Output = Tile; //! fn index(&self, y: usize) -> &Tile { //! &self.tilemap.storage[y * MAP_WIDTH + self.x] //! } //! } //! # } //! # //! # fn main() {} //! ``` //! //! Here is a working approach using `RefCast`. //! //! ``` //! # use ref_cast::RefCast; //! # use std::ops::Index; //! # //! # const MAP_WIDTH: usize = 4; //! # //! # struct Tile(u8); //! # //! # struct TileMap { //! # storage: Vec, //! # } //! # //! #[derive(RefCast)] //! #[repr(transparent)] //! struct Strided([Tile]); //! //! // Implement `tilemap[x][y]` as `tilemap[x..][y * MAP_WIDTH]`. //! impl Index for TileMap { //! type Output = Strided; //! fn index(&self, x: usize) -> &Self::Output { //! assert!(x < MAP_WIDTH); //! Strided::ref_cast(&self.storage[x..]) //! } //! } //! //! impl Index for Strided { //! type Output = Tile; //! fn index(&self, y: usize) -> &Self::Output { //! &self.0[y * MAP_WIDTH] //! } //! } //! ``` #![doc(html_root_url = "https://docs.rs/ref-cast/1.0.23")] #![no_std] #![allow( clippy::extra_unused_type_parameters, clippy::let_underscore_untyped, clippy::manual_assert, clippy::missing_panics_doc, clippy::missing_safety_doc, clippy::module_name_repetitions, clippy::needless_doctest_main, clippy::needless_pass_by_value )] mod custom; mod layout; mod trivial; pub use ref_cast_impl::{ref_cast_custom, RefCast, RefCastCustom}; /// Safely cast `&T` to `&U` where the struct `U` contains a single field of /// type `T`. /// /// ``` /// # use ref_cast::RefCast; /// # /// // `&String` can be cast to `&U`. /// #[derive(RefCast)] /// #[repr(transparent)] /// struct U(String); /// /// // `&T` can be cast to `&V`. /// #[derive(RefCast)] /// #[repr(transparent)] /// struct V { /// t: T, /// } /// ``` /// /// See the [crate-level documentation][crate] for usage examples! pub trait RefCast { type From: ?Sized; fn ref_cast(from: &Self::From) -> &Self; fn ref_cast_mut(from: &mut Self::From) -> &mut Self; } // Not public API. #[doc(hidden)] pub mod __private { #[doc(hidden)] pub use crate::custom::{ref_cast_custom, CurrentCrate, RefCastCustom}; #[doc(hidden)] pub use crate::layout::{assert_layout, Layout, LayoutUnsized}; #[doc(hidden)] pub use crate::trivial::assert_trivial; #[doc(hidden)] pub use core::mem::transmute; } ref-cast-1.0.23/src/trivial.rs000064400000000000000000000005031046102023000142200ustar 00000000000000use core::marker::PhantomData; #[cfg(not(no_phantom_pinned))] use core::marker::PhantomPinned; #[doc(hidden)] pub trait Trivial {} impl Trivial for () {} impl Trivial for PhantomData {} #[cfg(not(no_phantom_pinned))] impl Trivial for PhantomPinned {} #[doc(hidden)] pub fn assert_trivial() {} ref-cast-1.0.23/tests/compiletest.rs000064400000000000000000000002461046102023000154550ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[cfg_attr(miri, ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } ref-cast-1.0.23/tests/test_custom.rs000064400000000000000000000005601046102023000154750ustar 00000000000000#[forbid(unsafe_code)] mod forbid_unsafe { use ref_cast::{ref_cast_custom, RefCastCustom}; #[derive(RefCastCustom)] #[repr(transparent)] pub struct Custom(#[allow(dead_code)] str); impl Custom { #[ref_cast_custom] pub fn new(s: &str) -> &Custom; } } #[test] fn test_forbid_unsafe() { forbid_unsafe::Custom::new("..."); } ref-cast-1.0.23/tests/test_trivial.rs000064400000000000000000000017311046102023000156360ustar 00000000000000#![allow(clippy::manual_non_exhaustive)] use ref_cast::RefCast; use std::marker::PhantomData; type Marker = PhantomData; #[derive(RefCast)] #[repr(transparent)] pub struct ImplicitUnit { pub value: usize, _private: (), } #[derive(RefCast)] #[repr(transparent)] pub struct ImplicitPhantomData { pub value: T, pub marker: PhantomData, } #[derive(RefCast)] #[repr(transparent)] pub struct ExplicitTrivial { pub value: usize, #[trivial] pub marker: Marker, } #[derive(RefCast)] #[repr(C)] pub struct Override { #[trivial] pub first: PhantomData, pub second: PhantomData, } #[derive(RefCast)] #[repr(transparent)] pub struct Unsized<'a> { pub marker: PhantomData<&'a str>, pub value: str, } #[test] fn test_trivial() { ImplicitUnit::ref_cast(&0); ImplicitPhantomData::ref_cast(&0); ExplicitTrivial::ref_cast(&0); Override::::ref_cast(&PhantomData::); Unsized::ref_cast("..."); } ref-cast-1.0.23/tests/ui/cross-crate.rs000064400000000000000000000003041046102023000157620ustar 00000000000000use ref_cast::ref_cast_custom; use ref_cast_test_suite::Struct; #[ref_cast_custom] fn ref_cast(s: &str) -> &Struct; #[ref_cast_custom] fn ref_cast_mut(s: &mut str) -> &mut Struct; fn main() {} ref-cast-1.0.23/tests/ui/cross-crate.stderr000064400000000000000000000006151046102023000166460ustar 00000000000000error[E0639]: cannot create non-exhaustive struct using struct expression --> tests/ui/cross-crate.rs:5:32 | 5 | fn ref_cast(s: &str) -> &Struct; | ^ error[E0639]: cannot create non-exhaustive struct using struct expression --> tests/ui/cross-crate.rs:8:44 | 8 | fn ref_cast_mut(s: &mut str) -> &mut Struct; | ^ ref-cast-1.0.23/tests/ui/dst-before-trivial.rs000064400000000000000000000003121046102023000172360ustar 00000000000000use ref_cast::RefCast; use std::marker::PhantomData; #[derive(RefCast)] #[repr(transparent)] struct Bytes<'arena> { bytes: [u8], #[trivial] marker: PhantomData<&'arena ()>, } fn main() {} ref-cast-1.0.23/tests/ui/dst-before-trivial.stderr000064400000000000000000000012331046102023000201200ustar 00000000000000error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> tests/ui/dst-before-trivial.rs:7:12 | 7 | bytes: [u8], | ^^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `[u8]` = note: only the last field of a struct may have a dynamically sized type = help: change the field's type to have a statically known size help: borrowed types always have a statically known size | 7 | bytes: &[u8], | + help: the `Box` type always has a statically known size and allocates its contents in the heap | 7 | bytes: Box<[u8]>, | ++++ + ref-cast-1.0.23/tests/ui/extra-arg.rs000064400000000000000000000003421046102023000154310ustar 00000000000000use ref_cast::{ref_cast_custom, RefCastCustom}; #[derive(RefCastCustom)] #[repr(transparent)] pub struct Thing(String); impl Thing { #[ref_cast_custom] pub fn ref_cast(s: &String, wat: i32) -> &Self; } fn main() {} ref-cast-1.0.23/tests/ui/extra-arg.stderr000064400000000000000000000010751046102023000163140ustar 00000000000000error: ref_cast_custom function is required to have a single argument --> tests/ui/extra-arg.rs:9:33 | 9 | pub fn ref_cast(s: &String, wat: i32) -> &Self; | ^^^^^^^^ error: associated function in `impl` without body --> tests/ui/extra-arg.rs:9:5 | 9 | pub fn ref_cast(s: &String, wat: i32) -> &Self; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- | | | help: provide a definition for the function: `{ }` ref-cast-1.0.23/tests/ui/function-body.rs000064400000000000000000000003321046102023000163160ustar 00000000000000use ref_cast::{ref_cast_custom, RefCastCustom}; #[derive(RefCastCustom)] #[repr(transparent)] pub struct Thing(String); impl Thing { #[ref_cast_custom] pub fn ref_cast(s: &String) -> &Self {} } fn main() {} ref-cast-1.0.23/tests/ui/function-body.stderr000064400000000000000000000007051046102023000172010ustar 00000000000000error: expected `;` --> tests/ui/function-body.rs:9:42 | 9 | pub fn ref_cast(s: &String) -> &Self {} | ^ error[E0308]: mismatched types --> tests/ui/function-body.rs:9:36 | 9 | pub fn ref_cast(s: &String) -> &Self {} | -------- ^^^^^ expected `&Thing`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression ref-cast-1.0.23/tests/ui/impl-trait.rs000064400000000000000000000004511046102023000156220ustar 00000000000000use ref_cast::{ref_cast_custom, RefCastCustom}; #[derive(RefCastCustom)] #[repr(transparent)] pub struct Thing(str); impl Thing { #[ref_cast_custom] pub fn ref_cast(s: impl AsRef) -> &Self; #[ref_cast_custom] pub fn ref_cast2(s: &impl AsRef) -> &Self; } fn main() {} ref-cast-1.0.23/tests/ui/impl-trait.stderr000064400000000000000000000025001046102023000164760ustar 00000000000000error[E0106]: missing lifetime specifier --> tests/ui/impl-trait.rs:9:44 | 9 | pub fn ref_cast(s: impl AsRef) -> &Self; | ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static` | 9 | pub fn ref_cast(s: impl AsRef) -> &'static Self; | +++++++ help: consider introducing a named lifetime parameter | 9 | pub fn ref_cast<'a>(s: impl AsRef) -> &'a Self; | ++++ ~~~ error[E0562]: `impl Trait` is not allowed in paths --> tests/ui/impl-trait.rs:9:24 | 9 | pub fn ref_cast(s: impl AsRef) -> &Self; | ^^^^^^^^^^^^^^^ | = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in paths --> tests/ui/impl-trait.rs:12:26 | 12 | pub fn ref_cast2(s: &impl AsRef) -> &Self; | ^^^^^^^^^^^^^^^ | = note: `impl Trait` is only allowed in arguments and return types of functions and methods ref-cast-1.0.23/tests/ui/no-custom.rs000064400000000000000000000002561046102023000154670ustar 00000000000000use ref_cast::ref_cast_custom; #[repr(transparent)] pub struct Thing(String); impl Thing { #[ref_cast_custom] pub fn ref_cast(s: &String) -> &Self; } fn main() {} ref-cast-1.0.23/tests/ui/no-custom.stderr000064400000000000000000000034731046102023000163520ustar 00000000000000error[E0277]: the trait bound `&Thing: ref_cast::custom::RefCastOkay<&String>` is not satisfied --> tests/ui/no-custom.rs:8:36 | 8 | pub fn ref_cast(s: &String) -> &Self; | ^^^^^ the trait `RefCastCustom` is not implemented for `&Thing`, which is required by `&Thing: ref_cast::custom::RefCastOkay<&String>` | = help: the following other types implement trait `ref_cast::custom::RefCastOkay`: <&'a To as ref_cast::custom::RefCastOkay<&'a From>> <&'a mut To as ref_cast::custom::RefCastOkay<&'a mut From>> = note: required for `&Thing` to implement `ref_cast::custom::RefCastOkay<&String>` note: required by a bound in `ref_cast_custom` --> src/custom.rs | | pub fn ref_cast_custom(_arg: From) | --------------- required by a bound in this function | where | To: RefCastOkay, | ^^^^^^^^^^^^^^^^^ required by this bound in `ref_cast_custom` error[E0071]: expected struct, variant or union type, found inferred type --> tests/ui/no-custom.rs:8:41 | 8 | pub fn ref_cast(s: &String) -> &Self; | ^ not a struct error[E0277]: the trait bound `Thing: RefCastCustom` is not satisfied --> tests/ui/no-custom.rs:8:41 | 8 | pub fn ref_cast(s: &String) -> &Self; | ^ the trait `RefCastCustom` is not implemented for `Thing`, which is required by `&Thing: ref_cast::custom::RefCastOkay<&String>` | = help: the following other types implement trait `ref_cast::custom::RefCastOkay`: <&'a To as ref_cast::custom::RefCastOkay<&'a From>> <&'a mut To as ref_cast::custom::RefCastOkay<&'a mut From>> = note: required for `&Thing` to implement `ref_cast::custom::RefCastOkay<&String>` ref-cast-1.0.23/tests/ui/no-repr.rs000064400000000000000000000001301046102023000151140ustar 00000000000000use ref_cast::RefCast; #[derive(RefCast)] struct Test { s: String, } fn main() {} ref-cast-1.0.23/tests/ui/no-repr.stderr000064400000000000000000000004021046102023000157750ustar 00000000000000error: RefCast trait requires #[repr(transparent)] --> tests/ui/no-repr.rs:3:10 | 3 | #[derive(RefCast)] | ^^^^^^^ | = note: this error originates in the derive macro `RefCast` (in Nightly builds, run with -Z macro-backtrace for more info) ref-cast-1.0.23/tests/ui/not-trivial.rs000064400000000000000000000002051046102023000160050ustar 00000000000000use ref_cast::RefCast; #[derive(RefCast)] #[repr(C)] struct Test { one: String, #[trivial] two: String, } fn main() {} ref-cast-1.0.23/tests/ui/not-trivial.stderr000064400000000000000000000011051046102023000166640ustar 00000000000000error[E0277]: the trait bound `String: ref_cast::trivial::Trivial` is not satisfied --> tests/ui/not-trivial.rs:8:10 | 8 | two: String, | ^^^^^^ the trait `ref_cast::trivial::Trivial` is not implemented for `String` | = help: the following other types implement trait `ref_cast::trivial::Trivial`: () PhantomData PhantomPinned note: required by a bound in `assert_trivial` --> src/trivial.rs | | pub fn assert_trivial() {} | ^^^^^^^ required by this bound in `assert_trivial` ref-cast-1.0.23/tests/ui/private.rs000064400000000000000000000005461046102023000152170ustar 00000000000000use ref_cast::{ref_cast_custom, RefCast, RefCastCustom}; #[derive(RefCast, RefCastCustom)] #[repr(transparent)] pub struct Public { private: Private, } struct Private; impl Public { #[ref_cast_custom] fn ref_cast(private: &Private) -> &Public; #[ref_cast_custom] fn ref_cast_mut(private: &mut Private) -> &mut Public; } fn main() {} ref-cast-1.0.23/tests/ui/private.stderr000064400000000000000000000005701046102023000160730ustar 00000000000000error[E0446]: private type `Private` in public interface --> tests/ui/private.rs:3:10 | 3 | #[derive(RefCast, RefCastCustom)] | ^^^^^^^ can't leak private type ... 9 | struct Private; | -------------- `Private` declared as private | = note: this error originates in the derive macro `RefCast` (in Nightly builds, run with -Z macro-backtrace for more info) ref-cast-1.0.23/tests/ui/repr-align.rs000064400000000000000000000001721046102023000156000ustar 00000000000000use ref_cast::RefCast; #[derive(RefCast)] #[repr(align(2), C, align = "2")] struct Test { s: String, } fn main() {} ref-cast-1.0.23/tests/ui/repr-align.stderr000064400000000000000000000010551046102023000164600ustar 00000000000000error: aligned repr on struct that implements RefCast is not supported --> tests/ui/repr-align.rs:4:8 | 4 | #[repr(align(2), C, align = "2")] | ^^^^^^^^ error: aligned repr on struct that implements RefCast is not supported --> tests/ui/repr-align.rs:4:21 | 4 | #[repr(align(2), C, align = "2")] | ^^^^^^^^^^^ error[E0693]: incorrect `repr(align)` attribute format --> tests/ui/repr-align.rs:4:21 | 4 | #[repr(align(2), C, align = "2")] | ^^^^^^^^^^^ help: use parentheses instead: `align(2)` ref-cast-1.0.23/tests/ui/short-lifetime.rs000064400000000000000000000003371046102023000164760ustar 00000000000000use ref_cast::{ref_cast_custom, RefCastCustom}; #[derive(RefCastCustom)] #[repr(transparent)] pub struct Thing(String); impl Thing { #[ref_cast_custom] pub fn ref_cast<'a>(s: &String) -> &'a Self; } fn main() {} ref-cast-1.0.23/tests/ui/short-lifetime.stderr000064400000000000000000000005501046102023000173520ustar 00000000000000error[E0621]: explicit lifetime required in the type of `s` --> tests/ui/short-lifetime.rs:9:48 | 9 | pub fn ref_cast<'a>(s: &String) -> &'a Self; | ------- ^ lifetime `'a` required | | | help: add explicit lifetime `'a` to the type of `s`: `&'a String` ref-cast-1.0.23/tests/ui/unrecognized-repr.rs000064400000000000000000000002111046102023000171740ustar 00000000000000use ref_cast::RefCast; #[derive(RefCast)] #[repr(packed, C, usize, usize(0), usize = "0")] struct Test { s: String, } fn main() {} ref-cast-1.0.23/tests/ui/unrecognized-repr.stderr000064400000000000000000000044141046102023000200640ustar 00000000000000error: unrecognized repr on struct that implements RefCast --> tests/ui/unrecognized-repr.rs:4:19 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^ error: unrecognized repr on struct that implements RefCast --> tests/ui/unrecognized-repr.rs:4:26 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^ error: unrecognized repr on struct that implements RefCast --> tests/ui/unrecognized-repr.rs:4:36 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^^^^ error[E0552]: invalid representation hint: `usize` does not take a parenthesized argument list --> tests/ui/unrecognized-repr.rs:4:26 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^ error[E0552]: invalid representation hint: `usize` does not take a value --> tests/ui/unrecognized-repr.rs:4:36 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^^^^ error[E0517]: attribute should be applied to an enum --> tests/ui/unrecognized-repr.rs:4:19 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^ 5 | / struct Test { 6 | | s: String, 7 | | } | |_- not an enum error[E0517]: attribute should be applied to an enum --> tests/ui/unrecognized-repr.rs:4:26 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^ 5 | / struct Test { 6 | | s: String, 7 | | } | |_- not an enum error[E0517]: attribute should be applied to an enum --> tests/ui/unrecognized-repr.rs:4:36 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^^^^^^ 5 | / struct Test { 6 | | s: String, 7 | | } | |_- not an enum error[E0566]: conflicting representation hints --> tests/ui/unrecognized-repr.rs:4:8 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] | ^^^^^^ ^ ^^^^^ ^^^^^^^^ ^^^^^^^^^^^ | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #68585 = note: `#[deny(conflicting_repr_hints)]` on by default