Skip to main content

ViewNpyExt

Trait ViewNpyExt 

Source
pub trait ViewNpyExt<'a>: Sized {
    // Required method
    fn view_npy(buf: &'a [u8]) -> Result<Self, ViewNpyError>;
}
Expand description

Extension trait for creating an ArrayView from a buffer containing an .npy file.

The primary use-case for this is viewing a memory-mapped .npy 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 .npy file 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_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.

    • 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 f32 require that the data in the file match the native endianness of the machine.

§Example

This is an example of opening a readonly memory-mapped file as an ArrayView.

This example uses the memmap2 crate because that appears to be the best-maintained memory-mapping crate at the moment, but view_npy takes a &[u8] instead of a file so that you can use the memory-mapping crate you’re most comfortable with.

use memmap2::Mmap;
use ndarray::ArrayView2;
use ndarray_npy::ViewNpyExt;
use std::fs::File;

let file = File::open("resources/array.npy")?;
let mmap = unsafe { Mmap::map(&file)? };
let view = ArrayView2::<i32>::view_npy(&mmap)?;

Required Methods§

Source

fn view_npy(buf: &'a [u8]) -> Result<Self, ViewNpyError>

Creates an ArrayView from a buffer containing an .npy file.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<'a, A, D> ViewNpyExt<'a> for ArrayView<'a, A, D>
where A: ViewElement, D: Dimension,

Source§

fn view_npy(buf: &'a [u8]) -> Result<Self, ViewNpyError>

Implementors§