castaway/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
//! Safe, zero-cost downcasting for limited compile-time specialization.
//!
//! This crate works fully on stable Rust, and also does not require the
//! standard library.
//!
//! 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.
#![no_std]
#[doc(hidden)]
pub mod internal;
/// 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.
///
/// # Examples
///
/// 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<T: 'static>(value: T) -> bool {
/// cast!(value, u8).is_ok()
/// }
///
/// assert!(is_this_a_u8(0u8));
/// assert!(!is_this_a_u8(0u16));
/// ```
///
/// Specialization in a blanket trait implementation:
///
/// ```
/// 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<T: Display + 'static> 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 long
/// // as both `Self` and `String` are `'static`.
/// 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::{
CastToken, TryCastMut, TryCastOwned, TryCastRef, TryCastSliceMut, TryCastSliceRef,
};
// 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 token = CastToken::of_val(&value);
let result: ::core::result::Result<$T, _> = (&&&&&token).try_cast(value);
result
}};
}
/// 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<T: Display + 'static>(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);
fn inner3<'a>(value: &'a mut [u8]) {
assert_eq!(cast!(value, &mut [u8]), Ok(&mut [1, 1][..]));
}
inner3(&mut slice);
}
#[test]
fn match_type() {
let v = 42i32;
assert!(match_type!(v, {
u32 as _ => false,
i32 as _ => true,
_ => false,
}));
}
}