siann 0.6.0

Serve nearest-neighbor indexes built by the siann Python package (exact, IVF, CAGRA graphs) from Rust, on the CPU, with the same results
Documentation
//! Reading a NumPy `.npz` file as `np.savez` writes it (a siann index file): a zip archive of `.npy` arrays,
//! stored uncompressed, with zip64 sizes (NumPy writes every member with them). Only what that needs: the central
//! directory (with its zip64 end record where the archive needs one), stored members, and `.npy` arrays of
//! little-endian numbers in C order. Arrays are read a chunk at a time, so a large one is held once, as its
//! values.

use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;

use super::Result;

const CHUNK: usize = 1 << 20;

/// A member's place in the archive: where its local header starts, and its size.
struct Member {
    offset: u64,
    size: u64,
}

/// An open `.npz` file and its members by name (without `.npy`).
pub(crate) struct Npz {
    file: BufReader<File>,
    members: HashMap<String, Member>,
}

/// One `.npy` array: its element type (NumPy's string, such as "<f4"), its shape and its values' bytes.
pub(crate) struct Array {
    pub descr: String,
    pub shape: Vec<usize>,
    pub bytes: Vec<u8>,
}

fn u16_at(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([b[at], b[at + 1]])
}

fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}

fn u64_at(b: &[u8], at: usize) -> u64 {
    let mut a = [0u8; 8];
    a.copy_from_slice(&b[at..at + 8]);
    u64::from_le_bytes(a)
}

fn io(e: std::io::Error) -> String {
    format!("reading the file: {e}")
}

impl Npz {
    pub(crate) fn open(path: &Path) -> Result<Npz> {
        let mut file =
            BufReader::new(File::open(path).map_err(|e| format!("{}: {e}", path.display()))?);
        let len = file.seek(SeekFrom::End(0)).map_err(io)?;
        // the end of central directory record: 22 bytes, then a comment of up to 65,535
        let tail = len.min(22 + 65_535);
        file.seek(SeekFrom::Start(len - tail)).map_err(io)?;
        let mut end = vec![0u8; tail as usize];
        file.read_exact(&mut end).map_err(io)?;
        let at = (0..end.len().saturating_sub(21))
            .rev()
            .find(|&i| u32_at(&end, i) == 0x0605_4b50)
            .ok_or("not a siann index file: no zip directory")?;
        let mut count = u64::from(u16_at(&end, at + 10));
        let mut dir_size = u64::from(u32_at(&end, at + 12));
        let mut dir_at = u64::from(u32_at(&end, at + 16));
        if count == 0xFFFF || dir_size == 0xFFFF_FFFF || dir_at == 0xFFFF_FFFF {
            // the zip64 end record, which the locator just before the end record points to
            if at < 20 || u32_at(&end, at - 20) != 0x0706_4b50 {
                return Err("not a siann index file: a zip64 archive without its locator".into());
            }
            let rec = u64_at(&end, at - 20 + 8);
            file.seek(SeekFrom::Start(rec)).map_err(io)?;
            let mut z = [0u8; 56];
            file.read_exact(&mut z).map_err(io)?;
            if u32_at(&z, 0) != 0x0606_4b50 {
                return Err("not a siann index file: a bad zip64 end record".into());
            }
            count = u64_at(&z, 32);
            dir_size = u64_at(&z, 40);
            dir_at = u64_at(&z, 48);
        }
        file.seek(SeekFrom::Start(dir_at)).map_err(io)?;
        let mut dir = vec![0u8; dir_size as usize];
        file.read_exact(&mut dir).map_err(io)?;
        let mut members = HashMap::new();
        let mut p = 0usize;
        for _ in 0..count {
            if p + 46 > dir.len() || u32_at(&dir, p) != 0x0201_4b50 {
                return Err("not a siann index file: a bad zip directory entry".into());
            }
            let method = u16_at(&dir, p + 10);
            let mut size = u64::from(u32_at(&dir, p + 24));
            let mut csize = u64::from(u32_at(&dir, p + 20));
            let (nlen, elen, clen) = (
                usize::from(u16_at(&dir, p + 28)),
                usize::from(u16_at(&dir, p + 30)),
                usize::from(u16_at(&dir, p + 32)),
            );
            let mut offset = u64::from(u32_at(&dir, p + 42));
            let name = String::from_utf8_lossy(&dir[p + 46..p + 46 + nlen]).into_owned();
            // the zip64 extra field: the sizes and offset the entry marks as 0xFFFFFFFF, in that order
            let extra = &dir[p + 46 + nlen..p + 46 + nlen + elen];
            let mut e = 0usize;
            while e + 4 <= extra.len() {
                let (id, len) = (u16_at(extra, e), usize::from(u16_at(extra, e + 2)));
                if id == 0x0001 {
                    let mut f = e + 4;
                    for v in [&mut size, &mut csize, &mut offset] {
                        if *v == 0xFFFF_FFFF && f + 8 <= e + 4 + len {
                            *v = u64_at(extra, f);
                            f += 8;
                        }
                    }
                }
                e += 4 + len;
            }
            if method != 0 || csize != size {
                return Err(format!(
                    "{name} is compressed: siann reads index files as index.save writes them (np.savez, stored)"
                ));
            }
            let key = name.strip_suffix(".npy").unwrap_or(&name).to_string();
            members.insert(key, Member { offset, size });
            p += 46 + nlen + elen + clen;
        }
        Ok(Npz { file, members })
    }

    pub(crate) fn has(&self, name: &str) -> bool {
        self.members.contains_key(name)
    }

    /// The array `name`, read whole.
    pub(crate) fn array(&mut self, name: &str) -> Result<Array> {
        let m = self
            .members
            .get(name)
            .ok_or(format!("the index file has no {name}"))?;
        let (offset, size) = (m.offset, m.size);
        self.file.seek(SeekFrom::Start(offset)).map_err(io)?;
        let mut local = [0u8; 30];
        self.file.read_exact(&mut local).map_err(io)?;
        if u32_at(&local, 0) != 0x0403_4b50 {
            return Err(format!("{name}: a bad zip member header"));
        }
        let skip = u64::from(u16_at(&local, 26)) + u64::from(u16_at(&local, 28));
        self.file.seek(SeekFrom::Current(skip as i64)).map_err(io)?;
        // the .npy header: magic, version, the header's length, then a Python dict
        let mut head = [0u8; 10];
        self.file.read_exact(&mut head).map_err(io)?;
        if &head[..6] != b"\x93NUMPY" {
            return Err(format!("{name}: not a .npy array"));
        }
        let (hlen, used) = if head[6] == 1 {
            (usize::from(u16_at(&head, 8)), 10usize)
        } else {
            let mut more = [0u8; 2];
            self.file.read_exact(&mut more).map_err(io)?;
            (
                u32_at(&[head[8], head[9], more[0], more[1]], 0) as usize,
                12usize,
            )
        };
        let mut dict = vec![0u8; hlen];
        self.file.read_exact(&mut dict).map_err(io)?;
        let dict = String::from_utf8_lossy(&dict).into_owned();
        let (descr, shape) =
            parse_header(&dict).ok_or(format!("{name}: an unreadable .npy header"))?;
        let n: usize = shape.iter().product();
        let width = match descr.as_str() {
            "<f4" | "<i4" | "<u4" => 4,
            "<i8" | "<f8" => 8,
            "|u1" | "|i1" | "|b1" => 1,
            other => {
                return Err(format!(
                    "{name}: element type {other}, which siann's index files do not hold"
                ));
            }
        };
        let bytes_len = n * width;
        if (used + hlen + bytes_len) as u64 > size {
            return Err(format!("{name}: shorter than its header says"));
        }
        let mut bytes = vec![0u8; bytes_len];
        for chunk in bytes.chunks_mut(CHUNK) {
            self.file.read_exact(chunk).map_err(io)?;
        }
        Ok(Array {
            descr,
            shape,
            bytes,
        })
    }
}

/// The element type and shape of a `.npy` header such as
/// `{'descr': '<f4', 'fortran_order': False, 'shape': (100, 16), }`; None for Fortran order or other forms.
fn parse_header(dict: &str) -> Option<(String, Vec<usize>)> {
    if dict.contains("'fortran_order': True") {
        return None;
    }
    let d = dict.split("'descr':").nth(1)?;
    let d = d.split('\'').nth(1)?.to_string();
    let s = dict.split("'shape':").nth(1)?;
    let s = s.split('(').nth(1)?.split(')').next()?;
    let shape = s
        .split(',')
        .map(str::trim)
        .filter(|t| !t.is_empty())
        .map(|t| t.parse::<usize>().ok())
        .collect::<Option<Vec<_>>>()?;
    Some((d, shape))
}

impl Array {
    fn check(&self, name: &str, descr: &str) -> Result<()> {
        if self.descr != descr {
            return Err(format!("{name}: element type {}, not {descr}", self.descr));
        }
        Ok(())
    }

    /// The values as f32: from float32, or widened from bytes (an index stored as bytes saves its vectors so).
    pub(crate) fn f32s(self, name: &str) -> Result<Vec<f32>> {
        match self.descr.as_str() {
            "<f4" => Ok(self
                .bytes
                .as_chunks::<4>()
                .0
                .iter()
                .map(|c| f32::from_le_bytes(*c))
                .collect()),
            "|u1" => Ok(self.bytes.iter().map(|&b| f32::from(b)).collect()),
            other => Err(format!(
                "{name}: element type {other}, not float32 or bytes"
            )),
        }
    }

    pub(crate) fn i64s(self, name: &str) -> Result<Vec<i64>> {
        match self.descr.as_str() {
            "<i8" => Ok(self
                .bytes
                .as_chunks::<8>()
                .0
                .iter()
                .map(|c| {
                    let mut a = [0u8; 8];
                    a.copy_from_slice(c);
                    i64::from_le_bytes(a)
                })
                .collect()),
            "<i4" => Ok(self
                .bytes
                .as_chunks::<4>()
                .0
                .iter()
                .map(|c| i64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])))
                .collect()),
            other => Err(format!("{name}: element type {other}, not an integer")),
        }
    }

    pub(crate) fn text(self, name: &str) -> Result<String> {
        self.check(name, "|u1")?;
        String::from_utf8(self.bytes).map_err(|_| format!("{name}: not UTF-8 text"))
    }
}

#[cfg(test)]
mod tests {
    use super::parse_header;

    #[test]
    fn headers() {
        let (d, s) =
            parse_header("{'descr': '<f4', 'fortran_order': False, 'shape': (100, 16), }").unwrap();
        assert_eq!((d.as_str(), s), ("<f4", vec![100, 16]));
        let (d, s) =
            parse_header("{'descr': '|u1', 'fortran_order': False, 'shape': (3,), }").unwrap();
        assert_eq!((d.as_str(), s), ("|u1", vec![3]));
        assert!(
            parse_header("{'descr': '<f4', 'fortran_order': True, 'shape': (2, 2), }").is_none()
        );
    }
}