1 unstable release
0.1.0 | May 1, 2019 |
---|
#6 in #coerce
13KB
332 lines
coercion
In-place type conversion.
lib.rs
:
In-place conversions between types of the same size and alignment.
Examples
use coercion::{Coerce, As};
let u8_slice: Box<[u8]> = vec![1,0,1,0].into_boxed_slice();
// Safe because true as u8 == 1
let bool_slice: Box<[bool]> = unsafe { u8_slice.coerce() };
assert_eq!(&bool_slice[..], &[true, false, true, false]);
// Don't need unsafe, because any bool is a valid u8
let u8_slice: Box<[u8]> = bool_slice.as_();
assert_eq!(&u8_slice[..], &[1,0,1,0]);
Both Coerce
and As
are implemented for str
:
use coercion::{Coerce, As};
let boxed_str = Box::<str>::from("Hello World!");
let boxed_bytes = boxed_str.as_();
assert_eq!(&boxed_bytes[..], b"Hello World!");
let boxed_str: Box<str> = unsafe { boxed_bytes.coerce() };
assert_eq!(&*boxed_str, "Hello World!");