Crate uncon [−] [src]
Traits for unchecked conversions between types.
The purpose of this crate is to provide FromUnchecked
and
IntoUnchecked
, which can be used across different crates to allow for
fast conversions between types when speed is 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.1.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) };
Safety
Vec<U>
toVec<T>
,Box<U>
toBox<T>
,&U
to&T
, and other conversions are similar tomem::transmute
except without the undefined behavior. There are absolutely no safety measures.- These conversions are extremely unsafe and should only be done in cases
such as turning
Vec<i8>
intoVec<u8>
or something similarly trivial. - If
T
implementsDrop
in the case ofVec<T>
, considermap
pingfrom_unchecked
andcollect
ing the results.
- These conversions are extremely unsafe and should only be done in cases
such as turning
Traits
FromUnchecked |
Unchecked and potentially unsafe conversions from |
IntoUnchecked |
Unchecked and potentially unsafe conversions from |