Skip to content

Latest commit

 

History

History
114 lines (81 loc) · 3.25 KB

README.md

File metadata and controls

114 lines (81 loc) · 3.25 KB

uncon Crates.io Downloads Build Status

Traits for unchecked conversions between types in Rust.

Documentation

Become a Patron! Buy me a coffee

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.