Crate uncon [−] [src]
Traits for unchecked conversions between types.
The purpose of this crate is to provide FromUnchecked
and
IntoUnchecked
, which that can be used across different crates to allow
for fast conversions between types when speed necessary. These traits allow
for code to be much more expressive than when using mem::transmute
. They
are the unchecked/unsafe equivalents of From
and Into
, respectively.
Some types already implement
FromUnchecked
out-of-the-box.
Usage
This crate is available on crates.io and can be used by adding the
following to your project's Cargo.toml
:
[dependencies]
uncon = "1.0.0"
and this to your crate root:
extern crate uncon;
Examples
A type may wrap around another but must maintain certain invariants that
aren't met by the inner type. An example of this is str
in relation to
[u8]
where a string is just a UTF-8 encoded byte slice.
In this example, U4
is a simple wrapper around u8
where valid instances
must only ever have 4 bits set.
struct U4(u8); impl From<u8> for U4 { fn from(byte: u8) -> U4 { U4(byte & 0b1111) } } impl FromUnchecked<u8> for U4 { unsafe fn from_unchecked(byte: u8) -> U4 { U4(byte) } }
If a type T
implements FromUnchecked
for some type U
, then U
automatically implements IntoUnchecked
for T
.
let b = [b'h', b'i']; let s: &str = unsafe { b.as_ref().into_unchecked() }; assert_eq!(s, "hi");
Deriving Traits
See the docs of uncon_derive
for info on deriving this crate's traits.
#[derive(FromUnchecked)] struct Flags(u8); let f = unsafe { Flags::from_unchecked(0b1100) };
Traits
FromUnchecked |
Unchecked and potentially unsafe conversions from |
IntoUnchecked |
Unchecked and potentially unsafe conversions from |