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. -
The data in the buffer must be properly aligned for the element type. Typically, this should not be a concern for memory-mapped files (unless an option like
MAP_FIXED
is used), since memory mappings are usually aligned to a page boundary, and the.npy
format has padding such that the header size is a multiple of 64 bytes.
§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", so this trait is not object safe.