├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── derive ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ └── lib.rs ├── src ├── custom.rs ├── layout.rs ├── lib.rs └── trivial.rs └── tests ├── compiletest.rs ├── helper ├── Cargo.toml └── lib.rs ├── test_custom.rs ├── test_trivial.rs └── ui ├── cross-crate.rs ├── cross-crate.stderr ├── dst-before-trivial.rs ├── dst-before-trivial.stderr ├── extra-arg.rs ├── extra-arg.stderr ├── function-body.rs ├── function-body.stderr ├── impl-trait.rs ├── impl-trait.stderr ├── no-custom.rs ├── no-custom.stderr ├── no-repr.rs ├── no-repr.stderr ├── not-trivial.rs ├── not-trivial.stderr ├── private.rs ├── private.stderr ├── repr-align.rs ├── repr-align.stderr ├── short-lifetime.rs ├── short-lifetime.stderr ├── unrecognized-repr.rs └── unrecognized-repr.stderr /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | pre_ci: 17 | uses: dtolnay/.github/.github/workflows/pre_ci.yml@master 18 | 19 | test: 20 | name: Rust ${{matrix.rust}} 21 | needs: pre_ci 22 | if: needs.pre_ci.outputs.continue 23 | runs-on: ubuntu-latest 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | rust: [nightly, beta, stable, 1.70.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{matrix.rust}} 34 | - name: Enable type layout randomization 35 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 36 | if: matrix.rust == 'nightly' 37 | - run: cargo test --workspace 38 | - uses: actions/upload-artifact@v4 39 | if: matrix.rust == 'nightly' && always() 40 | with: 41 | name: Cargo.lock 42 | path: Cargo.lock 43 | continue-on-error: true 44 | 45 | msrv: 46 | name: Rust 1.56.0 47 | needs: pre_ci 48 | if: needs.pre_ci.outputs.continue 49 | runs-on: ubuntu-latest 50 | timeout-minutes: 45 51 | steps: 52 | - uses: actions/checkout@v4 53 | - uses: dtolnay/rust-toolchain@1.56.0 54 | - run: cargo check 55 | 56 | minimal: 57 | name: Minimal versions 58 | needs: pre_ci 59 | if: needs.pre_ci.outputs.continue 60 | runs-on: ubuntu-latest 61 | timeout-minutes: 45 62 | steps: 63 | - uses: actions/checkout@v4 64 | - uses: dtolnay/rust-toolchain@nightly 65 | - run: cargo generate-lockfile -Z minimal-versions 66 | - run: cargo check --locked 67 | 68 | doc: 69 | name: Documentation 70 | needs: pre_ci 71 | if: needs.pre_ci.outputs.continue 72 | runs-on: ubuntu-latest 73 | timeout-minutes: 45 74 | env: 75 | RUSTDOCFLAGS: -Dwarnings 76 | steps: 77 | - uses: actions/checkout@v4 78 | - uses: dtolnay/rust-toolchain@nightly 79 | - uses: dtolnay/install@cargo-docs-rs 80 | - run: cargo docs-rs 81 | 82 | miri: 83 | name: Miri 84 | needs: pre_ci 85 | if: needs.pre_ci.outputs.continue 86 | runs-on: ubuntu-latest 87 | timeout-minutes: 45 88 | steps: 89 | - uses: actions/checkout@v4 90 | - uses: dtolnay/rust-toolchain@miri 91 | with: 92 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 93 | - run: cargo miri setup 94 | - run: cargo miri test 95 | env: 96 | MIRIFLAGS: -Zmiri-strict-provenance 97 | 98 | clippy: 99 | name: Clippy 100 | runs-on: ubuntu-latest 101 | if: github.event_name != 'pull_request' 102 | timeout-minutes: 45 103 | steps: 104 | - uses: actions/checkout@v4 105 | - uses: dtolnay/rust-toolchain@clippy 106 | - run: cargo clippy --workspace --tests -- -Dclippy::all -Dclippy::pedantic 107 | 108 | outdated: 109 | name: Outdated 110 | runs-on: ubuntu-latest 111 | if: github.event_name != 'pull_request' 112 | timeout-minutes: 45 113 | steps: 114 | - uses: actions/checkout@v4 115 | - uses: dtolnay/rust-toolchain@stable 116 | - uses: dtolnay/install@cargo-outdated 117 | - run: cargo outdated --workspace --exit-code 1 118 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ref-cast" 3 | version = "1.0.24" 4 | authors = ["David Tolnay "] 5 | categories = ["rust-patterns", "no-std", "no-std::no-alloc"] 6 | description = "Safely cast &T to &U where the struct U contains a single field of type T." 7 | documentation = "https://docs.rs/ref-cast" 8 | edition = "2021" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/dtolnay/ref-cast" 11 | rust-version = "1.56" 12 | 13 | [dependencies] 14 | ref-cast-impl = { version = "=1.0.24", path = "derive" } 15 | 16 | [dev-dependencies] 17 | ref-cast-test-suite = { version = "0", path = "tests/helper" } 18 | rustversion = "1.0.13" 19 | trybuild = { version = "1.0.81", features = ["diff"] } 20 | 21 | [workspace] 22 | members = ["derive", "tests/helper"] 23 | 24 | [package.metadata.docs.rs] 25 | targets = ["x86_64-unknown-linux-gnu"] 26 | rustdoc-args = [ 27 | "--generate-link-to-definition", 28 | "--extern-html-root-url=core=https://doc.rust-lang.org", 29 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 30 | "--extern-html-root-url=std=https://doc.rust-lang.org", 31 | ] 32 | 33 | [patch.crates-io] 34 | ref-cast = { path = "." } 35 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | RefCast 2 | ======= 3 | 4 | [github](https://github.com/dtolnay/ref-cast) 5 | [crates.io](https://crates.io/crates/ref-cast) 6 | [docs.rs](https://docs.rs/ref-cast) 7 | [build status](https://github.com/dtolnay/ref-cast/actions?query=branch%3Amaster) 8 | 9 | Safely cast `&T` to `&U` where the struct `U` contains a single field of 10 | type `T`. 11 | 12 | ```toml 13 | [dependencies] 14 | ref-cast = "1.0" 15 | ``` 16 | 17 | ## Basic example 18 | 19 | ```rust 20 | use ref_cast::RefCast; 21 | 22 | #[derive(RefCast)] 23 | #[repr(transparent)] 24 | struct U(String); 25 | 26 | fn main() { 27 | let s = String::new(); 28 | 29 | // Safely cast from `&String` to `&U`. 30 | let u = U::ref_cast(&s); 31 | } 32 | ``` 33 | 34 | Note that `#[repr(transparent)]` is required in order for the conversion to be 35 | sound. The derive macro will refuse to compile if that is not present. 36 | 37 | ## Realistic example 38 | 39 | Suppose we have a multidimensional array represented in a flat buffer in 40 | row-major order for performance reasons, but we want to expose an indexing 41 | operation that works in column-major order because it is more intuitive in 42 | the context of our application. 43 | 44 | ```rust 45 | const MAP_WIDTH: usize = 4; 46 | 47 | struct Tile(u8); 48 | 49 | struct TileMap { 50 | storage: Vec, 51 | } 52 | 53 | // `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`. 54 | ``` 55 | 56 | The signature of the [`Index`] trait in Rust is such that the output is 57 | forced to be borrowed from the type being indexed. So something like the 58 | following is not going to work. 59 | 60 | [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html 61 | 62 | ```rust 63 | struct Column<'a> { 64 | tilemap: &'a TileMap, 65 | x: usize, 66 | } 67 | 68 | // Does not work! The output of Index must be a reference that is 69 | // borrowed from self. Here the type Column is not a reference. 70 | impl Index for TileMap { 71 | fn index(&self, x: usize) -> Column { 72 | assert!(x < MAP_WIDTH); 73 | Column { tilemap: self, x } 74 | } 75 | } 76 | 77 | impl<'a> Index for Column<'a> { 78 | fn index(&self, y: usize) -> &Tile { 79 | &self.tilemap.storage[y * MAP_WIDTH + self.x] 80 | } 81 | } 82 | ``` 83 | 84 | Here is a working approach using `RefCast`. 85 | 86 | ```rust 87 | #[derive(RefCast)] 88 | #[repr(transparent)] 89 | struct Strided([Tile]); 90 | 91 | // Implement `tilemap[x][y]` as `tilemap[x..][y * MAP_WIDTH]`. 92 | impl Index for TileMap { 93 | type Output = Strided; 94 | fn index(&self, x: usize) -> &Self::Output { 95 | assert!(x < MAP_WIDTH); 96 | Strided::ref_cast(&self.storage[x..]) 97 | } 98 | } 99 | 100 | impl Index for Strided { 101 | type Output = Tile; 102 | fn index(&self, y: usize) -> &Self::Output { 103 | &self.0[y * MAP_WIDTH] 104 | } 105 | } 106 | ``` 107 | 108 |
109 | 110 | #### License 111 | 112 | 113 | Licensed under either of Apache License, Version 114 | 2.0 or MIT license at your option. 115 | 116 | 117 |
118 | 119 | 120 | Unless you explicitly state otherwise, any contribution intentionally submitted 121 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 122 | be dual licensed as above, without any additional terms or conditions. 123 | 124 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process::Command; 3 | use std::str; 4 | 5 | fn main() { 6 | println!("cargo:rerun-if-changed=build.rs"); 7 | 8 | let minor = match rustc_minor_version() { 9 | Some(minor) => minor, 10 | None => return, 11 | }; 12 | 13 | if minor >= 80 { 14 | println!("cargo:rustc-check-cfg=cfg(no_intrinsic_type_name)"); 15 | println!("cargo:rustc-check-cfg=cfg(no_phantom_pinned)"); 16 | } 17 | 18 | if minor < 33 { 19 | println!("cargo:rustc-cfg=no_phantom_pinned"); 20 | } 21 | 22 | if minor < 38 { 23 | println!("cargo:rustc-cfg=no_intrinsic_type_name"); 24 | } 25 | } 26 | 27 | fn rustc_minor_version() -> Option { 28 | let rustc = env::var_os("RUSTC")?; 29 | let output = Command::new(rustc).arg("--version").output().ok()?; 30 | let version = str::from_utf8(&output.stdout).ok()?; 31 | let mut pieces = version.split('.'); 32 | if pieces.next() != Some("rustc 1") { 33 | return None; 34 | } 35 | pieces.next()?.parse().ok() 36 | } 37 | -------------------------------------------------------------------------------- /derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ref-cast-impl" 3 | version = "1.0.24" 4 | authors = ["David Tolnay "] 5 | description = "Derive implementation for ref_cast::RefCast." 6 | documentation = "https://docs.rs/ref-cast" 7 | edition = "2021" 8 | license = "MIT OR Apache-2.0" 9 | repository = "https://github.com/dtolnay/ref-cast" 10 | rust-version = "1.56" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | proc-macro2 = "1.0.74" 17 | quote = "1.0.35" 18 | syn = "2.0.46" 19 | 20 | [dev-dependencies] 21 | ref-cast = "1" 22 | 23 | [package.metadata.docs.rs] 24 | targets = ["x86_64-unknown-linux-gnu"] 25 | rustdoc-args = [ 26 | "--generate-link-to-definition", 27 | "--extern-html-root-url=core=https://doc.rust-lang.org", 28 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 29 | "--extern-html-root-url=std=https://doc.rust-lang.org", 30 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 31 | ] 32 | -------------------------------------------------------------------------------- /derive/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /derive/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow( 2 | clippy::blocks_in_conditions, 3 | clippy::needless_pass_by_value, 4 | clippy::if_not_else 5 | )] 6 | 7 | extern crate proc_macro; 8 | 9 | use proc_macro::TokenStream; 10 | use proc_macro2::{Ident, Span, TokenStream as TokenStream2, TokenTree}; 11 | use quote::{quote, quote_spanned}; 12 | use syn::parse::{Nothing, ParseStream, Parser}; 13 | use syn::punctuated::Punctuated; 14 | use syn::{ 15 | parenthesized, parse_macro_input, token, Abi, Attribute, Data, DeriveInput, Error, Expr, Field, 16 | Generics, Path, Result, Token, Type, Visibility, 17 | }; 18 | 19 | /// Derive the `RefCast` trait. 20 | /// 21 | /// See the [crate-level documentation](./index.html) for usage examples! 22 | /// 23 | /// # Attributes 24 | /// 25 | /// Use the `#[trivial]` attribute to mark any zero-sized fields that are *not* 26 | /// the one that references are going to be converted from. 27 | /// 28 | /// ``` 29 | /// use ref_cast::RefCast; 30 | /// use std::marker::PhantomData; 31 | /// 32 | /// #[derive(RefCast)] 33 | /// #[repr(transparent)] 34 | /// pub struct Generic { 35 | /// raw: Vec, 36 | /// #[trivial] 37 | /// aux: Variance, 38 | /// } 39 | /// 40 | /// type Variance = PhantomData U>; 41 | /// ``` 42 | /// 43 | /// Fields with a type named `PhantomData` or `PhantomPinned` are automatically 44 | /// recognized and do not need to be marked with this attribute. 45 | /// 46 | /// ``` 47 | /// use ref_cast::RefCast; 48 | /// use std::marker::{PhantomData, PhantomPinned}; 49 | /// 50 | /// #[derive(RefCast)] // generates a conversion from &[u8] to &Bytes<'_> 51 | /// #[repr(transparent)] 52 | /// pub struct Bytes<'arena> { 53 | /// lifetime: PhantomData<&'arena ()>, 54 | /// pin: PhantomPinned, 55 | /// bytes: [u8], 56 | /// } 57 | /// ``` 58 | #[proc_macro_derive(RefCast, attributes(trivial))] 59 | pub fn derive_ref_cast(input: TokenStream) -> TokenStream { 60 | let input = parse_macro_input!(input as DeriveInput); 61 | expand_ref_cast(&input) 62 | .unwrap_or_else(Error::into_compile_error) 63 | .into() 64 | } 65 | 66 | /// Derive that makes the `ref_cast_custom` attribute able to generate 67 | /// freestanding reference casting functions for a type. 68 | /// 69 | /// Please refer to the documentation of 70 | /// [`#[ref_cast_custom]`][macro@ref_cast_custom] where these two macros are 71 | /// documented together. 72 | #[proc_macro_derive(RefCastCustom, attributes(trivial))] 73 | pub fn derive_ref_cast_custom(input: TokenStream) -> TokenStream { 74 | let input = parse_macro_input!(input as DeriveInput); 75 | expand_ref_cast_custom(&input) 76 | .unwrap_or_else(Error::into_compile_error) 77 | .into() 78 | } 79 | 80 | /// Create a function for a RefCast-style reference cast. Call site gets control 81 | /// of the visibility, function name, argument name, `const`ness, unsafety, and 82 | /// documentation. 83 | /// 84 | /// The `derive(RefCast)` macro produces a trait impl, which means the function 85 | /// names are predefined, and public if your type is public, and not callable in 86 | /// `const` (at least today on stable Rust). As an alternative to that, 87 | /// `derive(RefCastCustom)` exposes greater flexibility so that instead of a 88 | /// trait impl, the casting functions can be made associated functions or free 89 | /// functions, can be named what you want, documented, `const` or `unsafe` if 90 | /// you want, and have your exact choice of visibility. 91 | /// 92 | /// ```rust 93 | /// use ref_cast::{ref_cast_custom, RefCastCustom}; 94 | /// 95 | /// #[derive(RefCastCustom)] // does not generate any public API by itself 96 | /// #[repr(transparent)] 97 | /// pub struct Frame([u8]); 98 | /// 99 | /// impl Frame { 100 | /// #[ref_cast_custom] // requires derive(RefCastCustom) on the return type 101 | /// pub(crate) const fn new(bytes: &[u8]) -> &Self; 102 | /// 103 | /// #[ref_cast_custom] 104 | /// pub(crate) fn new_mut(bytes: &mut [u8]) -> &mut Self; 105 | /// } 106 | /// 107 | /// // example use of the const fn 108 | /// const FRAME: &Frame = Frame::new(b"..."); 109 | /// ``` 110 | /// 111 | /// The above shows associated functions, but you might alternatively want to 112 | /// generate free functions: 113 | /// 114 | /// ```rust 115 | /// # use ref_cast::{ref_cast_custom, RefCastCustom}; 116 | /// # 117 | /// # #[derive(RefCastCustom)] 118 | /// # #[repr(transparent)] 119 | /// # pub struct Frame([u8]); 120 | /// # 121 | /// impl Frame { 122 | /// pub fn new>(bytes: &T) -> &Self { 123 | /// #[ref_cast_custom] 124 | /// fn ref_cast(bytes: &[u8]) -> &Frame; 125 | /// 126 | /// ref_cast(bytes.as_ref()) 127 | /// } 128 | /// } 129 | /// ``` 130 | #[proc_macro_attribute] 131 | pub fn ref_cast_custom(args: TokenStream, input: TokenStream) -> TokenStream { 132 | let input = TokenStream2::from(input); 133 | let expanded = match (|input: ParseStream| { 134 | let attrs = input.call(Attribute::parse_outer)?; 135 | let vis: Visibility = input.parse()?; 136 | let constness: Option = input.parse()?; 137 | let asyncness: Option = input.parse()?; 138 | let unsafety: Option = input.parse()?; 139 | let abi: Option = input.parse()?; 140 | let fn_token: Token![fn] = input.parse()?; 141 | let ident: Ident = input.parse()?; 142 | let mut generics: Generics = input.parse()?; 143 | 144 | let content; 145 | let paren_token = parenthesized!(content in input); 146 | let arg: Ident = content.parse()?; 147 | let colon_token: Token![:] = content.parse()?; 148 | let from_type: Type = content.parse()?; 149 | let _trailing_comma: Option = content.parse()?; 150 | if !content.is_empty() { 151 | let rest: TokenStream2 = content.parse()?; 152 | return Err(Error::new_spanned( 153 | rest, 154 | "ref_cast_custom function is required to have a single argument", 155 | )); 156 | } 157 | 158 | let arrow_token: Token![->] = input.parse()?; 159 | let to_type: Type = input.parse()?; 160 | generics.where_clause = input.parse()?; 161 | let semi_token: Token![;] = input.parse()?; 162 | 163 | let _: Nothing = syn::parse::(args)?; 164 | 165 | Ok(Function { 166 | attrs, 167 | vis, 168 | constness, 169 | asyncness, 170 | unsafety, 171 | abi, 172 | fn_token, 173 | ident, 174 | generics, 175 | paren_token, 176 | arg, 177 | colon_token, 178 | from_type, 179 | arrow_token, 180 | to_type, 181 | semi_token, 182 | }) 183 | }) 184 | .parse2(input.clone()) 185 | { 186 | Ok(function) => expand_function_body(function), 187 | Err(parse_error) => { 188 | let compile_error = parse_error.to_compile_error(); 189 | quote!(#compile_error #input) 190 | } 191 | }; 192 | TokenStream::from(expanded) 193 | } 194 | 195 | struct Function { 196 | attrs: Vec, 197 | vis: Visibility, 198 | constness: Option, 199 | asyncness: Option, 200 | unsafety: Option, 201 | abi: Option, 202 | fn_token: Token![fn], 203 | ident: Ident, 204 | generics: Generics, 205 | paren_token: token::Paren, 206 | arg: Ident, 207 | colon_token: Token![:], 208 | from_type: Type, 209 | arrow_token: Token![->], 210 | to_type: Type, 211 | semi_token: Token![;], 212 | } 213 | 214 | fn expand_ref_cast(input: &DeriveInput) -> Result { 215 | check_repr(input)?; 216 | 217 | let name = &input.ident; 218 | let name_str = name.to_string(); 219 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 220 | 221 | let fields = fields(input)?; 222 | let from = only_field_ty(fields)?; 223 | let trivial = trivial_fields(fields)?; 224 | 225 | let assert_trivial_fields = if !trivial.is_empty() { 226 | Some(quote! { 227 | if false { 228 | #( 229 | ::ref_cast::__private::assert_trivial::<#trivial>(); 230 | )* 231 | } 232 | }) 233 | } else { 234 | None 235 | }; 236 | 237 | Ok(quote! { 238 | impl #impl_generics ::ref_cast::RefCast for #name #ty_generics #where_clause { 239 | type From = #from; 240 | 241 | #[inline] 242 | fn ref_cast(_from: &Self::From) -> &Self { 243 | #assert_trivial_fields 244 | #[cfg(debug_assertions)] 245 | { 246 | #[allow(unused_imports)] 247 | use ::ref_cast::__private::LayoutUnsized; 248 | ::ref_cast::__private::assert_layout::( 249 | #name_str, 250 | ::ref_cast::__private::Layout::::SIZE, 251 | ::ref_cast::__private::Layout::::SIZE, 252 | ::ref_cast::__private::Layout::::ALIGN, 253 | ::ref_cast::__private::Layout::::ALIGN, 254 | ); 255 | } 256 | unsafe { 257 | &*(_from as *const Self::From as *const Self) 258 | } 259 | } 260 | 261 | #[inline] 262 | fn ref_cast_mut(_from: &mut Self::From) -> &mut Self { 263 | #[cfg(debug_assertions)] 264 | { 265 | #[allow(unused_imports)] 266 | use ::ref_cast::__private::LayoutUnsized; 267 | ::ref_cast::__private::assert_layout::( 268 | #name_str, 269 | ::ref_cast::__private::Layout::::SIZE, 270 | ::ref_cast::__private::Layout::::SIZE, 271 | ::ref_cast::__private::Layout::::ALIGN, 272 | ::ref_cast::__private::Layout::::ALIGN, 273 | ); 274 | } 275 | unsafe { 276 | &mut *(_from as *mut Self::From as *mut Self) 277 | } 278 | } 279 | } 280 | }) 281 | } 282 | 283 | fn expand_ref_cast_custom(input: &DeriveInput) -> Result { 284 | check_repr(input)?; 285 | 286 | let vis = &input.vis; 287 | let name = &input.ident; 288 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 289 | 290 | let fields = fields(input)?; 291 | let from = only_field_ty(fields)?; 292 | let trivial = trivial_fields(fields)?; 293 | 294 | let assert_trivial_fields = if !trivial.is_empty() { 295 | Some(quote! { 296 | fn __static_assert() { 297 | if false { 298 | #( 299 | ::ref_cast::__private::assert_trivial::<#trivial>(); 300 | )* 301 | } 302 | } 303 | }) 304 | } else { 305 | None 306 | }; 307 | 308 | Ok(quote! { 309 | const _: () = { 310 | #[non_exhaustive] 311 | #vis struct RefCastCurrentCrate {} 312 | 313 | unsafe impl #impl_generics ::ref_cast::__private::RefCastCustom<#from> for #name #ty_generics #where_clause { 314 | type CurrentCrate = RefCastCurrentCrate; 315 | #assert_trivial_fields 316 | } 317 | }; 318 | }) 319 | } 320 | 321 | fn expand_function_body(function: Function) -> TokenStream2 { 322 | let Function { 323 | attrs, 324 | vis, 325 | constness, 326 | asyncness, 327 | unsafety, 328 | abi, 329 | fn_token, 330 | ident, 331 | generics, 332 | paren_token, 333 | arg, 334 | colon_token, 335 | from_type, 336 | arrow_token, 337 | to_type, 338 | semi_token, 339 | } = function; 340 | 341 | let args = quote_spanned! {paren_token.span=> 342 | (#arg #colon_token #from_type) 343 | }; 344 | 345 | let allow_unused_unsafe = if unsafety.is_some() { 346 | Some(quote!(#[allow(unused_unsafe)])) 347 | } else { 348 | None 349 | }; 350 | 351 | let mut inline_attr = Some(quote!(#[inline])); 352 | for attr in &attrs { 353 | if attr.path().is_ident("inline") { 354 | inline_attr = None; 355 | break; 356 | } 357 | } 358 | 359 | // Apply a macro-generated span to the "unsafe" token for the unsafe block. 360 | // This is instead of reusing the caller's function signature's #unsafety 361 | // across both the generated function signature and generated unsafe block, 362 | // and instead of using `semi_token.span` like for the rest of the generated 363 | // code below, both of which would cause `forbid(unsafe_code)` located in 364 | // the caller to reject the expanded code. 365 | let macro_generated_unsafe = quote!(unsafe); 366 | 367 | quote_spanned! {semi_token.span=> 368 | #(#attrs)* 369 | #inline_attr 370 | #vis #constness #asyncness #unsafety #abi 371 | #fn_token #ident #generics #args #arrow_token #to_type { 372 | // check lifetime 373 | let _ = || { 374 | ::ref_cast::__private::ref_cast_custom::<#from_type, #to_type>(#arg); 375 | }; 376 | 377 | // check same crate 378 | let _ = ::ref_cast::__private::CurrentCrate::<#from_type, #to_type> {}; 379 | 380 | #allow_unused_unsafe // in case they are building with deny(unsafe_op_in_unsafe_fn) 381 | #[allow(clippy::transmute_ptr_to_ptr)] 382 | #macro_generated_unsafe { 383 | ::ref_cast::__private::transmute::<#from_type, #to_type>(#arg) 384 | } 385 | } 386 | } 387 | } 388 | 389 | fn check_repr(input: &DeriveInput) -> Result<()> { 390 | let mut has_repr = false; 391 | let mut errors = None; 392 | let mut push_error = |error| match &mut errors { 393 | Some(errors) => Error::combine(errors, error), 394 | None => errors = Some(error), 395 | }; 396 | 397 | for attr in &input.attrs { 398 | if attr.path().is_ident("repr") { 399 | if let Err(error) = attr.parse_args_with(|input: ParseStream| { 400 | while !input.is_empty() { 401 | let path = input.call(Path::parse_mod_style)?; 402 | if path.is_ident("transparent") || path.is_ident("C") { 403 | has_repr = true; 404 | } else if path.is_ident("packed") { 405 | // ignore 406 | } else { 407 | let meta_item_span = if input.peek(token::Paren) { 408 | let group: TokenTree = input.parse()?; 409 | quote!(#path #group) 410 | } else if input.peek(Token![=]) { 411 | let eq_token: Token![=] = input.parse()?; 412 | let value: Expr = input.parse()?; 413 | quote!(#path #eq_token #value) 414 | } else { 415 | quote!(#path) 416 | }; 417 | let msg = if path.is_ident("align") { 418 | "aligned repr on struct that implements RefCast is not supported" 419 | } else { 420 | "unrecognized repr on struct that implements RefCast" 421 | }; 422 | push_error(Error::new_spanned(meta_item_span, msg)); 423 | } 424 | if !input.is_empty() { 425 | input.parse::()?; 426 | } 427 | } 428 | Ok(()) 429 | }) { 430 | push_error(error); 431 | } 432 | } 433 | } 434 | 435 | if !has_repr { 436 | let mut requires_repr = Error::new( 437 | Span::call_site(), 438 | "RefCast trait requires #[repr(transparent)]", 439 | ); 440 | if let Some(errors) = errors { 441 | requires_repr.combine(errors); 442 | } 443 | errors = Some(requires_repr); 444 | } 445 | 446 | match errors { 447 | None => Ok(()), 448 | Some(errors) => Err(errors), 449 | } 450 | } 451 | 452 | type Fields = Punctuated; 453 | 454 | fn fields(input: &DeriveInput) -> Result<&Fields> { 455 | use syn::Fields; 456 | 457 | match &input.data { 458 | Data::Struct(data) => match &data.fields { 459 | Fields::Named(fields) => Ok(&fields.named), 460 | Fields::Unnamed(fields) => Ok(&fields.unnamed), 461 | Fields::Unit => Err(Error::new( 462 | Span::call_site(), 463 | "RefCast does not support unit structs", 464 | )), 465 | }, 466 | Data::Enum(_) => Err(Error::new( 467 | Span::call_site(), 468 | "RefCast does not support enums", 469 | )), 470 | Data::Union(_) => Err(Error::new( 471 | Span::call_site(), 472 | "RefCast does not support unions", 473 | )), 474 | } 475 | } 476 | 477 | fn only_field_ty(fields: &Fields) -> Result<&Type> { 478 | let is_trivial = decide_trivial(fields)?; 479 | let mut only_field = None; 480 | 481 | for field in fields { 482 | if !is_trivial(field)? { 483 | if only_field.take().is_some() { 484 | break; 485 | } 486 | only_field = Some(&field.ty); 487 | } 488 | } 489 | 490 | only_field.ok_or_else(|| { 491 | Error::new( 492 | Span::call_site(), 493 | "RefCast requires a struct with a single field", 494 | ) 495 | }) 496 | } 497 | 498 | fn trivial_fields(fields: &Fields) -> Result> { 499 | let is_trivial = decide_trivial(fields)?; 500 | let mut trivial = Vec::new(); 501 | 502 | for field in fields { 503 | if is_trivial(field)? { 504 | trivial.push(&field.ty); 505 | } 506 | } 507 | 508 | Ok(trivial) 509 | } 510 | 511 | fn decide_trivial(fields: &Fields) -> Result Result> { 512 | for field in fields { 513 | if is_explicit_trivial(field)? { 514 | return Ok(is_explicit_trivial); 515 | } 516 | } 517 | Ok(is_implicit_trivial) 518 | } 519 | 520 | #[allow(clippy::unnecessary_wraps)] // match signature of is_explicit_trivial 521 | fn is_implicit_trivial(field: &Field) -> Result { 522 | match &field.ty { 523 | Type::Tuple(ty) => Ok(ty.elems.is_empty()), 524 | Type::Path(ty) => { 525 | let ident = &ty.path.segments.last().unwrap().ident; 526 | Ok(ident == "PhantomData" || ident == "PhantomPinned") 527 | } 528 | _ => Ok(false), 529 | } 530 | } 531 | 532 | fn is_explicit_trivial(field: &Field) -> Result { 533 | for attr in &field.attrs { 534 | if attr.path().is_ident("trivial") { 535 | attr.meta.require_path_only()?; 536 | return Ok(true); 537 | } 538 | } 539 | Ok(false) 540 | } 541 | -------------------------------------------------------------------------------- /src/custom.rs: -------------------------------------------------------------------------------- 1 | // Not public API. Use #[derive(RefCastCustom)] and #[ref_cast_custom]. 2 | #[doc(hidden)] 3 | pub unsafe trait RefCastCustom { 4 | type CurrentCrate; 5 | fn __static_assert() {} 6 | } 7 | 8 | #[doc(hidden)] 9 | pub unsafe trait RefCastOkay: Sealed { 10 | type CurrentCrate; 11 | type Target: ?Sized; 12 | } 13 | 14 | unsafe impl<'a, From, To> RefCastOkay<&'a From> for &'a To 15 | where 16 | From: ?Sized, 17 | To: ?Sized + RefCastCustom, 18 | { 19 | type CurrentCrate = To::CurrentCrate; 20 | type Target = To; 21 | } 22 | 23 | unsafe impl<'a, From, To> RefCastOkay<&'a mut From> for &'a mut To 24 | where 25 | From: ?Sized, 26 | To: ?Sized + RefCastCustom, 27 | { 28 | type CurrentCrate = To::CurrentCrate; 29 | type Target = To; 30 | } 31 | 32 | #[doc(hidden)] 33 | pub trait Sealed {} 34 | 35 | impl<'a, From, To> Sealed<&'a From> for &'a To 36 | where 37 | From: ?Sized, 38 | To: ?Sized + RefCastCustom, 39 | { 40 | } 41 | 42 | impl<'a, From, To> Sealed<&'a mut From> for &'a mut To 43 | where 44 | From: ?Sized, 45 | To: ?Sized + RefCastCustom, 46 | { 47 | } 48 | 49 | #[doc(hidden)] 50 | pub type CurrentCrate = >::CurrentCrate; 51 | 52 | #[doc(hidden)] 53 | pub fn ref_cast_custom(_arg: From) 54 | where 55 | To: RefCastOkay, 56 | { 57 | } 58 | -------------------------------------------------------------------------------- /src/layout.rs: -------------------------------------------------------------------------------- 1 | use core::mem; 2 | 3 | #[doc(hidden)] 4 | pub struct Layout(T); 5 | 6 | #[doc(hidden)] 7 | pub trait LayoutUnsized { 8 | const SIZE: usize = usize::MAX; 9 | const ALIGN: usize = usize::MAX; 10 | } 11 | 12 | impl LayoutUnsized for Layout {} 13 | 14 | impl Layout { 15 | pub const SIZE: usize = mem::size_of::(); 16 | pub const ALIGN: usize = mem::align_of::(); 17 | } 18 | 19 | #[doc(hidden)] 20 | #[inline] 21 | pub fn assert_layout( 22 | name: &'static str, 23 | outer_size: usize, 24 | inner_size: usize, 25 | outer_align: usize, 26 | inner_align: usize, 27 | ) { 28 | if outer_size != inner_size { 29 | #[cfg(no_intrinsic_type_name)] 30 | panic!( 31 | "unexpected size in cast to {}: {} != {}", 32 | name, outer_size, inner_size, 33 | ); 34 | #[cfg(not(no_intrinsic_type_name))] 35 | panic!( 36 | "unexpected size in cast from {} to {}: {} != {}", 37 | core::any::type_name::(), 38 | core::any::type_name::(), 39 | inner_size, 40 | outer_size, 41 | ); 42 | } 43 | if outer_align != inner_align { 44 | #[cfg(no_intrinsic_type_name)] 45 | panic!( 46 | "unexpected alignment in cast to {}: {} != {}", 47 | name, outer_align, inner_align, 48 | ); 49 | #[cfg(not(no_intrinsic_type_name))] 50 | panic!( 51 | "unexpected alignment in cast from {} to {}: {} != {}", 52 | core::any::type_name::(), 53 | core::any::type_name::(), 54 | inner_align, 55 | outer_align, 56 | ); 57 | } 58 | #[cfg(not(no_intrinsic_type_name))] 59 | let _ = name; 60 | } 61 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/ref-cast) [![crates-io]](https://crates.io/crates/ref-cast) [![docs-rs]](https://docs.rs/ref-cast) 2 | //! 3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 | //! 7 | //!
8 | //! 9 | //! This crate provides a derive macro for generating safe conversions from `&T` 10 | //! to `&U` where the struct `U` contains a single field of type `T`. 11 | //! 12 | //! # Basic example 13 | //! 14 | //! ``` 15 | //! use ref_cast::RefCast; 16 | //! 17 | //! #[derive(RefCast)] 18 | //! #[repr(transparent)] 19 | //! struct U(String); 20 | //! 21 | //! fn main() { 22 | //! let s = String::new(); 23 | //! 24 | //! // Safely cast from `&String` to `&U`. 25 | //! let u = U::ref_cast(&s); 26 | //! } 27 | //! ``` 28 | //! 29 | //! Note that `#[repr(transparent)]` is required in order for the conversion to 30 | //! be sound. The derive macro will refuse to compile if that is not present. 31 | //! 32 | //! # Realistic example 33 | //! 34 | //! Suppose we have a multidimensional array represented in a flat buffer in 35 | //! row-major order for performance reasons, but we want to expose an indexing 36 | //! operation that works in column-major order because it is more intuitive in 37 | //! the context of our application. 38 | //! 39 | //! ``` 40 | //! const MAP_WIDTH: usize = 4; 41 | //! 42 | //! struct Tile(u8); 43 | //! 44 | //! struct TileMap { 45 | //! storage: Vec, 46 | //! } 47 | //! 48 | //! // `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`. 49 | //! ``` 50 | //! 51 | //! The signature of the [`Index`] trait in Rust is such that the output is 52 | //! forced to be borrowed from the type being indexed. So something like the 53 | //! following is not going to work. 54 | //! 55 | //! [`Index`]: core::ops::Index 56 | //! 57 | //! ``` 58 | //! # const MAP_WIDTH: usize = 4; 59 | //! # 60 | //! # struct Tile(u8); 61 | //! # 62 | //! # struct TileMap { 63 | //! # storage: Vec, 64 | //! # } 65 | //! # 66 | //! struct Column<'a> { 67 | //! tilemap: &'a TileMap, 68 | //! x: usize, 69 | //! } 70 | //! 71 | //! # mod index1 { 72 | //! # use super::{TileMap, Column, MAP_WIDTH}; 73 | //! # 74 | //! # trait Index { 75 | //! # fn index(&self, idx: Idx) -> Column; 76 | //! # } 77 | //! # 78 | //! // Does not work! The output of Index must be a reference that is 79 | //! // borrowed from self. Here the type Column is not a reference. 80 | //! impl Index for TileMap { 81 | //! fn index(&self, x: usize) -> Column { 82 | //! assert!(x < MAP_WIDTH); 83 | //! Column { tilemap: self, x } 84 | //! } 85 | //! } 86 | //! # } 87 | //! 88 | //! # mod index2 { 89 | //! # use super::{Column, Tile, MAP_WIDTH}; 90 | //! # use std::ops::Index; 91 | //! # 92 | //! impl<'a> Index for Column<'a> { 93 | //! # type Output = Tile; 94 | //! fn index(&self, y: usize) -> &Tile { 95 | //! &self.tilemap.storage[y * MAP_WIDTH + self.x] 96 | //! } 97 | //! } 98 | //! # } 99 | //! # 100 | //! # fn main() {} 101 | //! ``` 102 | //! 103 | //! Here is a working approach using `RefCast`. 104 | //! 105 | //! ``` 106 | //! # use ref_cast::RefCast; 107 | //! # use std::ops::Index; 108 | //! # 109 | //! # const MAP_WIDTH: usize = 4; 110 | //! # 111 | //! # struct Tile(u8); 112 | //! # 113 | //! # struct TileMap { 114 | //! # storage: Vec, 115 | //! # } 116 | //! # 117 | //! #[derive(RefCast)] 118 | //! #[repr(transparent)] 119 | //! struct Strided([Tile]); 120 | //! 121 | //! // Implement `tilemap[x][y]` as `tilemap[x..][y * MAP_WIDTH]`. 122 | //! impl Index for TileMap { 123 | //! type Output = Strided; 124 | //! fn index(&self, x: usize) -> &Self::Output { 125 | //! assert!(x < MAP_WIDTH); 126 | //! Strided::ref_cast(&self.storage[x..]) 127 | //! } 128 | //! } 129 | //! 130 | //! impl Index for Strided { 131 | //! type Output = Tile; 132 | //! fn index(&self, y: usize) -> &Self::Output { 133 | //! &self.0[y * MAP_WIDTH] 134 | //! } 135 | //! } 136 | //! ``` 137 | 138 | #![doc(html_root_url = "https://docs.rs/ref-cast/1.0.24")] 139 | #![no_std] 140 | #![allow( 141 | clippy::extra_unused_type_parameters, 142 | clippy::let_underscore_untyped, 143 | clippy::manual_assert, 144 | clippy::missing_panics_doc, 145 | clippy::missing_safety_doc, 146 | clippy::module_name_repetitions, 147 | clippy::needless_doctest_main, 148 | clippy::needless_pass_by_value 149 | )] 150 | 151 | mod custom; 152 | mod layout; 153 | mod trivial; 154 | 155 | pub use ref_cast_impl::{ref_cast_custom, RefCast, RefCastCustom}; 156 | 157 | /// Safely cast `&T` to `&U` where the struct `U` contains a single field of 158 | /// type `T`. 159 | /// 160 | /// ``` 161 | /// # use ref_cast::RefCast; 162 | /// # 163 | /// // `&String` can be cast to `&U`. 164 | /// #[derive(RefCast)] 165 | /// #[repr(transparent)] 166 | /// struct U(String); 167 | /// 168 | /// // `&T` can be cast to `&V`. 169 | /// #[derive(RefCast)] 170 | /// #[repr(transparent)] 171 | /// struct V { 172 | /// t: T, 173 | /// } 174 | /// ``` 175 | /// 176 | /// See the [crate-level documentation][crate] for usage examples! 177 | pub trait RefCast { 178 | type From: ?Sized; 179 | fn ref_cast(from: &Self::From) -> &Self; 180 | fn ref_cast_mut(from: &mut Self::From) -> &mut Self; 181 | } 182 | 183 | // Not public API. 184 | #[doc(hidden)] 185 | pub mod __private { 186 | #[doc(hidden)] 187 | pub use crate::custom::{ref_cast_custom, CurrentCrate, RefCastCustom}; 188 | #[doc(hidden)] 189 | pub use crate::layout::{assert_layout, Layout, LayoutUnsized}; 190 | #[doc(hidden)] 191 | pub use crate::trivial::assert_trivial; 192 | #[doc(hidden)] 193 | pub use core::mem::transmute; 194 | } 195 | -------------------------------------------------------------------------------- /src/trivial.rs: -------------------------------------------------------------------------------- 1 | use core::marker::PhantomData; 2 | #[cfg(not(no_phantom_pinned))] 3 | use core::marker::PhantomPinned; 4 | 5 | #[doc(hidden)] 6 | pub trait Trivial {} 7 | 8 | impl Trivial for () {} 9 | impl Trivial for PhantomData {} 10 | 11 | #[cfg(not(no_phantom_pinned))] 12 | impl Trivial for PhantomPinned {} 13 | 14 | #[doc(hidden)] 15 | pub fn assert_trivial() {} 16 | -------------------------------------------------------------------------------- /tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore = "requires nightly")] 2 | #[cfg_attr(miri, ignore = "incompatible with miri")] 3 | #[test] 4 | fn ui() { 5 | let t = trybuild::TestCases::new(); 6 | t.compile_fail("tests/ui/*.rs"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/helper/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ref-cast-test-suite" 3 | authors = ["David Tolnay "] 4 | version = "0.0.0" 5 | edition = "2021" 6 | publish = false 7 | 8 | [lib] 9 | path = "lib.rs" 10 | 11 | [dependencies] 12 | ref-cast = "1" 13 | -------------------------------------------------------------------------------- /tests/helper/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | 3 | use ref_cast::RefCastCustom; 4 | 5 | #[derive(RefCastCustom)] 6 | #[repr(transparent)] 7 | pub struct Struct(str); 8 | -------------------------------------------------------------------------------- /tests/test_custom.rs: -------------------------------------------------------------------------------- 1 | #[forbid(unsafe_code)] 2 | mod forbid_unsafe { 3 | use ref_cast::{ref_cast_custom, RefCastCustom}; 4 | 5 | #[derive(RefCastCustom)] 6 | #[repr(transparent)] 7 | pub struct Custom(#[allow(dead_code)] str); 8 | 9 | impl Custom { 10 | #[ref_cast_custom] 11 | pub fn new(s: &str) -> &Custom; 12 | } 13 | } 14 | 15 | #[test] 16 | fn test_forbid_unsafe() { 17 | forbid_unsafe::Custom::new("..."); 18 | } 19 | -------------------------------------------------------------------------------- /tests/test_trivial.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::manual_non_exhaustive)] 2 | 3 | use ref_cast::RefCast; 4 | use std::marker::PhantomData; 5 | 6 | type Marker = PhantomData; 7 | 8 | #[derive(RefCast)] 9 | #[repr(transparent)] 10 | pub struct ImplicitUnit { 11 | pub value: usize, 12 | _private: (), 13 | } 14 | 15 | #[derive(RefCast)] 16 | #[repr(transparent)] 17 | pub struct ImplicitPhantomData { 18 | pub value: T, 19 | pub marker: PhantomData, 20 | } 21 | 22 | #[derive(RefCast)] 23 | #[repr(transparent)] 24 | pub struct ExplicitTrivial { 25 | pub value: usize, 26 | #[trivial] 27 | pub marker: Marker, 28 | } 29 | 30 | #[derive(RefCast)] 31 | #[repr(C)] 32 | pub struct Override { 33 | #[trivial] 34 | pub first: PhantomData, 35 | pub second: PhantomData, 36 | } 37 | 38 | #[derive(RefCast)] 39 | #[repr(transparent)] 40 | pub struct Unsized<'a> { 41 | pub marker: PhantomData<&'a str>, 42 | pub value: str, 43 | } 44 | 45 | #[test] 46 | fn test_trivial() { 47 | ImplicitUnit::ref_cast(&0); 48 | ImplicitPhantomData::ref_cast(&0); 49 | ExplicitTrivial::ref_cast(&0); 50 | Override::::ref_cast(&PhantomData::); 51 | Unsized::ref_cast("..."); 52 | } 53 | -------------------------------------------------------------------------------- /tests/ui/cross-crate.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::ref_cast_custom; 2 | use ref_cast_test_suite::Struct; 3 | 4 | #[ref_cast_custom] 5 | fn ref_cast(s: &str) -> &Struct; 6 | 7 | #[ref_cast_custom] 8 | fn ref_cast_mut(s: &mut str) -> &mut Struct; 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /tests/ui/cross-crate.stderr: -------------------------------------------------------------------------------- 1 | error[E0639]: cannot create non-exhaustive struct using struct expression 2 | --> tests/ui/cross-crate.rs:5:32 3 | | 4 | 5 | fn ref_cast(s: &str) -> &Struct; 5 | | ^ 6 | 7 | error[E0639]: cannot create non-exhaustive struct using struct expression 8 | --> tests/ui/cross-crate.rs:8:44 9 | | 10 | 8 | fn ref_cast_mut(s: &mut str) -> &mut Struct; 11 | | ^ 12 | -------------------------------------------------------------------------------- /tests/ui/dst-before-trivial.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::RefCast; 2 | use std::marker::PhantomData; 3 | 4 | #[derive(RefCast)] 5 | #[repr(transparent)] 6 | struct Bytes<'arena> { 7 | bytes: [u8], 8 | #[trivial] 9 | marker: PhantomData<&'arena ()>, 10 | } 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /tests/ui/dst-before-trivial.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the size for values of type `[u8]` cannot be known at compilation time 2 | --> tests/ui/dst-before-trivial.rs:7:12 3 | | 4 | 7 | bytes: [u8], 5 | | ^^^^ doesn't have a size known at compile-time 6 | | 7 | = help: the trait `Sized` is not implemented for `[u8]` 8 | = note: only the last field of a struct may have a dynamically sized type 9 | = help: change the field's type to have a statically known size 10 | help: borrowed types always have a statically known size 11 | | 12 | 7 | bytes: &[u8], 13 | | + 14 | help: the `Box` type always has a statically known size and allocates its contents in the heap 15 | | 16 | 7 | bytes: Box<[u8]>, 17 | | ++++ + 18 | -------------------------------------------------------------------------------- /tests/ui/extra-arg.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::{ref_cast_custom, RefCastCustom}; 2 | 3 | #[derive(RefCastCustom)] 4 | #[repr(transparent)] 5 | pub struct Thing(String); 6 | 7 | impl Thing { 8 | #[ref_cast_custom] 9 | pub fn ref_cast(s: &String, wat: i32) -> &Self; 10 | } 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /tests/ui/extra-arg.stderr: -------------------------------------------------------------------------------- 1 | error: ref_cast_custom function is required to have a single argument 2 | --> tests/ui/extra-arg.rs:9:33 3 | | 4 | 9 | pub fn ref_cast(s: &String, wat: i32) -> &Self; 5 | | ^^^^^^^^ 6 | 7 | error: associated function in `impl` without body 8 | --> tests/ui/extra-arg.rs:9:5 9 | | 10 | 9 | pub fn ref_cast(s: &String, wat: i32) -> &Self; 11 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- 12 | | | 13 | | help: provide a definition for the function: `{ }` 14 | -------------------------------------------------------------------------------- /tests/ui/function-body.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::{ref_cast_custom, RefCastCustom}; 2 | 3 | #[derive(RefCastCustom)] 4 | #[repr(transparent)] 5 | pub struct Thing(String); 6 | 7 | impl Thing { 8 | #[ref_cast_custom] 9 | pub fn ref_cast(s: &String) -> &Self {} 10 | } 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /tests/ui/function-body.stderr: -------------------------------------------------------------------------------- 1 | error: expected `;` 2 | --> tests/ui/function-body.rs:9:42 3 | | 4 | 9 | pub fn ref_cast(s: &String) -> &Self {} 5 | | ^ 6 | 7 | error[E0308]: mismatched types 8 | --> tests/ui/function-body.rs:9:36 9 | | 10 | 9 | pub fn ref_cast(s: &String) -> &Self {} 11 | | -------- ^^^^^ expected `&Thing`, found `()` 12 | | | 13 | | implicitly returns `()` as its body has no tail or `return` expression 14 | -------------------------------------------------------------------------------- /tests/ui/impl-trait.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::{ref_cast_custom, RefCastCustom}; 2 | 3 | #[derive(RefCastCustom)] 4 | #[repr(transparent)] 5 | pub struct Thing(str); 6 | 7 | impl Thing { 8 | #[ref_cast_custom] 9 | pub fn ref_cast(s: impl AsRef) -> &Self; 10 | 11 | #[ref_cast_custom] 12 | pub fn ref_cast2(s: &impl AsRef) -> &Self; 13 | } 14 | 15 | fn main() {} 16 | -------------------------------------------------------------------------------- /tests/ui/impl-trait.stderr: -------------------------------------------------------------------------------- 1 | error[E0106]: missing lifetime specifier 2 | --> tests/ui/impl-trait.rs:9:44 3 | | 4 | 9 | pub fn ref_cast(s: impl AsRef) -> &Self; 5 | | ^ expected named lifetime parameter 6 | | 7 | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from 8 | help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static` 9 | | 10 | 9 | pub fn ref_cast(s: impl AsRef) -> &'static Self; 11 | | +++++++ 12 | help: consider introducing a named lifetime parameter 13 | | 14 | 9 | pub fn ref_cast<'a>(s: impl AsRef) -> &'a Self; 15 | | ++++ ++ 16 | 17 | error[E0562]: `impl Trait` is not allowed in paths 18 | --> tests/ui/impl-trait.rs:9:24 19 | | 20 | 9 | pub fn ref_cast(s: impl AsRef) -> &Self; 21 | | ^^^^^^^^^^^^^^^ 22 | | 23 | = note: `impl Trait` is only allowed in arguments and return types of functions and methods 24 | 25 | error[E0562]: `impl Trait` is not allowed in paths 26 | --> tests/ui/impl-trait.rs:12:26 27 | | 28 | 12 | pub fn ref_cast2(s: &impl AsRef) -> &Self; 29 | | ^^^^^^^^^^^^^^^ 30 | | 31 | = note: `impl Trait` is only allowed in arguments and return types of functions and methods 32 | -------------------------------------------------------------------------------- /tests/ui/no-custom.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::ref_cast_custom; 2 | 3 | #[repr(transparent)] 4 | pub struct Thing(String); 5 | 6 | impl Thing { 7 | #[ref_cast_custom] 8 | pub fn ref_cast(s: &String) -> &Self; 9 | } 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /tests/ui/no-custom.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `&Thing: ref_cast::custom::RefCastOkay<&String>` is not satisfied 2 | --> tests/ui/no-custom.rs:8:36 3 | | 4 | 8 | pub fn ref_cast(s: &String) -> &Self; 5 | | ^^^^^ the trait `RefCastCustom` is not implemented for `Thing` 6 | | 7 | = help: the following other types implement trait `ref_cast::custom::RefCastOkay`: 8 | `&'a To` implements `ref_cast::custom::RefCastOkay<&'a From>` 9 | `&'a mut To` implements `ref_cast::custom::RefCastOkay<&'a mut From>` 10 | = note: required for `&Thing` to implement `ref_cast::custom::RefCastOkay<&String>` 11 | note: required by a bound in `ref_cast_custom` 12 | --> src/custom.rs 13 | | 14 | | pub fn ref_cast_custom(_arg: From) 15 | | --------------- required by a bound in this function 16 | | where 17 | | To: RefCastOkay, 18 | | ^^^^^^^^^^^^^^^^^ required by this bound in `ref_cast_custom` 19 | 20 | error[E0071]: expected struct, variant or union type, found inferred type 21 | --> tests/ui/no-custom.rs:8:41 22 | | 23 | 8 | pub fn ref_cast(s: &String) -> &Self; 24 | | ^ not a struct 25 | 26 | error[E0277]: the trait bound `Thing: RefCastCustom` is not satisfied 27 | --> tests/ui/no-custom.rs:8:41 28 | | 29 | 8 | pub fn ref_cast(s: &String) -> &Self; 30 | | ^ the trait `RefCastCustom` is not implemented for `Thing` 31 | | 32 | = help: the following other types implement trait `ref_cast::custom::RefCastOkay`: 33 | `&'a To` implements `ref_cast::custom::RefCastOkay<&'a From>` 34 | `&'a mut To` implements `ref_cast::custom::RefCastOkay<&'a mut From>` 35 | = note: required for `&Thing` to implement `ref_cast::custom::RefCastOkay<&String>` 36 | -------------------------------------------------------------------------------- /tests/ui/no-repr.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::RefCast; 2 | 3 | #[derive(RefCast)] 4 | struct Test { 5 | s: String, 6 | } 7 | 8 | fn main() {} 9 | -------------------------------------------------------------------------------- /tests/ui/no-repr.stderr: -------------------------------------------------------------------------------- 1 | error: RefCast trait requires #[repr(transparent)] 2 | --> tests/ui/no-repr.rs:3:10 3 | | 4 | 3 | #[derive(RefCast)] 5 | | ^^^^^^^ 6 | | 7 | = note: this error originates in the derive macro `RefCast` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/ui/not-trivial.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::RefCast; 2 | 3 | #[derive(RefCast)] 4 | #[repr(C)] 5 | struct Test { 6 | one: String, 7 | #[trivial] 8 | two: String, 9 | } 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /tests/ui/not-trivial.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `String: ref_cast::trivial::Trivial` is not satisfied 2 | --> tests/ui/not-trivial.rs:8:10 3 | | 4 | 8 | two: String, 5 | | ^^^^^^ the trait `ref_cast::trivial::Trivial` is not implemented for `String` 6 | | 7 | = help: the following other types implement trait `ref_cast::trivial::Trivial`: 8 | () 9 | PhantomData 10 | PhantomPinned 11 | note: required by a bound in `assert_trivial` 12 | --> src/trivial.rs 13 | | 14 | | pub fn assert_trivial() {} 15 | | ^^^^^^^ required by this bound in `assert_trivial` 16 | -------------------------------------------------------------------------------- /tests/ui/private.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::{ref_cast_custom, RefCast, RefCastCustom}; 2 | 3 | #[derive(RefCast, RefCastCustom)] 4 | #[repr(transparent)] 5 | pub struct Public { 6 | private: Private, 7 | } 8 | 9 | struct Private; 10 | 11 | impl Public { 12 | #[ref_cast_custom] 13 | fn ref_cast(private: &Private) -> &Public; 14 | 15 | #[ref_cast_custom] 16 | fn ref_cast_mut(private: &mut Private) -> &mut Public; 17 | } 18 | 19 | fn main() {} 20 | -------------------------------------------------------------------------------- /tests/ui/private.stderr: -------------------------------------------------------------------------------- 1 | error[E0446]: private type `Private` in public interface 2 | --> tests/ui/private.rs:3:10 3 | | 4 | 3 | #[derive(RefCast, RefCastCustom)] 5 | | ^^^^^^^ can't leak private type 6 | ... 7 | 9 | struct Private; 8 | | -------------- `Private` declared as private 9 | | 10 | = note: this error originates in the derive macro `RefCast` (in Nightly builds, run with -Z macro-backtrace for more info) 11 | -------------------------------------------------------------------------------- /tests/ui/repr-align.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::RefCast; 2 | 3 | #[derive(RefCast)] 4 | #[repr(align(2), C, align = "2")] 5 | struct Test { 6 | s: String, 7 | } 8 | 9 | fn main() {} 10 | -------------------------------------------------------------------------------- /tests/ui/repr-align.stderr: -------------------------------------------------------------------------------- 1 | error: aligned repr on struct that implements RefCast is not supported 2 | --> tests/ui/repr-align.rs:4:8 3 | | 4 | 4 | #[repr(align(2), C, align = "2")] 5 | | ^^^^^^^^ 6 | 7 | error: aligned repr on struct that implements RefCast is not supported 8 | --> tests/ui/repr-align.rs:4:21 9 | | 10 | 4 | #[repr(align(2), C, align = "2")] 11 | | ^^^^^^^^^^^ 12 | 13 | error[E0693]: incorrect `repr(align)` attribute format 14 | --> tests/ui/repr-align.rs:4:21 15 | | 16 | 4 | #[repr(align(2), C, align = "2")] 17 | | ^^^^^^^^^^^ help: use parentheses instead: `align(2)` 18 | -------------------------------------------------------------------------------- /tests/ui/short-lifetime.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::{ref_cast_custom, RefCastCustom}; 2 | 3 | #[derive(RefCastCustom)] 4 | #[repr(transparent)] 5 | pub struct Thing(String); 6 | 7 | impl Thing { 8 | #[ref_cast_custom] 9 | pub fn ref_cast<'a>(s: &String) -> &'a Self; 10 | } 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /tests/ui/short-lifetime.stderr: -------------------------------------------------------------------------------- 1 | error[E0621]: explicit lifetime required in the type of `s` 2 | --> tests/ui/short-lifetime.rs:9:48 3 | | 4 | 9 | pub fn ref_cast<'a>(s: &String) -> &'a Self; 5 | | ------- ^ lifetime `'a` required 6 | | | 7 | | help: add explicit lifetime `'a` to the type of `s`: `&'a String` 8 | -------------------------------------------------------------------------------- /tests/ui/unrecognized-repr.rs: -------------------------------------------------------------------------------- 1 | use ref_cast::RefCast; 2 | 3 | #[derive(RefCast)] 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 5 | struct Test { 6 | s: String, 7 | } 8 | 9 | fn main() {} 10 | -------------------------------------------------------------------------------- /tests/ui/unrecognized-repr.stderr: -------------------------------------------------------------------------------- 1 | error: unrecognized repr on struct that implements RefCast 2 | --> tests/ui/unrecognized-repr.rs:4:19 3 | | 4 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 5 | | ^^^^^ 6 | 7 | error: unrecognized repr on struct that implements RefCast 8 | --> tests/ui/unrecognized-repr.rs:4:26 9 | | 10 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 11 | | ^^^^^^^^ 12 | 13 | error: unrecognized repr on struct that implements RefCast 14 | --> tests/ui/unrecognized-repr.rs:4:36 15 | | 16 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 17 | | ^^^^^^^^^^^ 18 | 19 | error[E0552]: invalid representation hint: `usize` does not take a parenthesized argument list 20 | --> tests/ui/unrecognized-repr.rs:4:26 21 | | 22 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 23 | | ^^^^^^^^ 24 | 25 | error[E0552]: invalid representation hint: `usize` does not take a value 26 | --> tests/ui/unrecognized-repr.rs:4:36 27 | | 28 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 29 | | ^^^^^^^^^^^ 30 | 31 | error[E0517]: attribute should be applied to an enum 32 | --> tests/ui/unrecognized-repr.rs:4:19 33 | | 34 | 4 | #[repr(packed, C, usize, usize(0), usize = "0")] 35 | | ^^^^^ 36 | 5 | / struct Test { 37 | 6 | | s: String, 38 | 7 | | } 39 | | |_- not an enum 40 | --------------------------------------------------------------------------------