Struct constmuck::TypeSize [−][src]
pub struct TypeSize<T, B, const SIZE: usize> { /* fields omitted */ }
Expand description
For passing a type along with its size and additional bounds.
The B
(bounds) type parameter can be any type that implements Infer
,
and is implicitly constructed by the TypeSize
macro.
Example
Making a max_bit_pattern
function
use constmuck::{IsPod, TypeSize};
pub const fn max_bit_pattern<T, const SIZE: usize>(bound: TypeSize<T, IsPod<T>, SIZE>) -> T {
constmuck::cast(
[u8::MAX; SIZE],
// `IsPod!()` here constructs an `IsPod<[u8; SIZE]>`
//
// `bound.into_bounds()` here returns a `IsPod<T>`.
(IsPod!(), bound.into_bounds())
)
}
const U64: u64 = max_bit_pattern(TypeSize!(u64));
const U8S: [u8; 5] = max_bit_pattern(TypeSize!([u8; 5]));
const I8S: [i8; 5] = max_bit_pattern(TypeSize!([i8; 5]));
assert_eq!(U64, u64::MAX);
assert_eq!(U8S, [u8::MAX; 5]);
assert_eq!(I8S, [-1i8; 5]);
Implementations
Sets the bounds field of a bound-less TypeSize
.
Leaking
Note that B
is expected not to own memory,
dropping a TypeSize<_, B, _>
will leak any resources it owns.
Example
This example demonstrates how with_bounds
can be used to
compose TypeSize
with Is*::new_unchecked
.
use constmuck::{IsZeroable, TypeSize, zeroed};
fn main() {
const NEW: Foo = Foo::new();
assert_eq!(NEW, Foo(0, 0, 0));
}
#[derive(Debug, PartialEq)]
pub struct Foo(u8, u16, u32);
impl Foo {
pub const fn new() -> Self {
// safety: this type knows that all its fields are zeroable right now,
// but it doesn't impl Zeroable to be able to add nonzeroable fields.
let iz = unsafe{ IsZeroable::<Self>::new_unchecked() };
zeroed(TypeSize!(Self).with_bounds(iz))
}
}
Replaces the bounds field with bounds
.
Leaking
Note that V
is expected not to own memory,
dropping a TypeSize<_, V, _>
will leak any resources it owns.
Turns this TypeSize
into its bounds field.
Equivalent to copying::repeat
but allows passing the length of the retuned array.
Creates a [T; ARR_LEN]
by copying from a &T
Requires that T
implements Copy + Pod
(see IsCopy
docs for why it requires Pod
)
Example
use constmuck::TypeSize;
const PAIR: &[u128] = &TypeSize!(u128).repeat::<2>(&300);
assert_eq!(PAIR, &[300, 300]);
Equivalent to constmuck::zeroed_array
but allows passing the length of the retuned array.
For safely getting a std::mem::zeroed
[T; N]
.
This function requires that T
implements Zeroable
.
Example
use constmuck::TypeSize;
const BYTES: &[u8] = &TypeSize!(u8).zeroed_array::<2>();
const CHARS: &[char] = &TypeSize!(char).zeroed_array::<4>();
assert_eq!(BYTES, [0, 0]);
assert_eq!(CHARS, ['\0', '\0', '\0', '\0']);