Skip to main content

qualia_vision/weights/
load_litert_bytes.rs

1//! Cold-path Google LiteRT (TFLite / FlatBuffers) model file validation.
2//!
3//! LiteRT / TFLite models use the FlatBuffers binary format with the canonical
4//! 4-byte file identifier `TFL3` at byte offset 4..8.
5
6use std::fs;
7use std::path::Path;
8
9/// Canonical FlatBuffers 4-byte identifier for Google LiteRT / TFLite models.
10pub const LITER_TFLITE_MAGIC: [u8; 4] = *b"TFL3";
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct LiteRtFileMeta {
14    pub bytes: usize,
15    pub looks_like_litert: bool,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum LiteRtLoadError {
20    Io,
21    TooSmall,
22    NotLiteRtLike,
23}
24
25const MIN_LITERT_BYTES: usize = 64;
26
27/// Load entire LiteRT / TFLite file into memory (cold path).
28pub fn load_litert_file(path: &Path) -> Result<(Vec<u8>, LiteRtFileMeta), LiteRtLoadError> {
29    let data = fs::read(path).map_err(|_| LiteRtLoadError::Io)?;
30    let meta = validate_litert_bytes(&data)?;
31    Ok((data, meta))
32}
33
34/// Validate Google LiteRT / TFLite FlatBuffers bytes without reading disk.
35pub fn validate_litert_bytes(data: &[u8]) -> Result<LiteRtFileMeta, LiteRtLoadError> {
36    if data.len() < MIN_LITERT_BYTES {
37        return Err(LiteRtLoadError::TooSmall);
38    }
39    let looks = looks_like_litert(data);
40    if !looks {
41        return Err(LiteRtLoadError::NotLiteRtLike);
42    }
43    Ok(LiteRtFileMeta {
44        bytes: data.len(),
45        looks_like_litert: true,
46    })
47}
48
49fn looks_like_litert(data: &[u8]) -> bool {
50    // Canonical FlatBuffer ID at offset 4..8 is "TFL3"
51    if data.len() >= 8 && &data[4..8] == &LITER_TFLITE_MAGIC {
52        return true;
53    }
54    // Backup search in first 256 bytes for TFL3, TFLITE, or LiteRT
55    let head = &data[..data.len().min(256)];
56    find_subslice(head, b"TFL3") || find_subslice(head, b"TFLITE") || find_subslice(head, b"LiteRT")
57}
58
59fn find_subslice(haystack: &[u8], needle: &[u8]) -> bool {
60    if needle.is_empty() || haystack.len() < needle.len() {
61        return false;
62    }
63    haystack.windows(needle.len()).any(|w| w == needle)
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn test_litert_validation() {
72        let mut fake_tflite = vec![0u8; 128];
73        fake_tflite[4..8].copy_from_slice(b"TFL3");
74
75        let meta = validate_litert_bytes(&fake_tflite).unwrap();
76        assert!(meta.looks_like_litert);
77        assert_eq!(meta.bytes, 128);
78
79        let small = vec![0u8; 10];
80        assert_eq!(
81            validate_litert_bytes(&small),
82            Err(LiteRtLoadError::TooSmall)
83        );
84
85        let invalid = vec![0u8; 128];
86        assert_eq!(
87            validate_litert_bytes(&invalid),
88            Err(LiteRtLoadError::NotLiteRtLike)
89        );
90    }
91}