pub trait ViewMutNpyExt<'a>: Sized {
// Required method
fn view_mut_npy(buf: &'a mut [u8]) -> Result<Self, ViewNpyError>;
}Expand description
Extension trait for creating an ArrayViewMut from a mutable buffer
containing an .npy file.
The primary use-case for this is modifying a memory-mapped .npy file.
Modifying the elements in the view will modify the file. Modifying the
shape/strides of the view will not modify the shape/strides of the array
in the file.
Notes:
-
For types for which not all bit patterns are valid, such as
bool, the implementation iterates over all of the elements when creating the view to ensure they have a valid bit pattern. -
Viewing an
.npyfile has more restrictions than reading it, due to memory layout. Specifically:-
An error is returned if the data in the buffer is not properly aligned for the element type. Typically, this should not be a concern for memory-mapped files (unless an option like
MAP_FIXEDis used), since memory mappings are usually aligned to a page boundary, and the.npyformat has padding such that the header size is a multiple of 64 bytes. -
An error is returned if the endianness of the data does not match the endianness of the target element type. For example, multi-byte primitive types such as
f32require that the data in the file match the native endianness of the machine.
-
§Example
This is an example of opening a writable memory-mapped file as an
ArrayViewMut. Changes to the data in the view will modify the
underlying file.
This example uses the memmap2 crate
because that appears to be the best-maintained memory-mapping crate at the
moment, but view_mut_npy takes a &mut [u8] instead of a file so that
you can use the memory-mapping crate you’re most comfortable with.
use memmap2::MmapMut;
use ndarray::ArrayViewMut2;
use ndarray_npy::ViewMutNpyExt;
use std::fs;
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.open("resources/array.npy")?;
let mut mmap = unsafe { MmapMut::map_mut(&file)? };
let view_mut = ArrayViewMut2::<i32>::view_mut_npy(&mut mmap)?;Required Methods§
Sourcefn view_mut_npy(buf: &'a mut [u8]) -> Result<Self, ViewNpyError>
fn view_mut_npy(buf: &'a mut [u8]) -> Result<Self, ViewNpyError>
Creates an ArrayViewMut from a mutable buffer containing an .npy
file.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".