Skip to content
This repository was archived by the owner on Dec 17, 2025. It is now read-only.
This repository was archived by the owner on Dec 17, 2025. It is now read-only.

A solution to have a completely safe casting API #9

Description

@Kixunil

Casting T into U is sound if they have the same type ID and at least one of these conditions hold:

  • Both T and U are 'static
  • U is guaranteed to not have lifetime parameters in itself or its type parameters recursively

The first one is already covered by Any, and second one can be implemented here. The crate just needs to define pub unsafe trait AlwaysStatic {} and bound U on that, then there are two ways to implement the trait soundly by the consumer crates without using the unsafe keyword:

  • derive macro which forces the : AlwaysStatic bound on all parameters and forbids any lifetime parameters
  • declarative macro that has its input syntax restricted to not have lifetime parameters - something like $(#[$($attr:tt)*])* $vis:$vis struct $name:ident$(<$(const $const_name:ident: $const_ty:ty),* $($param:ident $(= $default:ty))*> ...)? and emits both the type and the trait impl

Note that, as opposed to other derive macros, this has no problem with bounds on the type parameters rather than field types because the fields cannot have lifetime parameters if the parent doesn't and if the parent does but fields don't that needs to be forbidden anyway.

(Also the trait would be, obviously, implemented for all relevant std types.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions