Skip to main content

ferray_io/
format.rs

1// ferray-io: Format constants and shared types
2
3/// The magic string at the start of every `.npy` file.
4pub const NPY_MAGIC: &[u8] = b"\x93NUMPY";
5
6/// Length of the magic string.
7pub const NPY_MAGIC_LEN: usize = 6;
8
9/// Supported `.npy` format version 1.0 (header length stored in 2 bytes).
10pub const VERSION_1_0: (u8, u8) = (1, 0);
11
12/// Supported `.npy` format version 2.0 (header length stored in 4 bytes).
13pub const VERSION_2_0: (u8, u8) = (2, 0);
14
15/// Supported `.npy` format version 3.0 (header length stored in 4 bytes, UTF-8 header).
16pub const VERSION_3_0: (u8, u8) = (3, 0);
17
18/// Alignment of the header + preamble in bytes.
19pub const HEADER_ALIGNMENT: usize = 64;
20
21/// Maximum header length for version 1.0 (u16::MAX).
22pub const MAX_HEADER_LEN_V1: usize = u16::MAX as usize;
23
24/// Mode for memory-mapped file access.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum MemmapMode {
27    /// Read-only memory mapping. The file is opened for reading and the
28    /// resulting slice is immutable.
29    ReadOnly,
30    /// Read-write memory mapping. Modifications are written back to the
31    /// underlying file.
32    ReadWrite,
33    /// Copy-on-write memory mapping. Modifications are kept in memory
34    /// and are not written back to the file.
35    CopyOnWrite,
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn magic_bytes() {
44        assert_eq!(NPY_MAGIC.len(), NPY_MAGIC_LEN);
45        assert_eq!(NPY_MAGIC[0], 0x93);
46        assert_eq!(&NPY_MAGIC[1..], b"NUMPY");
47    }
48
49    #[test]
50    fn memmap_mode_variants() {
51        let modes = [
52            MemmapMode::ReadOnly,
53            MemmapMode::ReadWrite,
54            MemmapMode::CopyOnWrite,
55        ];
56        assert_eq!(modes.len(), 3);
57        assert_ne!(MemmapMode::ReadOnly, MemmapMode::ReadWrite);
58    }
59}