├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── dependabot-auto-merge.yml │ └── release.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── internal.rs ├── lib.rs ├── lifetime_free.rs └── utils.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "00:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | on: 3 | push: 4 | branches: [master] 5 | pull_request: 6 | 7 | jobs: 8 | test: 9 | uses: sagebind/workflows/.github/workflows/rust-ci.yml@v1 10 | with: 11 | msrv: "1.54" 12 | test-release: true 13 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: auto-merge 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | auto-merge: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: ahmadnassri/action-dependabot-auto-merge@v2 12 | with: 13 | target: patch 14 | github-token: ${{ secrets.GH_PAT }} 15 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | with: 12 | submodules: true 13 | 14 | - name: Publish to crates.io 15 | run: cargo publish --token "${CARGO_TOKEN}" --no-verify 16 | env: 17 | CARGO_TOKEN: ${{ secrets.CARGO_TOKEN }} 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "castaway" 7 | version = "0.2.3" 8 | dependencies = [ 9 | "paste", 10 | "rustversion", 11 | ] 12 | 13 | [[package]] 14 | name = "paste" 15 | version = "1.0.15" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" 18 | 19 | [[package]] 20 | name = "rustversion" 21 | version = "1.0.19" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "castaway" 3 | version = "0.2.3" 4 | description = "Safe, zero-cost downcasting for limited compile-time specialization." 5 | authors = ["Stephen M. Coakley "] 6 | license = "MIT" 7 | keywords = ["specialization", "specialize", "cast"] 8 | categories = ["no-std", "rust-patterns"] 9 | repository = "https://github.com/sagebind/castaway" 10 | edition = "2018" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | 15 | [features] 16 | default = ["std"] 17 | std = ["alloc"] 18 | alloc = [] 19 | 20 | [dependencies] 21 | rustversion = "1" 22 | 23 | [dev-dependencies] 24 | paste = "1" 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Stephen M. Coakley 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Castaway 2 | 3 | Safe, zero-cost downcasting for limited compile-time specialization. 4 | 5 | [![Crates.io](https://img.shields.io/crates/v/castaway.svg)](https://crates.io/crates/castaway) 6 | [![Documentation](https://docs.rs/castaway/badge.svg)][documentation] 7 | [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) 8 | [![Minimum supported Rust version](https://img.shields.io/badge/rustc-1.38+-yellow.svg)](#minimum-supported-rust-version) 9 | [![Build](https://github.com/sagebind/castaway/workflows/ci/badge.svg)](https://github.com/sagebind/castaway/actions) 10 | 11 | ## [Documentation] 12 | 13 | Please check out the [documentation] for details how to use Castaway and its limitations. To get you started, here is a really simple, complete example of Castaway in action: 14 | 15 | ```rust 16 | use std::fmt::Display; 17 | use castaway::cast; 18 | 19 | /// Like `std::string::ToString`, but with an optimization when `Self` is 20 | /// already a `String`. 21 | /// 22 | /// Since the standard library is allowed to use unstable features, 23 | /// `ToString` already has this optimization using the `specialization` 24 | /// feature, but this isn't something normal crates can do. 25 | pub trait FastToString { 26 | fn fast_to_string(&self) -> String; 27 | } 28 | 29 | impl FastToString for T { 30 | fn fast_to_string(&self) -> String { 31 | // If `T` is already a string, then take a different code path. 32 | // After monomorphization, this check will be completely optimized 33 | // away. 34 | if let Ok(string) = cast!(self, &String) { 35 | // Don't invoke the std::fmt machinery, just clone the string. 36 | string.to_owned() 37 | } else { 38 | // Make use of `Display` for any other `T`. 39 | format!("{}", self) 40 | } 41 | } 42 | } 43 | 44 | fn main() { 45 | println!("specialized: {}", String::from("hello").fast_to_string()); 46 | println!("default: {}", "hello".fast_to_string()); 47 | } 48 | ``` 49 | 50 | ## Minimum supported Rust version 51 | 52 | The minimum supported Rust version (or _MSRV_) for Castaway is **stable Rust 1.38 or greater**, meaning we only guarantee that Castaway will compile if you use a rustc version of at least 1.38. This version is explicitly tested in CI and may only be bumped in new minor versions. Any changes to the supported minimum version will be called out in the release notes. 53 | 54 | ## What is this? 55 | 56 | This is an experimental library that implements zero-cost downcasting of types that works on stable Rust. It began as a thought experiment after I had read [this pull request](https://github.com/hyperium/http/pull/369) and wondered if it would be possible to alter the behavior of a generic function based on a concrete type without using trait objects. I stumbled on the "zero-cost"-ness of my findings by accident while playing around with different implementations and examining the generated assembly of example programs. 57 | 58 | The API is somewhat similar to [`Any`](https://doc.rust-lang.org/stable/std/any/trait.Any.html) in the standard library, but Castaway is instead focused on ergonomic compile-time downcasting rather than runtime downcasting. Unlike `Any`, Castaway _does_ support safely casting non-`'static` references in limited scenarios. If you need to store one or more `Box` objects implementing some trait with the option of downcasting, you are much better off using `Any`. 59 | 60 | ## License 61 | 62 | This project's source code and documentation is licensed under the MIT license. See the [LICENSE](LICENSE) file for details. 63 | 64 | 65 | [documentation]: https://docs.rs/castaway 66 | -------------------------------------------------------------------------------- /src/internal.rs: -------------------------------------------------------------------------------- 1 | //! This module contains helper traits and types used by the public-facing 2 | //! macros. Most are public so they can be accessed by the expanded macro code, 3 | //! but are not meant to be used by users directly and do not have a stable API. 4 | //! 5 | //! The various `TryCast*` traits in this module are referenced in macro 6 | //! expansions and expose multiple possible implementations of casting with 7 | //! different generic bounds. The compiler chooses which trait to use to fulfill 8 | //! the cast based on the trait bounds using the _autoderef_ trick. 9 | 10 | use crate::{ 11 | lifetime_free::LifetimeFree, 12 | utils::{transmute_unchecked, type_eq, type_eq_non_static}, 13 | }; 14 | use core::marker::PhantomData; 15 | 16 | /// A token struct used to capture a type without taking ownership of any 17 | /// values. Used to select a cast implementation in macros. 18 | pub struct CastToken(PhantomData); 19 | 20 | impl CastToken { 21 | /// Create a cast token for the given type of value. 22 | pub const fn of_val(_value: &T) -> Self { 23 | Self::of() 24 | } 25 | 26 | /// Create a new cast token of the specified type. 27 | pub const fn of() -> Self { 28 | Self(PhantomData) 29 | } 30 | } 31 | 32 | /// Supporting trait for autoderef specialization on mutable references to lifetime-free 33 | /// types. 34 | pub trait TryCastMutLifetimeFree<'a, T: ?Sized, U: LifetimeFree + ?Sized> { 35 | #[inline(always)] 36 | fn try_cast(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> { 37 | // SAFETY: See comments on safety in `TryCastLifetimeFree`. 38 | 39 | if type_eq_non_static::() { 40 | // Pointer casts are not allowed here since the compiler can't prove 41 | // that `&mut T` and `&mut U` have the same kind of associated 42 | // pointer data if they are fat pointers. But we know they are 43 | // identical, so we use a transmute. 44 | Ok(unsafe { transmute_unchecked::<&mut T, &mut U>(value) }) 45 | } else { 46 | Err(value) 47 | } 48 | } 49 | } 50 | 51 | impl<'a, T, U: LifetimeFree> TryCastMutLifetimeFree<'a, T, U> 52 | for &&&&&&&(CastToken<&'a mut T>, CastToken<&'a mut U>) 53 | { 54 | } 55 | 56 | /// Supporting trait for autoderef specialization on references to lifetime-free 57 | /// types. 58 | pub trait TryCastRefLifetimeFree<'a, T: ?Sized, U: LifetimeFree + ?Sized> { 59 | #[inline(always)] 60 | fn try_cast(&self, value: &'a T) -> Result<&'a U, &'a T> { 61 | // SAFETY: See comments on safety in `TryCastLifetimeFree`. 62 | 63 | if type_eq_non_static::() { 64 | // Pointer casts are not allowed here since the compiler can't prove 65 | // that `&T` and `&U` have the same kind of associated pointer data if 66 | // they are fat pointers. But we know they are identical, so we use 67 | // a transmute. 68 | Ok(unsafe { transmute_unchecked::<&T, &U>(value) }) 69 | } else { 70 | Err(value) 71 | } 72 | } 73 | } 74 | 75 | impl<'a, T, U: LifetimeFree> TryCastRefLifetimeFree<'a, T, U> 76 | for &&&&&&(CastToken<&'a T>, CastToken<&'a U>) 77 | { 78 | } 79 | 80 | /// Supporting trait for autoderef specialization on lifetime-free types. 81 | pub trait TryCastOwnedLifetimeFree { 82 | #[inline(always)] 83 | fn try_cast(&self, value: T) -> Result { 84 | // SAFETY: If `U` is lifetime-free, and the base types of `T` and `U` 85 | // are equal, then `T` is also lifetime-free. Therefore `T` and `U` are 86 | // strictly identical and it is safe to cast a `T` into a `U`. 87 | // 88 | // We know that `U` is lifetime-free because of the `LifetimeFree` trait 89 | // checked statically. `LifetimeFree` is an unsafe trait implemented for 90 | // individual types, so the burden of verifying that a type is indeed 91 | // lifetime-free is on the implementer. 92 | 93 | if type_eq_non_static::() { 94 | Ok(unsafe { transmute_unchecked::(value) }) 95 | } else { 96 | Err(value) 97 | } 98 | } 99 | } 100 | 101 | impl TryCastOwnedLifetimeFree for &&&&&(CastToken, CastToken) {} 102 | 103 | /// Supporting trait for autoderef specialization on mutable slices. 104 | pub trait TryCastSliceMut<'a, T: 'static, U: 'static> { 105 | /// Attempt to cast a generic mutable slice to a given type if the types are 106 | /// equal. 107 | /// 108 | /// The reference does not have to be static as long as the item type is 109 | /// static. 110 | #[inline(always)] 111 | fn try_cast(&self, value: &'a mut [T]) -> Result<&'a mut [U], &'a mut [T]> { 112 | if type_eq::() { 113 | Ok(unsafe { &mut *(value as *mut [T] as *mut [U]) }) 114 | } else { 115 | Err(value) 116 | } 117 | } 118 | } 119 | 120 | impl<'a, T: 'static, U: 'static> TryCastSliceMut<'a, T, U> 121 | for &&&&(CastToken<&'a mut [T]>, CastToken<&'a mut [U]>) 122 | { 123 | } 124 | 125 | /// Supporting trait for autoderef specialization on slices. 126 | pub trait TryCastSliceRef<'a, T: 'static, U: 'static> { 127 | /// Attempt to cast a generic slice to a given type if the types are equal. 128 | /// 129 | /// The reference does not have to be static as long as the item type is 130 | /// static. 131 | #[inline(always)] 132 | fn try_cast(&self, value: &'a [T]) -> Result<&'a [U], &'a [T]> { 133 | if type_eq::() { 134 | Ok(unsafe { &*(value as *const [T] as *const [U]) }) 135 | } else { 136 | Err(value) 137 | } 138 | } 139 | } 140 | 141 | impl<'a, T: 'static, U: 'static> TryCastSliceRef<'a, T, U> 142 | for &&&(CastToken<&'a [T]>, CastToken<&'a [U]>) 143 | { 144 | } 145 | 146 | /// Supporting trait for autoderef specialization on mutable references. 147 | pub trait TryCastMut<'a, T: 'static, U: 'static> { 148 | /// Attempt to cast a generic mutable reference to a given type if the types 149 | /// are equal. 150 | /// 151 | /// The reference does not have to be static as long as the reference target 152 | /// type is static. 153 | #[inline(always)] 154 | fn try_cast(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> { 155 | if type_eq::() { 156 | Ok(unsafe { &mut *(value as *mut T as *mut U) }) 157 | } else { 158 | Err(value) 159 | } 160 | } 161 | } 162 | 163 | impl<'a, T: 'static, U: 'static> TryCastMut<'a, T, U> 164 | for &&(CastToken<&'a mut T>, CastToken<&'a mut U>) 165 | { 166 | } 167 | 168 | /// Supporting trait for autoderef specialization on references. 169 | pub trait TryCastRef<'a, T: 'static, U: 'static> { 170 | /// Attempt to cast a generic reference to a given type if the types are 171 | /// equal. 172 | /// 173 | /// The reference does not have to be static as long as the reference target 174 | /// type is static. 175 | #[inline(always)] 176 | fn try_cast(&self, value: &'a T) -> Result<&'a U, &'a T> { 177 | if type_eq::() { 178 | Ok(unsafe { &*(value as *const T as *const U) }) 179 | } else { 180 | Err(value) 181 | } 182 | } 183 | } 184 | 185 | impl<'a, T: 'static, U: 'static> TryCastRef<'a, T, U> for &(CastToken<&'a T>, CastToken<&'a U>) {} 186 | 187 | /// Default trait for autoderef specialization. 188 | pub trait TryCastOwned { 189 | /// Attempt to cast a value to a given type if the types are equal. 190 | #[inline(always)] 191 | fn try_cast(&self, value: T) -> Result { 192 | if type_eq::() { 193 | Ok(unsafe { transmute_unchecked::(value) }) 194 | } else { 195 | Err(value) 196 | } 197 | } 198 | } 199 | 200 | impl TryCastOwned for (CastToken, CastToken) {} 201 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Safe, zero-cost downcasting for limited compile-time specialization. 2 | //! 3 | //! This crate works fully on stable Rust, and also does not require the 4 | //! standard library. To disable references to the standard library, you must 5 | //! opt-out of the `std` feature using `default-features = false` in your 6 | //! `Cargo.toml` file. When in no-std mode, a separate `alloc` feature flag 7 | //! is available to support casting to several [`alloc`] types not included 8 | //! in [`core`]. 9 | //! 10 | //! Castaway provides the following key macros: 11 | //! 12 | //! - [`cast`]: Attempt to cast the result of an expression into a given 13 | //! concrete type. 14 | //! - [`match_type`]: Match the result of an expression against multiple 15 | //! concrete types. 16 | 17 | #![no_std] 18 | 19 | #[cfg(feature = "std")] 20 | extern crate std; 21 | 22 | #[cfg(feature = "alloc")] 23 | extern crate alloc; 24 | 25 | #[doc(hidden)] 26 | pub mod internal; 27 | mod lifetime_free; 28 | mod utils; 29 | 30 | pub use lifetime_free::LifetimeFree; 31 | 32 | /// Attempt to cast the result of an expression into a given concrete type. 33 | /// 34 | /// If the expression is in fact of the given type, an [`Ok`] is returned 35 | /// containing the result of the expression as that type. If the types do not 36 | /// match, the value is returned in an [`Err`] unchanged. 37 | /// 38 | /// This macro is designed to work inside a generic context, and allows you to 39 | /// downcast generic types to their concrete types or to another generic type at 40 | /// compile time. If you are looking for the ability to downcast values at 41 | /// runtime, you should use [`Any`](core::any::Any) instead. 42 | /// 43 | /// This macro does not perform any sort of type _conversion_ (such as 44 | /// re-interpreting `i32` as `u32` and so on), it only resolves generic types to 45 | /// concrete types if the instantiated generic type is exactly the same as the 46 | /// type you specify. If you are looking to reinterpret the bits of a value as a 47 | /// type other than the one it actually is, then you should look for a different 48 | /// library. 49 | /// 50 | /// Invoking this macro is zero-cost, meaning after normal compiler optimization 51 | /// steps there will be no code generated in the final binary for performing a 52 | /// cast. In debug builds some glue code may be present with a small runtime 53 | /// cost. 54 | /// 55 | /// # Restrictions 56 | /// 57 | /// Attempting to perform an illegal or unsupported cast that can never be 58 | /// successful, such as casting to a value with a longer lifetime than the 59 | /// expression, will produce a compile-time error. 60 | /// 61 | /// Due to language limitations with lifetime bounds, this macro is more 62 | /// restrictive than what is theoretically possible and rejects some legal 63 | /// casts. This is to ensure safety and correctness around lifetime handling. 64 | /// Examples include the following: 65 | /// 66 | /// - Casting an expression by value with a non-`'static` lifetime is not 67 | /// allowed. For example, you cannot attempt to cast a `T: 'a` to `Foo<'a>`. 68 | /// - Casting to a reference with a non-`'static` lifetime is not allowed if the 69 | /// expression type is not required to be a reference. For example, you can 70 | /// attempt to cast a `&T` to `&String`, but you can't attempt to cast a `T` 71 | /// to `&String` because `T` may or may not be a reference. You can, however, 72 | /// attempt to cast a `T: 'static` to `&'static String`. 73 | /// - You cannot cast references whose target itself may contain non-`'static` 74 | /// references. For example, you can attempt to cast a `&'a T: 'static` to 75 | /// `&'a Foo<'static>`, but you can't attempt to cast a `&'a T: 'b` to `&'a 76 | /// Foo<'b>`. 77 | /// - You can cast generic slices as long as the item type is `'static` and 78 | /// `Sized`, but you cannot cast a generic reference to a slice or vice versa. 79 | /// 80 | /// Some exceptions are made to the above restrictions for certain types which 81 | /// are known to be _lifetime-free_. You can cast a generic type to any 82 | /// lifetime-free type by value or by reference, even if the generic type is not 83 | /// `'static`. 84 | /// 85 | /// A type is considered lifetime-free if it contains no generic lifetime 86 | /// bounds, ensuring that all possible instantiations of the type are always 87 | /// `'static`. To mark a type as being lifetime-free and enable it to be casted 88 | /// to in this manner by this macro it must implement the [`LifetimeFree`] 89 | /// trait. This is implemented automatically for all primitive types and for 90 | /// several [`core`] types. If you enable the `std` crate feature, then it will 91 | /// also be implemented for several [`std`] types as well. If you enable the 92 | /// `alloc` crate feature, then it will be implemented for several [`alloc`] 93 | /// types without linking to the standard library as the `std` feature would. 94 | /// 95 | /// # Examples 96 | /// 97 | /// The above restrictions are admittedly complex and can be tricky to reason 98 | /// about, so it is recommended to read the following examples to get a feel for 99 | /// what is, and what is not, supported. 100 | /// 101 | /// Performing trivial casts: 102 | /// 103 | /// ``` 104 | /// use castaway::cast; 105 | /// 106 | /// let value: u8 = 0; 107 | /// assert_eq!(cast!(value, u8), Ok(0)); 108 | /// 109 | /// let slice: &[u8] = &[value]; 110 | /// assert_eq!(cast!(slice, &[u8]), Ok(slice)); 111 | /// ``` 112 | /// 113 | /// Performing a cast in a generic context: 114 | /// 115 | /// ``` 116 | /// use castaway::cast; 117 | /// 118 | /// fn is_this_a_u8(value: T) -> bool { 119 | /// cast!(value, u8).is_ok() 120 | /// } 121 | /// 122 | /// assert!(is_this_a_u8(0u8)); 123 | /// assert!(!is_this_a_u8(0u16)); 124 | /// 125 | /// // Note that we can also implement this without the `'static` type bound 126 | /// // because the only type(s) we care about casting to all implement 127 | /// // `LifetimeFree`: 128 | /// 129 | /// fn is_this_a_u8_non_static(value: T) -> bool { 130 | /// cast!(value, u8).is_ok() 131 | /// } 132 | /// 133 | /// assert!(is_this_a_u8_non_static(0u8)); 134 | /// assert!(!is_this_a_u8_non_static(0u16)); 135 | /// ``` 136 | /// 137 | /// Specialization in a blanket trait implementation: 138 | /// 139 | /// ``` 140 | /// # #[cfg(feature = "std")] { 141 | /// use std::fmt::Display; 142 | /// use castaway::cast; 143 | /// 144 | /// /// Like `std::string::ToString`, but with an optimization when `Self` is 145 | /// /// already a `String`. 146 | /// /// 147 | /// /// Since the standard library is allowed to use unstable features, 148 | /// /// `ToString` already has this optimization using the `specialization` 149 | /// /// feature, but this isn't something normal crates can do. 150 | /// pub trait FastToString { 151 | /// fn fast_to_string(&self) -> String; 152 | /// } 153 | /// 154 | /// impl FastToString for T { 155 | /// fn fast_to_string<'local>(&'local self) -> String { 156 | /// // If `T` is already a string, then take a different code path. 157 | /// // After monomorphization, this check will be completely optimized 158 | /// // away. 159 | /// // 160 | /// // Note we can cast a `&'local self` to a `&'local String` as `String` 161 | /// // implements `LifetimeFree`. 162 | /// if let Ok(string) = cast!(self, &String) { 163 | /// // Don't invoke the std::fmt machinery, just clone the string. 164 | /// string.to_owned() 165 | /// } else { 166 | /// // Make use of `Display` for any other `T`. 167 | /// format!("{}", self) 168 | /// } 169 | /// } 170 | /// } 171 | /// 172 | /// println!("specialized: {}", String::from("hello").fast_to_string()); 173 | /// println!("default: {}", "hello".fast_to_string()); 174 | /// # } 175 | /// ``` 176 | #[macro_export] 177 | macro_rules! cast { 178 | ($value:expr, $T:ty) => {{ 179 | #[allow(unused_imports)] 180 | use $crate::internal::*; 181 | 182 | // Here we are using an _autoderef specialization_ technique, which 183 | // exploits method resolution autoderefs to select different cast 184 | // implementations based on the type of expression passed in. The traits 185 | // imported above are all in scope and all have the potential to be 186 | // chosen to resolve the method name `try_cast` based on their generic 187 | // constraints. 188 | // 189 | // To support casting references with non-static lifetimes, the traits 190 | // limited to reference types require less dereferencing to invoke and 191 | // thus are preferred by the compiler if applicable. 192 | let value = $value; 193 | let src_token = CastToken::of_val(&value); 194 | let dest_token = CastToken::<$T>::of(); 195 | 196 | // Note: The number of references added here must be kept in sync with 197 | // the largest number of references used by any trait implementation in 198 | // the internal module. 199 | let result: ::core::result::Result<$T, _> = (&&&&&&&(src_token, dest_token)).try_cast(value); 200 | 201 | result 202 | }}; 203 | 204 | ($value:expr) => { 205 | $crate::cast!($value, _) 206 | }; 207 | } 208 | 209 | /// Match the result of an expression against multiple concrete types. 210 | /// 211 | /// You can write multiple match arms in the following syntax: 212 | /// 213 | /// ```no_compile 214 | /// TYPE as name => { /* expression */ } 215 | /// ``` 216 | /// 217 | /// If the concrete type matches the given type, then the value will be cast to 218 | /// that type and bound to the given variable name. The expression on the 219 | /// right-hand side of the match is then executed and returned as the result of 220 | /// the entire match expression. 221 | /// 222 | /// The name following the `as` keyword can be any [irrefutable 223 | /// pattern](https://doc.rust-lang.org/stable/reference/patterns.html#refutability). 224 | /// Like `match` or `let` expressions, you can use an underscore to prevent 225 | /// warnings if you don't use the casted value, such as `_value` or just `_`. 226 | /// 227 | /// Since it would be impossible to exhaustively list all possible types of an 228 | /// expression, you **must** include a final default match arm. The default 229 | /// match arm does not specify a type: 230 | /// 231 | /// ```no_compile 232 | /// name => { /* expression */ } 233 | /// ``` 234 | /// 235 | /// The original expression will be bound to the given variable name without 236 | /// being casted. If you don't care about the original value, the default arm 237 | /// can be: 238 | /// 239 | /// ```no_compile 240 | /// _ => { /* expression */ } 241 | /// ``` 242 | /// 243 | /// This macro has all the same rules and restrictions around type casting as 244 | /// [`cast`]. 245 | /// 246 | /// # Examples 247 | /// 248 | /// ``` 249 | /// use std::fmt::Display; 250 | /// use castaway::match_type; 251 | /// 252 | /// fn to_string(value: T) -> String { 253 | /// match_type!(value, { 254 | /// String as s => s, 255 | /// &str as s => s.to_string(), 256 | /// s => s.to_string(), 257 | /// }) 258 | /// } 259 | /// 260 | /// println!("{}", to_string("foo")); 261 | /// ``` 262 | #[macro_export] 263 | macro_rules! match_type { 264 | ($value:expr, { 265 | $T:ty as $pat:pat => $branch:expr, 266 | $($tail:tt)+ 267 | }) => { 268 | match $crate::cast!($value, $T) { 269 | Ok(value) => { 270 | let $pat = value; 271 | $branch 272 | }, 273 | Err(value) => $crate::match_type!(value, { 274 | $($tail)* 275 | }) 276 | } 277 | }; 278 | 279 | ($value:expr, { 280 | $pat:pat => $branch:expr $(,)? 281 | }) => {{ 282 | let $pat = $value; 283 | $branch 284 | }}; 285 | } 286 | 287 | #[cfg(test)] 288 | mod tests { 289 | use super::*; 290 | 291 | #[cfg(feature = "alloc")] 292 | use alloc::string::String; 293 | 294 | #[test] 295 | fn cast() { 296 | assert_eq!(cast!(0u8, u16), Err(0u8)); 297 | assert_eq!(cast!(1u8, u8), Ok(1u8)); 298 | assert_eq!(cast!(2u8, &'static u8), Err(2u8)); 299 | assert_eq!(cast!(2u8, &u8), Err(2u8)); // 'static is inferred 300 | 301 | static VALUE: u8 = 2u8; 302 | assert_eq!(cast!(&VALUE, &u8), Ok(&2u8)); 303 | assert_eq!(cast!(&VALUE, &'static u8), Ok(&2u8)); 304 | assert_eq!(cast!(&VALUE, &u16), Err(&2u8)); 305 | assert_eq!(cast!(&VALUE, &i8), Err(&2u8)); 306 | 307 | let value = 2u8; 308 | 309 | fn inner<'a>(value: &'a u8) { 310 | assert_eq!(cast!(value, &u8), Ok(&2u8)); 311 | assert_eq!(cast!(value, &'a u8), Ok(&2u8)); 312 | assert_eq!(cast!(value, &u16), Err(&2u8)); 313 | assert_eq!(cast!(value, &i8), Err(&2u8)); 314 | } 315 | 316 | inner(&value); 317 | 318 | let mut slice = [1u8; 2]; 319 | 320 | fn inner2<'a>(value: &'a [u8]) { 321 | assert_eq!(cast!(value, &[u8]), Ok(&[1, 1][..])); 322 | assert_eq!(cast!(value, &'a [u8]), Ok(&[1, 1][..])); 323 | assert_eq!(cast!(value, &'a [u16]), Err(&[1, 1][..])); 324 | assert_eq!(cast!(value, &'a [i8]), Err(&[1, 1][..])); 325 | } 326 | 327 | inner2(&slice); 328 | 329 | #[allow(clippy::needless_lifetimes)] 330 | fn inner3<'a>(value: &'a mut [u8]) { 331 | assert_eq!(cast!(value, &mut [u8]), Ok(&mut [1, 1][..])); 332 | } 333 | inner3(&mut slice); 334 | } 335 | 336 | #[test] 337 | fn cast_with_type_inference() { 338 | let result: Result = cast!(0u8); 339 | assert_eq!(result, Ok(0u8)); 340 | 341 | let result: Result = cast!(0u16); 342 | assert_eq!(result, Err(0u16)); 343 | } 344 | 345 | #[test] 346 | fn match_type() { 347 | let v = 42i32; 348 | 349 | assert!(match_type!(v, { 350 | u32 as _ => false, 351 | i32 as _ => true, 352 | _ => false, 353 | })); 354 | } 355 | 356 | macro_rules! test_lifetime_free_cast { 357 | () => {}; 358 | 359 | ( 360 | $(#[$meta:meta])* 361 | for $TARGET:ty as $name:ident { 362 | $( 363 | $value:expr => $matches:pat $(if $guard:expr)?, 364 | )+ 365 | } 366 | $($tail:tt)* 367 | ) => { 368 | paste::paste! { 369 | $(#[$meta])* 370 | #[test] 371 | #[allow(non_snake_case)] 372 | fn []() { 373 | fn do_cast(value: T) -> Result<$TARGET, T> { 374 | cast!(value, $TARGET) 375 | } 376 | 377 | $( 378 | assert!(match do_cast($value) { 379 | $matches $(if $guard)* => true, 380 | _ => false, 381 | }); 382 | )* 383 | } 384 | 385 | $(#[$meta])* 386 | #[test] 387 | #[allow(non_snake_case)] 388 | fn []() { 389 | fn do_cast(value: &T) -> Result<&$TARGET, &T> { 390 | cast!(value, &$TARGET) 391 | } 392 | 393 | $( 394 | assert!(match do_cast(&$value).map(|t| t.clone()).map_err(|e| e.clone()) { 395 | $matches $(if $guard)* => true, 396 | _ => false, 397 | }); 398 | )* 399 | } 400 | 401 | $(#[$meta])* 402 | #[test] 403 | #[allow(non_snake_case)] 404 | fn []() { 405 | fn do_cast(value: &mut T) -> Result<&mut $TARGET, &mut T> { 406 | cast!(value, &mut $TARGET) 407 | } 408 | 409 | $( 410 | assert!(match do_cast(&mut $value).map(|t| t.clone()).map_err(|e| e.clone()) { 411 | $matches $(if $guard)* => true, 412 | _ => false, 413 | }); 414 | )* 415 | } 416 | } 417 | 418 | test_lifetime_free_cast! { 419 | $($tail)* 420 | } 421 | }; 422 | 423 | ( 424 | $(#[$meta:meta])* 425 | for $TARGET:ty { 426 | $( 427 | $value:expr => $matches:pat $(if $guard:expr)?, 428 | )+ 429 | } 430 | $($tail:tt)* 431 | ) => { 432 | paste::paste! { 433 | $(#[$meta])* 434 | #[test] 435 | #[allow(non_snake_case)] 436 | fn []() { 437 | fn do_cast(value: T) -> Result<$TARGET, T> { 438 | cast!(value, $TARGET) 439 | } 440 | 441 | $( 442 | assert!(match do_cast($value) { 443 | $matches $(if $guard)* => true, 444 | _ => false, 445 | }); 446 | )* 447 | } 448 | 449 | $(#[$meta])* 450 | #[test] 451 | #[allow(non_snake_case)] 452 | fn []() { 453 | fn do_cast(value: &T) -> Result<&$TARGET, &T> { 454 | cast!(value, &$TARGET) 455 | } 456 | 457 | $( 458 | assert!(match do_cast(&$value).map(|t| t.clone()).map_err(|e| e.clone()) { 459 | $matches $(if $guard)* => true, 460 | _ => false, 461 | }); 462 | )* 463 | } 464 | 465 | $(#[$meta])* 466 | #[test] 467 | #[allow(non_snake_case)] 468 | fn []() { 469 | fn do_cast(value: &mut T) -> Result<&mut $TARGET, &mut T> { 470 | cast!(value, &mut $TARGET) 471 | } 472 | 473 | $( 474 | assert!(match do_cast(&mut $value).map(|t| t.clone()).map_err(|e| e.clone()) { 475 | $matches $(if $guard)* => true, 476 | _ => false, 477 | }); 478 | )* 479 | } 480 | } 481 | 482 | test_lifetime_free_cast! { 483 | $($tail)* 484 | } 485 | }; 486 | } 487 | 488 | test_lifetime_free_cast! { 489 | for bool { 490 | 0u8 => Err(_), 491 | true => Ok(true), 492 | } 493 | 494 | for u8 { 495 | 0u8 => Ok(0u8), 496 | 1u16 => Err(1u16), 497 | 42u8 => Ok(42u8), 498 | } 499 | 500 | for f32 { 501 | 3.2f32 => Ok(v) if v == 3.2, 502 | 3.2f64 => Err(v) if v == 3.2f64, 503 | } 504 | 505 | #[cfg(feature = "alloc")] 506 | for String { 507 | String::from("hello world") => Ok(ref v) if v.as_str() == "hello world", 508 | "hello world" => Err("hello world"), 509 | } 510 | 511 | for Option as Option_u8 { 512 | 0u8 => Err(0u8), 513 | Some(42u8) => Ok(Some(42u8)), 514 | } 515 | 516 | // See https://github.com/rust-lang/rust/issues/127286 for details. 517 | for (u8, u8) as TupleU8U8 { 518 | (1u8, 2u8) => Ok((1u8, 2u8)), 519 | 1u8 => Err(1u8), 520 | } 521 | for (bool, u16) as TupleBoolU16 { 522 | (false, 2u16) => Ok((false, 2u16)), 523 | true => Err(true), 524 | } 525 | } 526 | } 527 | -------------------------------------------------------------------------------- /src/lifetime_free.rs: -------------------------------------------------------------------------------- 1 | /// Marker trait for types that do not contain any lifetime parameters. Such 2 | /// types are safe to cast from non-static type parameters if their types are 3 | /// equal. 4 | /// 5 | /// This trait is used by [`cast!`](crate::cast) to determine what casts are legal on values 6 | /// without a `'static` type constraint. 7 | /// 8 | /// # Safety 9 | /// 10 | /// When implementing this trait for a type, you must ensure that the type is 11 | /// free of any lifetime parameters. Failure to meet **all** of the requirements 12 | /// below may result in undefined behavior. 13 | /// 14 | /// - The type must be `'static`. 15 | /// - The type must be free of lifetime parameters. In other words, the type 16 | /// must be an "owned" type and not contain *any* lifetime parameters. 17 | /// - All contained fields must also be `LifetimeFree`. 18 | /// 19 | /// # Examples 20 | /// 21 | /// ``` 22 | /// use castaway::LifetimeFree; 23 | /// 24 | /// struct Container(T); 25 | /// 26 | /// // UNDEFINED BEHAVIOR!! 27 | /// // unsafe impl LifetimeFree for Container<&'static str> {} 28 | /// 29 | /// // UNDEFINED BEHAVIOR!! 30 | /// // unsafe impl LifetimeFree for Container {} 31 | /// 32 | /// // This is safe. 33 | /// unsafe impl LifetimeFree for Container {} 34 | /// 35 | /// struct PlainOldData { 36 | /// foo: u8, 37 | /// bar: bool, 38 | /// } 39 | /// 40 | /// // This is also safe, since all fields are known to be `LifetimeFree`. 41 | /// unsafe impl LifetimeFree for PlainOldData {} 42 | /// ``` 43 | pub unsafe trait LifetimeFree {} 44 | 45 | unsafe impl LifetimeFree for () {} 46 | unsafe impl LifetimeFree for bool {} 47 | unsafe impl LifetimeFree for char {} 48 | unsafe impl LifetimeFree for f32 {} 49 | unsafe impl LifetimeFree for f64 {} 50 | unsafe impl LifetimeFree for i8 {} 51 | unsafe impl LifetimeFree for i16 {} 52 | unsafe impl LifetimeFree for i32 {} 53 | unsafe impl LifetimeFree for i64 {} 54 | unsafe impl LifetimeFree for i128 {} 55 | unsafe impl LifetimeFree for isize {} 56 | unsafe impl LifetimeFree for str {} 57 | unsafe impl LifetimeFree for u8 {} 58 | unsafe impl LifetimeFree for u16 {} 59 | unsafe impl LifetimeFree for u32 {} 60 | unsafe impl LifetimeFree for u64 {} 61 | unsafe impl LifetimeFree for u128 {} 62 | unsafe impl LifetimeFree for usize {} 63 | 64 | unsafe impl LifetimeFree for core::num::NonZeroI8 {} 65 | unsafe impl LifetimeFree for core::num::NonZeroI16 {} 66 | unsafe impl LifetimeFree for core::num::NonZeroI32 {} 67 | unsafe impl LifetimeFree for core::num::NonZeroI64 {} 68 | unsafe impl LifetimeFree for core::num::NonZeroI128 {} 69 | unsafe impl LifetimeFree for core::num::NonZeroIsize {} 70 | unsafe impl LifetimeFree for core::num::NonZeroU8 {} 71 | unsafe impl LifetimeFree for core::num::NonZeroU16 {} 72 | unsafe impl LifetimeFree for core::num::NonZeroU32 {} 73 | unsafe impl LifetimeFree for core::num::NonZeroU64 {} 74 | unsafe impl LifetimeFree for core::num::NonZeroU128 {} 75 | unsafe impl LifetimeFree for core::num::NonZeroUsize {} 76 | 77 | unsafe impl LifetimeFree for [T] {} 78 | #[rustversion::since(1.51)] 79 | unsafe impl LifetimeFree for [T; SIZE] {} 80 | unsafe impl LifetimeFree for Option {} 81 | unsafe impl LifetimeFree for Result {} 82 | unsafe impl LifetimeFree for core::num::Wrapping {} 83 | unsafe impl LifetimeFree for core::cell::Cell {} 84 | unsafe impl LifetimeFree for core::cell::RefCell {} 85 | 86 | macro_rules! tuple_impls { 87 | ($( $( $name:ident )+, )+) => { 88 | $( 89 | unsafe impl<$($name: LifetimeFree),+> LifetimeFree for ($($name,)+) {} 90 | )+ 91 | }; 92 | } 93 | 94 | tuple_impls! { 95 | T0, 96 | T0 T1, 97 | T0 T1 T2, 98 | T0 T1 T2 T3, 99 | T0 T1 T2 T3 T4, 100 | T0 T1 T2 T3 T4 T5, 101 | T0 T1 T2 T3 T4 T5 T6, 102 | T0 T1 T2 T3 T4 T5 T6 T7, 103 | T0 T1 T2 T3 T4 T5 T6 T7 T8, 104 | T0 T1 T2 T3 T4 T5 T6 T7 T8 T9, 105 | } 106 | 107 | #[cfg(feature = "alloc")] 108 | mod alloc_impls { 109 | use super::LifetimeFree; 110 | 111 | unsafe impl LifetimeFree for alloc::string::String {} 112 | 113 | unsafe impl LifetimeFree for alloc::boxed::Box {} 114 | unsafe impl LifetimeFree for alloc::vec::Vec {} 115 | 116 | #[rustversion::attr(since(1.60), cfg(target_has_atomic = "ptr"))] 117 | unsafe impl LifetimeFree for alloc::sync::Arc {} 118 | } 119 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | //! Low-level utility functions. 2 | 3 | use core::{ 4 | any::{type_name, TypeId}, 5 | marker::PhantomData, 6 | mem, ptr, 7 | }; 8 | 9 | /// Determine if two static, generic types are equal to each other. 10 | #[inline(always)] 11 | pub(crate) fn type_eq() -> bool { 12 | // Reduce the chance of `TypeId` collisions causing a problem by also 13 | // verifying the layouts match and the type names match. Since `T` and `U` 14 | // are known at compile time the compiler should optimize away these extra 15 | // checks anyway. 16 | mem::size_of::() == mem::size_of::() 17 | && mem::align_of::() == mem::align_of::() 18 | && mem::needs_drop::() == mem::needs_drop::() 19 | && TypeId::of::() == TypeId::of::() 20 | && type_name::() == type_name::() 21 | } 22 | 23 | /// Determine if two generic types which may not be static are equal to each 24 | /// other. 25 | /// 26 | /// This function must be used with extreme discretion, as no lifetime checking 27 | /// is done. Meaning, this function considers `Struct<'a>` to be equal to 28 | /// `Struct<'b>`, even if either `'a` or `'b` outlives the other. 29 | #[inline(always)] 30 | pub(crate) fn type_eq_non_static() -> bool { 31 | non_static_type_id::() == non_static_type_id::() 32 | } 33 | 34 | /// Produces type IDs that are compatible with `TypeId::of::`, but without 35 | /// `T: 'static` bound. 36 | fn non_static_type_id() -> TypeId { 37 | trait NonStaticAny { 38 | fn get_type_id(&self) -> TypeId 39 | where 40 | Self: 'static; 41 | } 42 | 43 | impl NonStaticAny for PhantomData { 44 | fn get_type_id(&self) -> TypeId 45 | where 46 | Self: 'static, 47 | { 48 | TypeId::of::() 49 | } 50 | } 51 | 52 | let phantom_data = PhantomData::; 53 | NonStaticAny::get_type_id(unsafe { 54 | mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(&phantom_data) 55 | }) 56 | } 57 | 58 | /// Reinterprets the bits of a value of one type as another type. 59 | /// 60 | /// Similar to [`std::mem::transmute`], except that it makes no compile-time 61 | /// guarantees about the layout of `T` or `U`, and is therefore even **more** 62 | /// dangerous than `transmute`. Extreme caution must be taken when using this 63 | /// function; it is up to the caller to assert that `T` and `U` have the same 64 | /// size and layout and that it is safe to do this conversion. Which it probably 65 | /// isn't, unless `T` and `U` are identical. 66 | /// 67 | /// # Panics 68 | /// 69 | /// This function panics if `T` and `U` have different sizes. 70 | /// 71 | /// # Safety 72 | /// 73 | /// It is up to the caller to uphold the following invariants: 74 | /// 75 | /// - `T` must have the same alignment as `U` 76 | /// - `T` must be safe to transmute into `U` 77 | #[inline(always)] 78 | pub(crate) unsafe fn transmute_unchecked(value: T) -> U { 79 | // Assert is necessary to avoid miscompilation caused by a bug in LLVM. 80 | // Without it `castaway::cast!(123_u8, (u8, u8))` returns `Ok(...)` on 81 | // release build profile. `assert` shouldn't be replaced by `assert_eq` 82 | // because with `assert_eq` Rust 1.70 and 1.71 will still miscompile it. 83 | // 84 | // See https://github.com/rust-lang/rust/issues/127286 for details. 85 | assert!( 86 | mem::size_of::() == mem::size_of::(), 87 | "cannot transmute_unchecked if Dst and Src have different size" 88 | ); 89 | 90 | let dest = ptr::read(&value as *const T as *const U); 91 | mem::forget(value); 92 | dest 93 | } 94 | 95 | #[cfg(test)] 96 | mod tests { 97 | use super::*; 98 | 99 | #[test] 100 | fn non_static_type_comparisons() { 101 | assert!(type_eq_non_static::()); 102 | assert!(type_eq_non_static::<&'static u8, &'static u8>()); 103 | assert!(type_eq_non_static::<&u8, &'static u8>()); 104 | 105 | assert!(!type_eq_non_static::()); 106 | assert!(!type_eq_non_static::()); 107 | } 108 | } 109 | --------------------------------------------------------------------------------