Trait ndarray_npy::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.

  • 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 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.

Object Safety§

This trait is not object safe.

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§