Skip to content

Commit

Permalink
Support for limited non-'static casts (#6)
Browse files Browse the repository at this point in the history
Allow casting to specific lifetime-free types from non-'static generic sources in specific contexts.

This adds a new `std` feature for implementing `LifetimeFree` on a number of types from the standard library which is enabled by default for convenience. This is not backwards-compatible with the previous no-std configuration.
  • Loading branch information
sagebind committed Apr 20, 2022
1 parent 6bc29b8 commit bd8ea00
Show file tree
Hide file tree
Showing 7 changed files with 379 additions and 54 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ jobs:
test:
uses: sagebind/workflows/.github/workflows/rust-ci.yml@v1
with:
msrv: "1.41.0"
msrv: "1.38.0"
10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ keywords = ["specialization"]
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"
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ 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]
Expand Down Expand Up @@ -46,6 +47,10 @@ fn main() {
}
```

## 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.
Expand Down
157 changes: 117 additions & 40 deletions src/internal.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,114 @@
//! This module contains helper functions and types used by the public-facing
//! macros. Some are public so they can be accessed by the expanded macro code,
//! 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 core::{
any::{type_name, TypeId},
marker::PhantomData,
mem,
use crate::{
lifetime_free::LifetimeFree,
utils::{transmute_unchecked, type_eq, type_eq_non_static},
};
use core::marker::PhantomData;

/// A token struct used to capture the type of a value without taking ownership of
/// it. Used to select a cast implementation in macros.
pub struct CastToken<T>(PhantomData<T>);
/// 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<T: ?Sized>(PhantomData<T>);

impl<T> CastToken<T> {
impl<T: ?Sized> CastToken<T> {
/// Create a cast token for the given type of value.
pub fn of_val(_value: &T) -> Self {
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::<T, U>() {
// 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::<T, U>() {
// 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<T, U: LifetimeFree> {
#[inline(always)]
fn try_cast(&self, value: T) -> Result<U, T> {
// 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::<T, U>() {
Ok(unsafe { transmute_unchecked::<T, U>(value) })
} else {
Err(value)
}
}
}

impl<T, U: LifetimeFree> TryCastOwnedLifetimeFree<T, U> for &&&&&(CastToken<T>, CastToken<U>) {}

/// Supporting trait for autoderef specialization on mutable slices.
pub trait TryCastSliceMut<'a, T: 'static> {
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<U: 'static>(&self, value: &'a mut [T]) -> Result<&'a mut [U], &'a mut [T]> {
fn try_cast(&self, value: &'a mut [T]) -> Result<&'a mut [U], &'a mut [T]> {
if type_eq::<T, U>() {
Ok(unsafe { &mut *(value as *mut [T] as *mut [U]) })
} else {
Expand All @@ -36,16 +117,19 @@ pub trait TryCastSliceMut<'a, T: 'static> {
}
}

impl<'a, T: 'static> TryCastSliceMut<'a, T> for &&&&CastToken<&'a mut [T]> {}
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> {
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<U: 'static>(&self, value: &'a [T]) -> Result<&'a [U], &'a [T]> {
fn try_cast(&self, value: &'a [T]) -> Result<&'a [U], &'a [T]> {
if type_eq::<T, U>() {
Ok(unsafe { &*(value as *const [T] as *const [U]) })
} else {
Expand All @@ -54,17 +138,20 @@ pub trait TryCastSliceRef<'a, T: 'static> {
}
}

impl<'a, T: 'static> TryCastSliceRef<'a, T> for &&&CastToken<&'a [T]> {}
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> {
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<U: 'static>(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> {
fn try_cast(&self, value: &'a mut T) -> Result<&'a mut U, &'a mut T> {
if type_eq::<T, U>() {
Ok(unsafe { &mut *(value as *mut T as *mut U) })
} else {
Expand All @@ -73,17 +160,20 @@ pub trait TryCastMut<'a, T: 'static> {
}
}

impl<'a, T: 'static> TryCastMut<'a, T> for &&CastToken<&'a mut T> {}
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> {
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<U: 'static>(&self, value: &'a T) -> Result<&'a U, &'a T> {
fn try_cast(&self, value: &'a T) -> Result<&'a U, &'a T> {
if type_eq::<T, U>() {
Ok(unsafe { &*(value as *const T as *const U) })
} else {
Expand All @@ -92,32 +182,19 @@ pub trait TryCastRef<'a, T: 'static> {
}
}

impl<'a, T: 'static> TryCastRef<'a, T> for &CastToken<&'a T> {}
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<T: 'static> {
pub trait TryCastOwned<T: 'static, U: 'static> {
/// Attempt to cast a value to a given type if the types are equal.
#[inline(always)]
fn try_cast<U: 'static>(&self, value: T) -> Result<U, T> {
fn try_cast(&self, value: T) -> Result<U, T> {
if type_eq::<T, U>() {
Ok(unsafe { mem::transmute_copy::<T, U>(&mem::ManuallyDrop::new(value)) })
Ok(unsafe { transmute_unchecked::<T, U>(value) })
} else {
Err(value)
}
}
}

impl<T: 'static> TryCastOwned<T> for CastToken<T> {}

/// Determine if two types are equal to each other.
#[inline(always)]
fn type_eq<T: 'static, U: 'static>() -> 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::<T>() == mem::size_of::<U>()
&& mem::align_of::<T>() == mem::align_of::<U>()
&& TypeId::of::<T>() == TypeId::of::<U>()
&& type_name::<T>() == type_name::<U>()
}
impl<T: 'static, U: 'static> TryCastOwned<T, U> for (CastToken<T>, CastToken<U>) {}
Loading

0 comments on commit bd8ea00

Please sign in to comment.