-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
model.rs
68 lines (54 loc) · 1.61 KB
/
model.rs
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
use std::{collections::HashMap, io, path::PathBuf, process::Command};
use thiserror::Error;
pub struct Model {
name: String,
}
impl Model {
pub fn new(name: String) -> Self {
Self { name }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn path(&self) -> String {
format!("models/{}", self.name)
}
pub fn src_path(&self) -> PathBuf {
format!("{}/src", self.path()).into()
}
pub fn load(
&self,
arguments: &HashMap<String, String>,
) -> Result<fj::Shape, Error> {
let status = Command::new("cargo")
.arg("build")
.args(["--manifest-path", &format!("{}/Cargo.toml", self.path())])
.status()?;
if !status.success() {
return Err(Error::Compile);
}
// TASK: Read up why those calls are unsafe. Make sure calling them is
// sound, and document why that is.
let shape = unsafe {
let lib = libloading::Library::new(format!(
"{}/target/debug/lib{}.so",
self.path(),
self.name(),
))?;
let model: libloading::Symbol<ModelFn> = lib.get(b"model")?;
model(&arguments)
};
Ok(shape)
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("Error compiling model")]
Compile,
#[error("I/O error while loading model")]
Io(#[from] io::Error),
#[error("Error loading model from dynamic library")]
LibLoading(#[from] libloading::Error),
}
type ModelFn =
unsafe extern "C" fn(args: &HashMap<String, String>) -> fj::Shape;