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
use std;
use std::ffi::CString;
use std::path::Path;
use error::{cvt_r, Error};
use ffi;
use ffi::menoh_model_data_handle;
use variable_profile::VariableProfileTable;
pub struct ModelData {
handle: menoh_model_data_handle,
}
impl ModelData {
pub fn new<P>(onnx_path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let mut handle: menoh_model_data_handle = std::ptr::null_mut();
let p = CString::new(onnx_path.as_ref().to_str().ok_or(Error::InvalidFileName)?)
.map_err(|_| Error::InvalidFileName)?;
cvt_r(|| unsafe {
ffi::menoh_make_model_data_from_onnx(
p.as_ptr(),
&mut handle as *mut menoh_model_data_handle,
)
})?;
Ok(ModelData { handle })
}
pub fn optimize(&mut self, vpt: &VariableProfileTable) -> Result<(), Error> {
cvt_r(|| unsafe { ffi::menoh_model_data_optimize(self.handle, vpt.get_handle()) })?;
Ok(())
}
#[doc(hidden)]
pub unsafe fn get_handle(&self) -> ffi::menoh_model_data_handle {
self.handle
}
}
impl Drop for ModelData {
fn drop(&mut self) {
unsafe { ffi::menoh_delete_model_data(self.handle) }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
const ROOT_DIR: &str = env!("CARGO_MANIFEST_DIR");
fn get_model_path(name: &str) -> PathBuf {
let mut path = PathBuf::new();
path.push(ROOT_DIR);
path.push("tests");
path.push("resource");
path.push(name);
path
}
#[test]
fn load_onnx_success() {
let model_path = get_model_path("mnist.onnx");
assert!(ModelData::new(model_path).is_ok());
}
#[test]
fn load_onnx_fail_with_wrong_path() {
assert_matches!(ModelData::new("").err().unwrap(), Error::InvalidFileName);
}
#[test]
fn load_onnx_fail_with_broken_string() {
assert_matches!(
ModelData::new("p\0ath").err().unwrap(),
Error::InvalidFileName
);
}
#[test]
fn load_onnx_fail_with_wrong_format() {
let invalid_model_path = get_model_path("invalid_onnx.onnx");
assert_matches!(
ModelData::new(invalid_model_path).err().unwrap(),
Error::ONNXParseError
)
}
}