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
use std::{
ffi::CString,
os::raw::{c_char, c_int},
path::Path,
ptr,
};
use crate::object::Object;
use tvm_macros::Object;
use tvm_sys::ffi;
use crate::errors::Error;
use crate::String as TString;
use crate::{errors, function::Function};
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Module"]
#[type_key = "runtime.Module"]
pub struct ModuleNode {
base: Object,
}
crate::external! {
#[name("runtime.RuntimeEnabled")]
fn runtime_enabled(target: CString) -> i32;
#[name("runtime.ModuleLoadFromFile")]
fn load_from_file(file_name: CString, format: CString) -> Module;
#[name("runtime.ModuleSaveToFile")]
fn save_to_file(module: Module, name: TString, fmt: TString);
#[name("tvm.relay.module_export_library")]
fn export_library(module: Module, file_name: TString);
}
impl Module {
pub fn default_fn(&mut self) -> Result<Function, Error> {
self.get_function("default", true)
}
pub fn get_function(&self, name: &str, query_import: bool) -> Result<Function, Error> {
let name = CString::new(name)?;
let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;
check_call!(ffi::TVMModGetFunction(
self.handle(),
name.as_ptr() as *const c_char,
query_import as c_int,
&mut fhandle as *mut _
));
if fhandle.is_null() {
return Err(errors::Error::NullHandle(name.into_string()?.to_string()));
}
Ok(Function::from_raw(fhandle))
}
pub fn import_module(&self, dependent_module: Module) {
check_call!(ffi::TVMModImport(self.handle(), dependent_module.handle()))
}
pub fn load<P: AsRef<Path>>(path: &P) -> Result<Module, Error> {
let ext = CString::new(
path.as_ref()
.extension()
.unwrap_or_else(|| std::ffi::OsStr::new(""))
.to_str()
.ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,
)?;
let cpath = CString::new(
path.as_ref()
.to_str()
.ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,
)?;
let module = load_from_file(cpath, ext)?;
Ok(module)
}
pub fn save_to_file(&self, name: String, fmt: String) -> Result<(), Error> {
save_to_file(self.clone(), name.into(), fmt.into())
}
pub fn export_library(&self, name: String) -> Result<(), Error> {
export_library(self.clone(), name.into())
}
pub fn enabled(&self, target: &str) -> bool {
let target = CString::new(target).unwrap();
let enabled = runtime_enabled(target).unwrap();
enabled != 0
}
pub unsafe fn handle(&self) -> ffi::TVMModuleHandle {
self.0.clone().unwrap().into_raw() as *mut _
}
}