Skip to content

Conversation

@zheland
Copy link
Contributor

@zheland zheland commented Jul 3, 2024

The TryCast{Mut,Ref,Owned}LifetimeFree traits are implemented for LifetimeFree target types, but not implemented for LifetimeFree source types.

This PR adds TryCast{Mut,Ref,Owned}LifetimeFreeBack traits with source types bounded by LifetimeFree trait.

This makes it possible to upcast types and make specialized builders/decoders/constructors like this:

fn decode_smth<T, const N: usize>(buffer: &[u8]) -> [T; N] {
    fn specialized_impl<const N: usize>(buffer: &[u8]) -> [u8; N] { todo!() }
    fn default_impl<T, const N: usize>(buffer: &[u8]) -> [T; N] { todo!() }

    if cast!(0_u8, T).is_ok() {
        let byte_array: [u8; N] = specialized_impl(buffer);
        cast!(byte_array, [T; N]).expect("unexpected cast failure")
    } else {
        default_impl(buffer)
    }
}

This PR is based on (includes) another PR #23 and might require rebase before merging if needed. This PR includes additional tests for both PRs. You can use last commit (7b75e1e if not changed) for better diffs related to this PR changes only.

Common implementations for *LifetimeFree::try_cast and *LifetimeFreeBack::try_cast methods are extracted into separate private functions to reduce boilerplate code.

New autoderef ordering: TryCastMutLifetimeFree, TryCastMutLifetimeFreeBack (new), TryCastRefLifetimeFree, TryCastRefLifetimeFreeBack (new), TryCastOwnedLifetimeFree, TryCastOwnedLifetimeFreeBack (new), TryCastSliceMut, TryCastSliceRef, TryCastMut, TryCastRef, TryCastOwned

@zheland zheland force-pushed the cast-from-lifetime-free-to-unbound branch from 7b75e1e to 67d6d16 Compare July 5, 2024 14:34
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

Successfully merging this pull request may close these issues.

1 participant