Module constmuck::wrapper[][src]

Expand description

Functions for wrapping/peeling types that implement TransparentWrapper.

Related: IsTransparentWrapper type and IsTW macro.

Example

Tranmuting between arrays of values and arrays of wrappers.

use constmuck::{IsTW, wrapper};

#[derive(Debug, PartialEq)]
#[repr(transparent)]
pub struct Foo<T>(pub T);

unsafe impl<T> constmuck::TransparentWrapper<T> for Foo<T> {}

// `[u8; 3]` to `[Foo<u8>; 3]`
{
    const ARR: [Foo<u8>; 3] = wrapper::wrap([3, 5, 8], IsTW!(Foo<u8>, u8).array());

    assert_eq!(ARR, [Foo(3), Foo(5), Foo(8)]);
    // How to use `wrap` without relying on return type inference:
    assert_eq!(
        wrapper::wrap([13, 21, 34], IsTW!(Foo<u8>, u8).array()),
        [Foo(13), Foo(21), Foo(34)],
    );
}

// `[Foo<u8>; 3]` to `[u8; 3]`
{
    const ARR: [u8; 3] = wrapper::peel([Foo(3), Foo(5), Foo(8)], IsTW!(Foo<u8>, u8).array());

    assert_eq!(ARR, [3, 5, 8]);
    assert_eq!(
        wrapper::peel([Foo(13), Foo(21), Foo(34)], IsTW!(Foo<u16>, u16).array()),
        [13, 21, 34],
    );
}

// `&[u8; 3]` to `&[Foo<u8>; 3]`
{
    const REF_ARR: &[Foo<u8>; 3] = wrapper::wrap_ref(&[3, 5, 8], IsTW!(Foo<u8>, u8).array());

    assert_eq!(REF_ARR, &[Foo(3), Foo(5), Foo(8)]);
    assert_eq!(
        wrapper::wrap_ref(&[13, 21, 34], IsTW!(Foo<i32>, i32).array()),
        &[Foo(13), Foo(21), Foo(34)],
    );    
}

// `&[Foo<u8>; 3]` to `&[u8; 3]`
{
    const REF_ARR: &[u8; 3] = wrapper::peel_ref(&[Foo(3), Foo(5), Foo(8)], IsTW!().array());

    assert_eq!(REF_ARR, &[3, 5, 8]);
    assert_eq!(
        wrapper::peel_ref(&[Foo(13), Foo(21), Foo(34)], IsTW!(Foo<_>).array()),
        &[13, 21, 34],
    );    
}

Re-exports

pub use crate::IsTransparentWrapper;
pub use crate::IsTW;

Macros

Casts &Outer to &Inner, allows casting between ?Sized types

Casts &Inner to &Outer, allows casting between ?Sized types.

Functions

Casts Outer to Inner

Casts &Outer to &Inner

Casts &[Outer] to &[Inner]

Casts Inner to Outer

Casts &Inner to &Outer

Casts &[Inner] to &[Outer]