Crate reinterpret

source ·
Expand description

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

The goal of this crate is to provide explicit safe wrappers for unsafe operations that prevent memory leaks and undefined behaviour. When the user misuses a function, it will panic.

Examples

    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] = 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]] = reinterpret_slice(&coordinates);
    assert_eq!(*coordinate_points, *points.as_slice()); // Same data.
    assert_eq!(coordinate_points, points.as_slice()); // Same location in memory.

Caveats

There are still ways to misuse these functions without causing panics that may produce unexpected (but not undefined) behaviour. For instance:

let data = vec![1.0f32; 4];
let garbage: &[f64] = reinterpret_slice(&data);

This is valid because a &[f64] can snuggly fit the data stored in data since 2 f64s occupy the same amount of memory as 4 f32s.

It is the users responsibility to avoid these types of scenarios.

Functions

Reinterpret a given slice as a slice of another type. This function checks that the resulting slice is appropriately sized.
Reinterpret a given slice as a slice of another type. This function checks that the resulting slice is appropriately sized.
Reinterpret a given Vec as a Vec of another type. This function checks that the resulting Vec is appropriately sized.