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
//! This module contains dtype related.
//!
use std;

use ffi;

/// Dtype that accepted by menoh model.
#[derive(Debug, Clone, Copy)]
pub enum Dtype {
    Float,
}

/// Indicate compatible type with menoh dtype
pub trait DtypeCompatible: 'static + Clone + Copy + Default {}

impl DtypeCompatible for f32 {}

impl Dtype {
    pub fn value(&self) -> ffi::menoh_dtype {
        match *self {
            Dtype::Float => ffi::menoh_dtype_float,
        }
    }

    pub fn from(dtype: ffi::menoh_dtype) -> Self {
        match dtype {
            ffi::menoh_dtype_float => Dtype::Float,
            _ => unreachable!(),
        }
    }

    pub fn type_id(&self) -> std::any::TypeId {
        match *self {
            Dtype::Float => std::any::TypeId::of::<f32>(),
        }
    }

    pub fn is_compatible<T: DtypeCompatible>(&self) -> bool {
        self.type_id() == std::any::TypeId::of::<T>()
    }
}

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

    #[test]
    fn is_compatible() {
        let dtype = Dtype::Float;
        assert!(dtype.is_compatible::<f32>())
    }
}