siann 1.0.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! 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"))
    }
}

/// The CRC-32 table (the zip format's: IEEE, reflected, polynomial 0xEDB88320).
fn crc_table() -> &'static [u32; 256] {
    static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new();
    TABLE.get_or_init(|| {
        let mut t = [0u32; 256];
        for (i, e) in t.iter_mut().enumerate() {
            let mut c = i as u32;
            for _ in 0..8 {
                c = if c & 1 != 0 {
                    0xEDB8_8320 ^ (c >> 1)
                } else {
                    c >> 1
                };
            }
            *e = c;
        }
        t
    })
}

/// A running CRC-32 (start from !0, finish with !) over more `data`.
fn crc32_update(c: u32, data: &[u8]) -> u32 {
    let t = crc_table();
    data.iter().fold(c, |c, &b| {
        t[((c ^ u32::from(b)) & 0xFF) as usize] ^ (c >> 8)
    })
}

/// A `.npy` record's header (format 1.0) as NumPy writes one, padded with spaces to a multiple of 64 bytes.
fn npy_header(descr: &str, shape: &[usize]) -> Vec<u8> {
    let dims = match shape {
        [] => "()".to_string(),
        [n] => format!("({n},)"),
        _ => format!(
            "({})",
            shape
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ),
    };
    let mut head = format!("{{'descr': '{descr}', 'fortran_order': False, 'shape': {dims}, }}");
    let pad = (64 - (10 + head.len() + 1) % 64) % 64;
    head.push_str(&" ".repeat(pad));
    head.push('\n');
    let mut out = b"\x93NUMPY\x01\x00".to_vec();
    out.extend_from_slice(&(head.len() as u16).to_le_bytes());
    out.extend_from_slice(head.as_bytes());
    out
}

/// One array for `write`: its name (without `.npy`), NumPy's element type ("<f4", "<i4", "<i8", "|u1"), its
/// shape, and its values' bytes in C order.
pub struct Entry<'a> {
    pub name: &'a str,
    pub descr: &'a str,
    pub shape: &'a [usize],
    pub data: &'a [u8],
}

/// Writes a `.npz` file as `np.savez` does (a zip of `.npy` records, stored, with zip64 sizes on every member), so
/// that NumPy's `np.load` and `Npz` both read it.
pub fn write(path: &Path, entries: &[Entry<'_>]) -> Result<()> {
    use std::io::Write;
    let ioe = |e: std::io::Error| format!("writing {}: {e}", path.display());
    let mut f = std::io::BufWriter::new(File::create(path).map_err(ioe)?);
    let (time, date) = (0u16, 0x21u16); // 1980-01-01, so that the same index writes the same bytes
    let mut central = Vec::new();
    let mut offset = 0u64;
    for e in entries {
        let width = match e.descr {
            "<f4" | "<i4" | "<u4" => 4,
            "<i8" | "<f8" => 8,
            "|u1" | "|i1" | "|b1" => 1,
            other => return Err(format!("{}: element type {other} is not written", e.name)),
        };
        if e.data.len() != e.shape.iter().product::<usize>() * width {
            return Err(format!("{}: its bytes do not match its shape", e.name));
        }
        let head = npy_header(e.descr, e.shape);
        let size = (head.len() + e.data.len()) as u64;
        let crc = !crc32_update(crc32_update(!0, &head), e.data); // over the header and data, not joined
        let name = format!("{}.npy", e.name);
        let mut local = Vec::with_capacity(30 + name.len() + 20);
        local.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
        local.extend_from_slice(&45u16.to_le_bytes()); // version needed: zip64
        local.extend_from_slice(&0u16.to_le_bytes()); // flags
        local.extend_from_slice(&0u16.to_le_bytes()); // stored
        local.extend_from_slice(&time.to_le_bytes());
        local.extend_from_slice(&date.to_le_bytes());
        local.extend_from_slice(&crc.to_le_bytes());
        local.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes()); // sizes in the zip64 field
        local.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
        local.extend_from_slice(&(name.len() as u16).to_le_bytes());
        local.extend_from_slice(&20u16.to_le_bytes());
        local.extend_from_slice(name.as_bytes());
        local.extend_from_slice(&0x0001u16.to_le_bytes());
        local.extend_from_slice(&16u16.to_le_bytes());
        local.extend_from_slice(&size.to_le_bytes());
        local.extend_from_slice(&size.to_le_bytes());
        f.write_all(&local).map_err(ioe)?;
        f.write_all(&head).map_err(ioe)?;
        f.write_all(e.data).map_err(ioe)?;
        central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
        central.extend_from_slice(&0x032Du16.to_le_bytes()); // made by: Unix, zip 4.5
        central.extend_from_slice(&45u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&time.to_le_bytes());
        central.extend_from_slice(&date.to_le_bytes());
        central.extend_from_slice(&crc.to_le_bytes());
        central.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
        central.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
        central.extend_from_slice(&(name.len() as u16).to_le_bytes());
        central.extend_from_slice(&28u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes()); // no comment
        central.extend_from_slice(&0u16.to_le_bytes()); // disk
        central.extend_from_slice(&0u16.to_le_bytes()); // internal attributes
        central.extend_from_slice(&(0o100644u32 << 16).to_le_bytes()); // a regular file, rw-r--r--
        central.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes()); // offset in the zip64 field
        central.extend_from_slice(name.as_bytes());
        central.extend_from_slice(&0x0001u16.to_le_bytes());
        central.extend_from_slice(&24u16.to_le_bytes());
        central.extend_from_slice(&size.to_le_bytes());
        central.extend_from_slice(&size.to_le_bytes());
        central.extend_from_slice(&offset.to_le_bytes());
        offset += local.len() as u64 + size;
    }
    let count = entries.len() as u64;
    let dir_at = offset;
    f.write_all(&central).map_err(ioe)?;
    let end64_at = dir_at + central.len() as u64;
    let mut end = Vec::new();
    end.extend_from_slice(&0x0606_4b50u32.to_le_bytes()); // the zip64 end record
    end.extend_from_slice(&44u64.to_le_bytes());
    end.extend_from_slice(&45u16.to_le_bytes());
    end.extend_from_slice(&45u16.to_le_bytes());
    end.extend_from_slice(&0u32.to_le_bytes());
    end.extend_from_slice(&0u32.to_le_bytes());
    end.extend_from_slice(&count.to_le_bytes());
    end.extend_from_slice(&count.to_le_bytes());
    end.extend_from_slice(&(central.len() as u64).to_le_bytes());
    end.extend_from_slice(&dir_at.to_le_bytes());
    end.extend_from_slice(&0x0706_4b50u32.to_le_bytes()); // its locator
    end.extend_from_slice(&0u32.to_le_bytes());
    end.extend_from_slice(&end64_at.to_le_bytes());
    end.extend_from_slice(&1u32.to_le_bytes());
    end.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); // the end record, pointing to the zip64 one
    end.extend_from_slice(&0u16.to_le_bytes());
    end.extend_from_slice(&0u16.to_le_bytes());
    end.extend_from_slice(&0xFFFFu16.to_le_bytes());
    end.extend_from_slice(&0xFFFFu16.to_le_bytes());
    end.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
    end.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
    end.extend_from_slice(&0u16.to_le_bytes());
    f.write_all(&end).map_err(ioe)?;
    f.flush().map_err(ioe)?;
    Ok(())
}

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

    #[test]
    fn crc32_of_a_known_string() {
        assert_eq!(!crc32_update(!0, b"123456789"), 0xCBF4_3926);
        assert_eq!(
            !crc32_update(crc32_update(!0, b"1234"), b"56789"),
            0xCBF4_3926
        );
    }

    #[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()
        );
    }
}