#unsafe #data #low-level #cast #memory #memory-safety #array

reinterpret

Low level utility functions to reinterpret arrays of data

5 releases

Uses old Rust 2015

0.2.1 Nov 5, 2019
0.2.0 Aug 20, 2019
0.1.2 Nov 9, 2018
0.1.1 Aug 25, 2018
0.1.0 Aug 25, 2018

#9 in #arrays

Download history 30/week @ 2024-06-16 19/week @ 2024-06-23 5/week @ 2024-06-30 14/week @ 2024-07-07 33/week @ 2024-07-14 29/week @ 2024-07-21 60/week @ 2024-07-28 82/week @ 2024-08-04 43/week @ 2024-08-11 32/week @ 2024-08-18 104/week @ 2024-08-25 139/week @ 2024-09-01 134/week @ 2024-09-08 71/week @ 2024-09-15 182/week @ 2024-09-22 98/week @ 2024-09-29

512 downloads per month
Used in 9 crates (4 directly)

MIT/Apache

13KB
151 lines

reinterpret

Low level utility functions to reinterpret arrays of data in Rust

On crates.io On docs.rs Build status

Overview

This crate provides convenient low-level utility functions for reinterpreting data. This includes Vecs and slices. These functions are intrinsically unsafe but are very useful in performance critical code since they avoid additional copies.

The goal of this crate is to provide some memory safety along the boundaries of Vecs and slices to reduce the boilerplate for reinterpreting data.

These functions check that the source and target arrays have the same size, however they don't check for safety of converting the contained types.

It is possible to write safe wrappers for converting collections of concrete types using these functions, however this is out of the scope of this crate.

Examples

# extern crate reinterpret;
# use reinterpret::*;
# fn main() {
    let points: Vec<[f64;2]> = vec![
        [0.1, 1.0],
        [1.2, 1.4],
        [0.5, 3.2],
    ];
    let coordinates: Vec<f64> = vec![0.1, 1.0, 1.2, 1.4, 0.5, 3.2];

    let point_coordinates: &[f64] = unsafe { reinterpret_slice(&points) };
    assert_eq!(*point_coordinates, *coordinates.as_slice()); // Same data.
    assert_eq!(point_coordinates, coordinates.as_slice()); // Same location in memory.

    let coordinate_points: &[[f64;2]] = unsafe { reinterpret_slice(&coordinates) };
    assert_eq!(*coordinate_points, *points.as_slice()); // Same data.
    assert_eq!(coordinate_points, points.as_slice()); // Same location in memory.
# }

Undefined Behavior

There are ways to misuse these functions without causing panics that may produce undefined behavior. For instance:

# extern crate reinterpret;
# use reinterpret::*;
# fn main() {
    let a = 1;
    let b = 2;
    let v = vec![&a, &b];
    let mut m: Vec<&mut usize> = unsafe { reinterpret_vec(v) };
    *m[0] = 3; // mutating through a shared reference is UB.
# }

License

This repository is licensed under either of

at your option.

No runtime deps