Skip to content
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

Implement cast from lifetime-free to unbound types #24

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

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