Crates.io | reinterpret |
lib.rs | reinterpret |
version | 0.2.1 |
source | src |
created_at | 2018-08-25 03:33:31.386582 |
updated_at | 2019-11-05 09:11:32.92323 |
description | Low level utility functions to reinterpret arrays of data |
homepage | https://github.com/elrnv/reinterpret |
repository | https://github.com/elrnv/reinterpret |
max_upload_size | |
id | 81183 |
size | 25,306 |
Low level utility functions to reinterpret arrays of data in Rust
This crate provides convenient low-level utility functions for reinterpreting data.
This includes Vec
s and slice
s. 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 Vec
s and
slice
s 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.
# 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.
# }
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.
# }
This repository is licensed under either of
at your option.