uncon_derive

Crates.iouncon_derive
lib.rsuncon_derive
version1.1.1
sourcesrc
created_at2017-09-11 16:14:05.277301
updated_at2017-10-28 20:47:07.394729
descriptionDerive functionality for unchecked conversion traits.
homepage
repositoryhttps://github.com/nvzqz/uncon-rs
max_upload_size
id31408
size27,189
Nikolai Vazquez (nvzqz)

documentation

README

uncon Crates.io Downloads Build Status

Traits for unchecked conversions between types in Rust.

Documentation

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.

Commit count: 105

cargo fmt