Crate plain [] [src]

A small Rust library that allows users to reinterpret data of certain types safely.

This crate provides an unsafe trait Plain, which the user of the crate uses to mark types for which operations of this library are safe. See Plain for the contractual obligation.

Other than that, everything else in this crate is perfectly safe to use as long as the Plain trait is not implemented on inadmissible types (similar to how Send and Sync in the standard library work).

Examples

To start using the crate, simply do extern crate plain;.

If you want your plain types to have methods from this crate, also include use plain.Methods;.

Then it's just a matter of marking the right types and using them.

extern crate plain;
use plain::Methods;



#[repr(C)]
#[derive(Default)]
struct ELF64Header {
    pub e_ident: [u8; 16],
    pub e_type: u16,
    pub e_machine: u16,
    pub e_version: u32,
    pub e_entry: u64,
    pub e_phoff: u64,
    pub e_shoff: u64,
    pub e_flags: u32,
    pub e_ehsize: u16,
    pub e_phentsize: u16,
    pub e_phnum: u16,
    pub e_shentsize: u16,
    pub e_shnum: u16,
    pub e_shstrndx: u16,
}
 
// SAFE: ELF64Header satisfies all the requirements of `Plain`.
unsafe impl plain::Plain for ELF64Header {}
 
fn reinterpret_buffer(buf: &[u8]) -> &ELF64Header {
    match plain::from_bytes(buf) {
        Err(_) => panic!("The buffer is either too short or not aligned!"),
        Ok(elfref) => elfref, 
    }
}
 
fn copy_from_buffer(buf: &[u8]) -> ELF64Header {
    let mut h = ELF64Header::default();
    h.as_mut_bytes().copy_from_slice(buf);
    h
}
 
#[repr(C)]
struct ArrayEntry {
    pub name: [u8; 64],
    pub tag: u32,
    pub score: u32, 
}
 
// SAFE: ArrayEntry satisfies all the requirements of `Plain`.
unsafe impl plain::Plain for ArrayEntry {}
 
fn array_from_bytes(buf: &[u8]) -> &[ArrayEntry] {
    // NOTE: length is not a concern here,
    // since from_bytes() can return empty slice.
 
    match plain::from_bytes(buf) {
        Err(_) => panic!("The buffer is not aligned!"),
        Ok(arr) => arr, 
    }
}

Enums

Error

Traits

Methods

This trait exposes all the functionality of this crate as methods on applicable types.

Plain

A trait for plain reinterpretable data.

Functions

as_bytes

Safely converts a reference to any type to an immutable byte slice of appropriate length.

as_mut_bytes

Safely converts a reference to a Plain type to a mutable byte slice of appropriate length.

from_bytes

Safely converts a byte slice to a Plain type reference.

from_mut_bytes

See from_bytes().