Skip to main content

neural_network/
encoding.rs

1//! Supported model file encodings for runtime loaders.
2use file_system::{IoErrorKind, Result};
3
4/// Model serialization formats supported by inference backends.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6#[repr(u32)]
7pub enum ModelEncoding {
8    /// TensorFlow Lite FlatBuffer format (`0`).
9    TensorFlowLite = 0,
10}
11
12impl ModelEncoding {
13    /// Convert a raw integer value into a [`ModelEncoding`], returning `None` if unknown.
14    pub const fn from_raw(raw: u32) -> Option<Self> {
15        match raw {
16            0 => Some(Self::TensorFlowLite),
17            _ => None,
18        }
19    }
20
21    /// Return the raw integer representation.
22    pub const fn raw(self) -> u32 {
23        self as u32
24    }
25}
26
27impl TryFrom<u32> for ModelEncoding {
28    type Error = IoErrorKind;
29
30    fn try_from(value: u32) -> Result<Self> {
31        Self::from_raw(value).ok_or(IoErrorKind::InvalidArgument)
32    }
33}
34
35impl From<ModelEncoding> for u32 {
36    fn from(encoding: ModelEncoding) -> Self {
37        encoding.raw()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn encoding_converts_to_and_from_raw() {
47        assert_eq!(
48            ModelEncoding::from_raw(0),
49            Some(ModelEncoding::TensorFlowLite)
50        );
51        assert_eq!(ModelEncoding::from_raw(1), None);
52        assert_eq!(
53            ModelEncoding::try_from(0),
54            Ok(ModelEncoding::TensorFlowLite)
55        );
56        assert_eq!(
57            ModelEncoding::try_from(42),
58            Err(file_system::IoErrorKind::InvalidArgument)
59        );
60        assert_eq!(ModelEncoding::TensorFlowLite.raw(), 0);
61        assert_eq!(u32::from(ModelEncoding::TensorFlowLite), 0);
62    }
63}