Skip to content

downcast for non-'static types #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lcnr opened this issue Jan 7, 2025 · 0 comments
Open

downcast for non-'static types #14

lcnr opened this issue Jan 7, 2025 · 0 comments

Comments

@lcnr
Copy link
Owner

lcnr commented Jan 7, 2025

use std::any::TypeId;

/// The type does not have any free lifetimes.
///
/// Necessary as `TypeId` cannot distinguish between
/// `&'a str` and `&'static str` and we must not cast
/// between these types.
unsafe trait NoFreeLifetimes: 'static {}

unsafe impl<T: NoFreeLifetimes> NoFreeLifetimes for Vec<T> {}
unsafe impl NoFreeLifetimes for u32 {}
unsafe impl NoFreeLifetimes for String {}

fn try_downcast_ref<'a, S, T: NoFreeLifetimes>(x: &S) -> Option<&T> {
    if non_static_type_id::<S>() == non_static_type_id::<T>() {
        Some(unsafe { &*(x as *const S).cast() })
    } else {
        None
    }
}

fn non_static_type_id<T>() -> TypeId {
    type_id_of_val(|| ())
}

fn type_id_of_val<T: 'static>(_: T) -> TypeId {
    TypeId::of::<T>()
}

fn foo<T>(x: &T) {
    if let Some(s) = try_downcast_ref::<_, String>(x) {
        println!("{s}");
    } else if let Some(v) = try_downcast_ref::<_, Vec<u32>>(x) {
        println!("{v:?}");
    } else {
        println!("unknown");
    }
}

fn main() {
    foo(&String::from("hello"));
    foo(&"unknown");
    foo(&vec![1u32]);
    foo(&vec![1i32]);
}

relies on an implementation detail of rustc for soundness, would need to either be a blessed part of std or requires strong regression tests. Please do not use this in production :3

The idea is that closures inherit the type parameters of the current body without considering them for outlives constraints.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant