castaway-0.2.2/.cargo_vcs_info.json0000644000000001360000000000100126510ustar { "git": { "sha1": "83275c29ce1096f7a14c97de491e568d293df38a" }, "path_in_vcs": "" }castaway-0.2.2/.github/dependabot.yml000064400000000000000000000002210072674642500156540ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "00:00" open-pull-requests-limit: 10 castaway-0.2.2/.github/workflows/ci.yml000064400000000000000000000002500072674642500162010ustar 00000000000000name: ci on: push: branches: [master] pull_request: jobs: test: uses: sagebind/workflows/.github/workflows/rust-ci.yml@v1 with: msrv: "1.38.0" castaway-0.2.2/.github/workflows/release.yml000064400000000000000000000005320072674642500172310ustar 00000000000000name: release on: release: types: [published] jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: submodules: true - name: Publish to crates.io run: cargo publish --token "${CARGO_TOKEN}" --no-verify env: CARGO_TOKEN: ${{ secrets.CARGO_TOKEN }} castaway-0.2.2/.gitignore000064400000000000000000000000370072674642500134610ustar 00000000000000/target/ Cargo.lock **/*.rs.bk castaway-0.2.2/Cargo.toml0000644000000020040000000000100106430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "castaway" version = "0.2.2" authors = ["Stephen M. Coakley "] description = "Safe, zero-cost downcasting for limited compile-time specialization." keywords = [ "specialization", "specialize", "cast", ] categories = [ "no-std", "rust-patterns", ] license = "MIT" repository = "https://github.com/sagebind/castaway" [package.metadata.docs.rs] all-features = true [dependencies.rustversion] version = "1" [dev-dependencies.paste] version = "1" [features] default = ["std"] std = [] castaway-0.2.2/Cargo.toml.orig000064400000000000000000000010070072674642500143560ustar 00000000000000[package] name = "castaway" version = "0.2.2" description = "Safe, zero-cost downcasting for limited compile-time specialization." authors = ["Stephen M. Coakley "] license = "MIT" keywords = ["specialization", "specialize", "cast"] categories = ["no-std", "rust-patterns"] repository = "https://github.com/sagebind/castaway" edition = "2018" [package.metadata.docs.rs] all-features = true [features] default = ["std"] std = [] [dependencies] rustversion = "1" [dev-dependencies] paste = "1" castaway-0.2.2/LICENSE000064400000000000000000000020630072674642500124770ustar 00000000000000MIT License Copyright (c) 2021 Stephen M. Coakley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. castaway-0.2.2/README.md000064400000000000000000000065660072674642500127650ustar 00000000000000# Castaway Safe, zero-cost downcasting for limited compile-time specialization. [![Crates.io](https://img.shields.io/crates/v/castaway.svg)](https://crates.io/crates/castaway) [![Documentation](https://docs.rs/castaway/badge.svg)][documentation] [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Minimum supported Rust version](https://img.shields.io/badge/rustc-1.38+-yellow.svg)](#minimum-supported-rust-version) [![Build](https://github.com/sagebind/castaway/workflows/ci/badge.svg)](https://github.com/sagebind/castaway/actions) ## [Documentation] 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: ```rust use std::fmt::Display; use castaway::cast; /// Like `std::string::ToString`, but with an optimization when `Self` is /// already a `String`. /// /// Since the standard library is allowed to use unstable features, /// `ToString` already has this optimization using the `specialization` /// feature, but this isn't something normal crates can do. pub trait FastToString { fn fast_to_string(&self) -> String; } impl FastToString for T { fn fast_to_string(&self) -> String { // If `T` is already a string, then take a different code path. // After monomorphization, this check will be completely optimized // away. if let Ok(string) = cast!(self, &String) { // Don't invoke the std::fmt machinery, just clone the string. string.to_owned() } else { // Make use of `Display` for any other `T`. format!("{}", self) } } } fn main() { println!("specialized: {}", String::from("hello").fast_to_string()); println!("default: {}", "hello".fast_to_string()); } ``` ## Minimum supported Rust version 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. ## What is this? 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. 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`. ## License This project's source code and documentation is licensed under the MIT license. See the [LICENSE](LICENSE) file for details. [documentation]: https://docs.rs/castaway castaway-0.2.2/src/internal.rs000064400000000000000000000157450072674642500144560ustar 00000000000000//! This module contains helper traits and types used by the public-facing //! macros. Most are public so they can be accessed by the expanded macro code, //! but are not meant to be used by users directly and do not have a stable API. //! //! The various `TryCast*` traits in this module are referenced in macro //! expansions and expose multiple possible implementations of casting with //! different generic bounds. The compiler chooses which trait to use to fulfill //! the cast based on the trait bounds using the _autoderef_ trick. use crate::{ lifetime_free::LifetimeFree, utils::{transmute_unchecked, type_eq, type_eq_non_static}, }; use core::marker::PhantomData; /// A token struct used to capture a type without taking ownership of any /// values. Used to select a cast implementation in macros. pub struct CastToken(PhantomData); impl CastToken { /// Create a cast token for the given type of value. pub const fn of_val(_value: &T) -> Self { Self::of() } /// Create a new cast token of the specified type. pub const fn of() -> Self { Self(PhantomData) } } /// Supporting trait for autoderef specialization on mutable references to lifetime-free /// types. pub trait TryCastMutLifetimeFree<'a, T: ?Sized, U: LifetimeFree + ?Sized> { #[inline(always)] fn try_cast(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> { // SAFETY: See comments on safety in `TryCastLifetimeFree`. if type_eq_non_static::() { // Pointer casts are not allowed here since the compiler can't prove // that `&mut T` and `&mut U` have the same kind of associated // pointer data if they are fat pointers. But we know they are // identical, so we use a transmute. Ok(unsafe { transmute_unchecked::<&mut T, &mut U>(value) }) } else { Err(value) } } } impl<'a, T, U: LifetimeFree> TryCastMutLifetimeFree<'a, T, U> for &&&&&&&(CastToken<&'a mut T>, CastToken<&'a mut U>) { } /// Supporting trait for autoderef specialization on references to lifetime-free /// types. pub trait TryCastRefLifetimeFree<'a, T: ?Sized, U: LifetimeFree + ?Sized> { #[inline(always)] fn try_cast(&self, value: &'a T) -> Result<&'a U, &'a T> { // SAFETY: See comments on safety in `TryCastLifetimeFree`. if type_eq_non_static::() { // Pointer casts are not allowed here since the compiler can't prove // that `&T` and `&U` have the same kind of associated pointer data if // they are fat pointers. But we know they are identical, so we use // a transmute. Ok(unsafe { transmute_unchecked::<&T, &U>(value) }) } else { Err(value) } } } impl<'a, T, U: LifetimeFree> TryCastRefLifetimeFree<'a, T, U> for &&&&&&(CastToken<&'a T>, CastToken<&'a U>) { } /// Supporting trait for autoderef specialization on lifetime-free types. pub trait TryCastOwnedLifetimeFree { #[inline(always)] fn try_cast(&self, value: T) -> Result { // SAFETY: If `U` is lifetime-free, and the base types of `T` and `U` // are equal, then `T` is also lifetime-free. Therefore `T` and `U` are // strictly identical and it is safe to cast a `T` into a `U`. // // We know that `U` is lifetime-free because of the `LifetimeFree` trait // checked statically. `LifetimeFree` is an unsafe trait implemented for // individual types, so the burden of verifying that a type is indeed // lifetime-free is on the implementer. if type_eq_non_static::() { Ok(unsafe { transmute_unchecked::(value) }) } else { Err(value) } } } impl TryCastOwnedLifetimeFree for &&&&&(CastToken, CastToken) {} /// Supporting trait for autoderef specialization on mutable slices. pub trait TryCastSliceMut<'a, T: 'static, U: 'static> { /// Attempt to cast a generic mutable slice to a given type if the types are /// equal. /// /// The reference does not have to be static as long as the item type is /// static. #[inline(always)] fn try_cast(&self, value: &'a mut [T]) -> Result<&'a mut [U], &'a mut [T]> { if type_eq::() { Ok(unsafe { &mut *(value as *mut [T] as *mut [U]) }) } else { Err(value) } } } impl<'a, T: 'static, U: 'static> TryCastSliceMut<'a, T, U> for &&&&(CastToken<&'a mut [T]>, CastToken<&'a mut [U]>) { } /// Supporting trait for autoderef specialization on slices. pub trait TryCastSliceRef<'a, T: 'static, U: 'static> { /// Attempt to cast a generic slice to a given type if the types are equal. /// /// The reference does not have to be static as long as the item type is /// static. #[inline(always)] fn try_cast(&self, value: &'a [T]) -> Result<&'a [U], &'a [T]> { if type_eq::() { Ok(unsafe { &*(value as *const [T] as *const [U]) }) } else { Err(value) } } } impl<'a, T: 'static, U: 'static> TryCastSliceRef<'a, T, U> for &&&(CastToken<&'a [T]>, CastToken<&'a [U]>) { } /// Supporting trait for autoderef specialization on mutable references. pub trait TryCastMut<'a, T: 'static, U: 'static> { /// Attempt to cast a generic mutable reference to a given type if the types /// are equal. /// /// The reference does not have to be static as long as the reference target /// type is static. #[inline(always)] fn try_cast(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> { if type_eq::() { Ok(unsafe { &mut *(value as *mut T as *mut U) }) } else { Err(value) } } } impl<'a, T: 'static, U: 'static> TryCastMut<'a, T, U> for &&(CastToken<&'a mut T>, CastToken<&'a mut U>) { } /// Supporting trait for autoderef specialization on references. pub trait TryCastRef<'a, T: 'static, U: 'static> { /// Attempt to cast a generic reference to a given type if the types are /// equal. /// /// The reference does not have to be static as long as the reference target /// type is static. #[inline(always)] fn try_cast(&self, value: &'a T) -> Result<&'a U, &'a T> { if type_eq::() { Ok(unsafe { &*(value as *const T as *const U) }) } else { Err(value) } } } impl<'a, T: 'static, U: 'static> TryCastRef<'a, T, U> for &(CastToken<&'a T>, CastToken<&'a U>) {} /// Default trait for autoderef specialization. pub trait TryCastOwned { /// Attempt to cast a value to a given type if the types are equal. #[inline(always)] fn try_cast(&self, value: T) -> Result { if type_eq::() { Ok(unsafe { transmute_unchecked::(value) }) } else { Err(value) } } } impl TryCastOwned for (CastToken, CastToken) {} castaway-0.2.2/src/lib.rs000064400000000000000000000411700072674642500133770ustar 00000000000000//! Safe, zero-cost downcasting for limited compile-time specialization. //! //! This crate works fully on stable Rust, and also does not require the //! standard library. To disable references to the standard library, you must //! opt-out of the `std` feature using `default-features = false` in your //! `Cargo.toml` file. //! //! Castaway provides the following key macros: //! //! - [`cast`]: Attempt to cast the result of an expression into a given //! concrete type. //! - [`match_type`]: Match the result of an expression against multiple //! concrete types. #![cfg_attr(not(feature = "std"), no_std)] #[doc(hidden)] pub mod internal; mod lifetime_free; mod utils; pub use lifetime_free::LifetimeFree; /// Attempt to cast the result of an expression into a given concrete type. /// /// If the expression is in fact of the given type, an [`Ok`] is returned /// containing the result of the expression as that type. If the types do not /// match, the value is returned in an [`Err`] unchanged. /// /// This macro is designed to work inside a generic context, and allows you to /// downcast generic types to their concrete types or to another generic type at /// compile time. If you are looking for the ability to downcast values at /// runtime, you should use [`Any`](core::any::Any) instead. /// /// This macro does not perform any sort of type _conversion_ (such as /// re-interpreting `i32` as `u32` and so on), it only resolves generic types to /// concrete types if the instantiated generic type is exactly the same as the /// type you specify. If you are looking to reinterpret the bits of a value as a /// type other than the one it actually is, then you should look for a different /// library. /// /// Invoking this macro is zero-cost, meaning after normal compiler optimization /// steps there will be no code generated in the final binary for performing a /// cast. In debug builds some glue code may be present with a small runtime /// cost. /// /// # Restrictions /// /// Attempting to perform an illegal or unsupported cast that can never be /// successful, such as casting to a value with a longer lifetime than the /// expression, will produce a compile-time error. /// /// Due to language limitations with lifetime bounds, this macro is more /// restrictive than what is theoretically possible and rejects some legal /// casts. This is to ensure safety and correctness around lifetime handling. /// Examples include the following: /// /// - Casting an expression by value with a non-`'static` lifetime is not /// allowed. For example, you cannot attempt to cast a `T: 'a` to `Foo<'a>`. /// - Casting to a reference with a non-`'static` lifetime is not allowed if the /// expression type is not required to be a reference. For example, you can /// attempt to cast a `&T` to `&String`, but you can't attempt to cast a `T` /// to `&String` because `T` may or may not be a reference. You can, however, /// attempt to cast a `T: 'static` to `&'static String`. /// - You cannot cast references whose target itself may contain non-`'static` /// references. For example, you can attempt to cast a `&'a T: 'static` to /// `&'a Foo<'static>`, but you can't attempt to cast a `&'a T: 'b` to `&'a /// Foo<'b>`. /// - You can cast generic slices as long as the item type is `'static` and /// `Sized`, but you cannot cast a generic reference to a slice or vice versa. /// /// Some exceptions are made to the above restrictions for certain types which /// are known to be _lifetime-free_. You can cast a generic type to any /// lifetime-free type by value or by reference, even if the generic type is not /// `'static`. /// /// A type is considered lifetime-free if it contains no generic lifetime /// bounds, ensuring that all possible instantiations of the type are always /// `'static`. To mark a type as being lifetime-free and enable it to be casted /// to in this manner by this macro it must implement the [`LifetimeFree`] /// trait. This is implemented automatically for all primitive types and for /// several `core` types. If you enable the `std` crate feature, then it will /// also be implemented for several `std` types as well. /// /// # Examples /// /// The above restrictions are admittedly complex and can be tricky to reason /// about, so it is recommended to read the following examples to get a feel for /// what is, and what is not, supported. /// /// Performing trivial casts: /// /// ``` /// use castaway::cast; /// /// let value: u8 = 0; /// assert_eq!(cast!(value, u8), Ok(0)); /// /// let slice: &[u8] = &[value]; /// assert_eq!(cast!(slice, &[u8]), Ok(slice)); /// ``` /// /// Performing a cast in a generic context: /// /// ``` /// use castaway::cast; /// /// fn is_this_a_u8(value: T) -> bool { /// cast!(value, u8).is_ok() /// } /// /// assert!(is_this_a_u8(0u8)); /// assert!(!is_this_a_u8(0u16)); /// /// // Note that we can also implement this without the `'static` type bound /// // because the only type(s) we care about casting to all implement /// // `LifetimeFree`: /// /// fn is_this_a_u8_non_static(value: T) -> bool { /// cast!(value, u8).is_ok() /// } /// /// assert!(is_this_a_u8_non_static(0u8)); /// assert!(!is_this_a_u8_non_static(0u16)); /// ``` /// /// Specialization in a blanket trait implementation: /// /// ``` /// # #[cfg(feature = "std")] { /// use std::fmt::Display; /// use castaway::cast; /// /// /// Like `std::string::ToString`, but with an optimization when `Self` is /// /// already a `String`. /// /// /// /// Since the standard library is allowed to use unstable features, /// /// `ToString` already has this optimization using the `specialization` /// /// feature, but this isn't something normal crates can do. /// pub trait FastToString { /// fn fast_to_string(&self) -> String; /// } /// /// impl FastToString for T { /// fn fast_to_string<'local>(&'local self) -> String { /// // If `T` is already a string, then take a different code path. /// // After monomorphization, this check will be completely optimized /// // away. /// // /// // Note we can cast a `&'local self` to a `&'local String` as `String` /// // implements `LifetimeFree`. /// if let Ok(string) = cast!(self, &String) { /// // Don't invoke the std::fmt machinery, just clone the string. /// string.to_owned() /// } else { /// // Make use of `Display` for any other `T`. /// format!("{}", self) /// } /// } /// } /// /// println!("specialized: {}", String::from("hello").fast_to_string()); /// println!("default: {}", "hello".fast_to_string()); /// # } /// ``` #[macro_export] macro_rules! cast { ($value:expr, $T:ty) => {{ #[allow(unused_imports)] use $crate::internal::*; // Here we are using an _autoderef specialization_ technique, which // exploits method resolution autoderefs to select different cast // implementations based on the type of expression passed in. The traits // imported above are all in scope and all have the potential to be // chosen to resolve the method name `try_cast` based on their generic // constraints. // // To support casting references with non-static lifetimes, the traits // limited to reference types require less dereferencing to invoke and // thus are preferred by the compiler if applicable. let value = $value; let src_token = CastToken::of_val(&value); let dest_token = CastToken::<$T>::of(); // Note: The number of references added here must be kept in sync with // the largest number of references used by any trait implementation in // the internal module. let result: ::core::result::Result<$T, _> = (&&&&&&&(src_token, dest_token)).try_cast(value); result }}; ($value:expr) => { $crate::cast!($value, _) }; } /// Match the result of an expression against multiple concrete types. /// /// You can write multiple match arms in the following syntax: /// /// ```no_compile /// TYPE as name => { /* expression */ } /// ``` /// /// If the concrete type matches the given type, then the value will be cast to /// that type and bound to the given variable name. The expression on the /// right-hand side of the match is then executed and returned as the result of /// the entire match expression. /// /// The name following the `as` keyword can be any [irrefutable /// pattern](https://doc.rust-lang.org/stable/reference/patterns.html#refutability). /// Like `match` or `let` expressions, you can use an underscore to prevent /// warnings if you don't use the casted value, such as `_value` or just `_`. /// /// Since it would be impossible to exhaustively list all possible types of an /// expression, you **must** include a final default match arm. The default /// match arm does not specify a type: /// /// ```no_compile /// name => { /* expression */ } /// ``` /// /// The original expression will be bound to the given variable name without /// being casted. If you don't care about the original value, the default arm /// can be: /// /// ```no_compile /// _ => { /* expression */ } /// ``` /// /// This macro has all the same rules and restrictions around type casting as /// [`cast`]. /// /// # Examples /// /// ``` /// use std::fmt::Display; /// use castaway::match_type; /// /// fn to_string(value: T) -> String { /// match_type!(value, { /// String as s => s, /// &str as s => s.to_string(), /// s => s.to_string(), /// }) /// } /// /// println!("{}", to_string("foo")); /// ``` #[macro_export] macro_rules! match_type { ($value:expr, { $T:ty as $pat:pat => $branch:expr, $($tail:tt)+ }) => { match $crate::cast!($value, $T) { Ok(value) => { let $pat = value; $branch }, Err(value) => $crate::match_type!(value, { $($tail)* }) } }; ($value:expr, { $pat:pat => $branch:expr $(,)? }) => {{ let $pat = $value; $branch }}; } #[cfg(test)] mod tests { use super::*; #[test] fn cast() { assert_eq!(cast!(0u8, u16), Err(0u8)); assert_eq!(cast!(1u8, u8), Ok(1u8)); assert_eq!(cast!(2u8, &'static u8), Err(2u8)); assert_eq!(cast!(2u8, &u8), Err(2u8)); // 'static is inferred static VALUE: u8 = 2u8; assert_eq!(cast!(&VALUE, &u8), Ok(&2u8)); assert_eq!(cast!(&VALUE, &'static u8), Ok(&2u8)); assert_eq!(cast!(&VALUE, &u16), Err(&2u8)); assert_eq!(cast!(&VALUE, &i8), Err(&2u8)); let value = 2u8; fn inner<'a>(value: &'a u8) { assert_eq!(cast!(value, &u8), Ok(&2u8)); assert_eq!(cast!(value, &'a u8), Ok(&2u8)); assert_eq!(cast!(value, &u16), Err(&2u8)); assert_eq!(cast!(value, &i8), Err(&2u8)); } inner(&value); let mut slice = [1u8; 2]; fn inner2<'a>(value: &'a [u8]) { assert_eq!(cast!(value, &[u8]), Ok(&[1, 1][..])); assert_eq!(cast!(value, &'a [u8]), Ok(&[1, 1][..])); assert_eq!(cast!(value, &'a [u16]), Err(&[1, 1][..])); assert_eq!(cast!(value, &'a [i8]), Err(&[1, 1][..])); } inner2(&slice); #[allow(clippy::needless_lifetimes)] fn inner3<'a>(value: &'a mut [u8]) { assert_eq!(cast!(value, &mut [u8]), Ok(&mut [1, 1][..])); } inner3(&mut slice); } #[test] fn cast_with_type_inference() { let result: Result = cast!(0u8); assert_eq!(result, Ok(0u8)); let result: Result = cast!(0u16); assert_eq!(result, Err(0u16)); } #[test] fn match_type() { let v = 42i32; assert!(match_type!(v, { u32 as _ => false, i32 as _ => true, _ => false, })); } macro_rules! test_lifetime_free_cast { () => {}; ( $(#[$meta:meta])* for $TARGET:ty as $name:ident { $( $value:expr => $matches:pat $(if $guard:expr)?, )+ } $($tail:tt)* ) => { paste::paste! { $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: T) -> Result<$TARGET, T> { cast!(value, $TARGET) } $( assert!(match do_cast($value) { $matches $(if $guard)* => true, _ => false, }); )* } $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: &T) -> Result<&$TARGET, &T> { cast!(value, &$TARGET) } $( assert!(match do_cast(&$value).map(|t| t.clone()).map_err(|e| e.clone()) { $matches $(if $guard)* => true, _ => false, }); )* } $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: &mut T) -> Result<&mut $TARGET, &mut T> { cast!(value, &mut $TARGET) } $( assert!(match do_cast(&mut $value).map(|t| t.clone()).map_err(|e| e.clone()) { $matches $(if $guard)* => true, _ => false, }); )* } } test_lifetime_free_cast! { $($tail)* } }; ( $(#[$meta:meta])* for $TARGET:ty { $( $value:expr => $matches:pat $(if $guard:expr)?, )+ } $($tail:tt)* ) => { paste::paste! { $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: T) -> Result<$TARGET, T> { cast!(value, $TARGET) } $( assert!(match do_cast($value) { $matches $(if $guard)* => true, _ => false, }); )* } $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: &T) -> Result<&$TARGET, &T> { cast!(value, &$TARGET) } $( assert!(match do_cast(&$value).map(|t| t.clone()).map_err(|e| e.clone()) { $matches $(if $guard)* => true, _ => false, }); )* } $(#[$meta])* #[test] #[allow(non_snake_case)] fn []() { fn do_cast(value: &mut T) -> Result<&mut $TARGET, &mut T> { cast!(value, &mut $TARGET) } $( assert!(match do_cast(&mut $value).map(|t| t.clone()).map_err(|e| e.clone()) { $matches $(if $guard)* => true, _ => false, }); )* } } test_lifetime_free_cast! { $($tail)* } }; } test_lifetime_free_cast! { for bool { 0u8 => Err(_), true => Ok(true), } for u8 { 0u8 => Ok(0u8), 1u16 => Err(1u16), 42u8 => Ok(42u8), } for f32 { 3.2f32 => Ok(v) if v == 3.2, 3.2f64 => Err(v) if v == 3.2f64, } #[cfg(feature = "std")] for String { String::from("hello world") => Ok(ref v) if v.as_str() == "hello world", "hello world" => Err("hello world"), } for Option as Option_u8 { 0u8 => Err(0u8), Some(42u8) => Ok(Some(42u8)), } } } castaway-0.2.2/src/lifetime_free.rs000064400000000000000000000066460072674642500154410ustar 00000000000000/// Marker trait for types that do not contain any lifetime parameters. Such /// types are safe to cast from non-static type parameters if their types are /// equal. /// /// This trait is used by [`cast!`] to determine what casts are legal on values /// without a `'static` type constraint. /// /// # Safety /// /// When implementing this trait for a type, you must ensure that the type is /// free of any lifetime parameters. Failure to meet **all** of the requirements /// below may result in undefined behavior. /// /// - The type must be `'static`. /// - The type must be free of lifetime parameters. In other words, the type /// must be an "owned" type and not contain *any* lifetime parameters. /// - All contained fields must also be `LifetimeFree`. /// /// # Examples /// /// ``` /// use castaway::LifetimeFree; /// /// struct Container(T); /// /// // UNDEFINED BEHAVIOR!! /// // unsafe impl LifetimeFree for Container<&'static str> {} /// /// // UNDEFINED BEHAVIOR!! /// // unsafe impl LifetimeFree for Container {} /// /// // This is safe. /// unsafe impl LifetimeFree for Container {} /// /// struct PlainOldData { /// foo: u8, /// bar: bool, /// } /// /// // This is also safe, since all fields are known to be `LifetimeFree`. /// unsafe impl LifetimeFree for PlainOldData {} /// ``` pub unsafe trait LifetimeFree {} unsafe impl LifetimeFree for () {} unsafe impl LifetimeFree for bool {} unsafe impl LifetimeFree for char {} unsafe impl LifetimeFree for f32 {} unsafe impl LifetimeFree for f64 {} unsafe impl LifetimeFree for i8 {} unsafe impl LifetimeFree for i16 {} unsafe impl LifetimeFree for i32 {} unsafe impl LifetimeFree for i64 {} unsafe impl LifetimeFree for i128 {} unsafe impl LifetimeFree for isize {} unsafe impl LifetimeFree for str {} unsafe impl LifetimeFree for u8 {} unsafe impl LifetimeFree for u16 {} unsafe impl LifetimeFree for u32 {} unsafe impl LifetimeFree for u64 {} unsafe impl LifetimeFree for u128 {} unsafe impl LifetimeFree for usize {} unsafe impl LifetimeFree for core::num::NonZeroI8 {} unsafe impl LifetimeFree for core::num::NonZeroI16 {} unsafe impl LifetimeFree for core::num::NonZeroI32 {} unsafe impl LifetimeFree for core::num::NonZeroI64 {} unsafe impl LifetimeFree for core::num::NonZeroI128 {} unsafe impl LifetimeFree for core::num::NonZeroIsize {} unsafe impl LifetimeFree for core::num::NonZeroU8 {} unsafe impl LifetimeFree for core::num::NonZeroU16 {} unsafe impl LifetimeFree for core::num::NonZeroU32 {} unsafe impl LifetimeFree for core::num::NonZeroU64 {} unsafe impl LifetimeFree for core::num::NonZeroU128 {} unsafe impl LifetimeFree for core::num::NonZeroUsize {} unsafe impl LifetimeFree for [T] {} #[rustversion::since(1.51)] unsafe impl LifetimeFree for [T; SIZE] {} unsafe impl LifetimeFree for Option {} unsafe impl LifetimeFree for Result {} unsafe impl LifetimeFree for core::num::Wrapping {} unsafe impl LifetimeFree for core::cell::Cell {} unsafe impl LifetimeFree for core::cell::RefCell {} #[cfg(feature = "std")] mod std_impls { use super::LifetimeFree; unsafe impl LifetimeFree for String {} unsafe impl LifetimeFree for Box {} unsafe impl LifetimeFree for Vec {} unsafe impl LifetimeFree for std::sync::Arc {} } castaway-0.2.2/src/utils.rs000064400000000000000000000073060072674642500137740ustar 00000000000000//! Low-level utility functions. use core::{ any::{type_name, TypeId}, mem, ptr, }; /// Determine if two static, generic types are equal to each other. #[inline(always)] pub(crate) fn type_eq() -> bool { // Reduce the chance of `TypeId` collisions causing a problem by also // verifying the layouts match and the type names match. Since `T` and `U` // are known at compile time the compiler should optimize away these extra // checks anyway. mem::size_of::() == mem::size_of::() && mem::align_of::() == mem::align_of::() && mem::needs_drop::() == mem::needs_drop::() && TypeId::of::() == TypeId::of::() && type_name::() == type_name::() } /// Determine if two generic types which may not be static are equal to each /// other. /// /// This function must be used with extreme discretion, as no lifetime checking /// is done. Meaning, this function considers `Struct<'a>` to be equal to /// `Struct<'b>`, even if either `'a` or `'b` outlives the other. #[inline(always)] pub(crate) fn type_eq_non_static() -> bool { // Inline has a weird, but desirable result on this function. It can't be // fully inlined everywhere since it creates a function pointer of itself. // But in practice when used here, the act of taking the address will be // inlined, thus avoiding a function call when comparing two types. #[inline] fn type_id_of() -> usize { type_id_of:: as usize } // What we're doing here is comparing two function pointers of the same // generic function to see if they are identical. If they are not // identical then `T` and `U` are not the same type. // // If they are equal, then they _might_ be the same type, unless an // optimization step reduced two different functions to the same // implementation due to having the same body. To avoid this we are using // a function which references itself. This is something that LLVM cannot // merge, since each monomorphized function has a reference to a different // global alias. type_id_of::() == type_id_of::() // This is used as a sanity check more than anything. Our previous calls // should not have any false positives, but if they did then the odds of // them having the same type name as well is extremely unlikely. && type_name::() == type_name::() } /// Reinterprets the bits of a value of one type as another type. /// /// Similar to [`std::mem::transmute`], except that it makes no compile-time /// guarantees about the layout of `T` or `U`, and is therefore even **more** /// dangerous than `transmute`. Extreme caution must be taken when using this /// function; it is up to the caller to assert that `T` and `U` have the same /// size and layout and that it is safe to do this conversion. Which it probably /// isn't, unless `T` and `U` are identical. /// /// # Safety /// /// It is up to the caller to uphold the following invariants: /// /// - `T` must have the same size as `U` /// - `T` must have the same alignment as `U` /// - `T` must be safe to transmute into `U` #[inline(always)] pub(crate) unsafe fn transmute_unchecked(value: T) -> U { let dest = ptr::read(&value as *const T as *const U); mem::forget(value); dest } #[cfg(test)] mod tests { use super::*; #[test] fn non_static_type_comparisons() { assert!(type_eq_non_static::()); assert!(type_eq_non_static::<&'static u8, &'static u8>()); assert!(type_eq_non_static::<&u8, &'static u8>()); assert!(!type_eq_non_static::()); assert!(!type_eq_non_static::()); } }