7 stable releases
Uses old Rust 2015
1.1.1 | Oct 28, 2017 |
---|---|
1.1.0 | Sep 18, 2017 |
#10 in #unchecked
31 downloads per month
Used in 2 crates
(via hexe_core)
14KB
159 lines
uncon
Traits for unchecked conversions between types in Rust.
Changes
Separate changelogs are available for
uncon
and
uncon_derive
.
Although they may differ in version number, uncon_derive
is always compatible
with current major version of uncon
.
Installation
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"
# Derive:
uncon_derive = "1.1.1"
Usage
This project allows for converting values between types with the unsafe assumption that whatever required invariants are met.
For example, a Value
instance must have a bit pattern from 0 to 2, inclusive.
#[macro_use]
extern crate uncon_derive;
extern crate uncon;
use uncon::*;
#[derive(FromUnchecked, PartialEq)]
#[repr(u8)]
enum Value {
X, Y, Z
}
fn main() {
let v = unsafe { Value::from_unchecked(2) };
assert_eq!(v, Value::Z);
// Undefined behavior:
let u = unsafe { Value::from_unchecked(3) };
}
To allow for safe (but possibly slower) conversions, one may also implement
From<T>
via FromUnchecked<T>
where a mask or other operation is used to
make the input value valid:
impl From<u8> for Value {
fn from(bits: u8) -> Value {
unsafe { Value::from_unchecked(bits % 3) }
}
}
Some types
already implement FromUnchecked
out-of-the-box.
Defined Behavior
This project is not an excuse to go around and create chaos through undefined behavior. These operations should only ever be done when speed is necessary and it is absolutely certain that they will not cause strange behavior.
Don't always reach for mem::transmute
. There are usually
alternatives. Here's a good list of reasons
why it should be avoided.
License
This project is released under either:
at your choosing.
Dependencies
~2MB
~42K SLoC