tm_rs/
graph_interpreter.rs

1use crate::{
2    api::{Api, ApiWithCtx, ApiWithCtxMut},
3    hash,
4};
5use std::{convert::TryInto, ffi::c_void, slice};
6use tm_sys::ffi::{
7    tm_graph_interpreter_api, tm_graph_interpreter_o, TM_GRAPH_INTERPRETER_API_NAME,
8};
9
10#[derive(Copy, Clone)]
11pub struct GraphInterpreterApi {
12    api: *mut tm_graph_interpreter_api,
13}
14
15unsafe impl Send for GraphInterpreterApi {}
16unsafe impl Sync for GraphInterpreterApi {}
17
18impl Api for GraphInterpreterApi {
19    type CType = *mut tm_graph_interpreter_api;
20    const NAME: &'static [u8] = TM_GRAPH_INTERPRETER_API_NAME;
21
22    #[inline]
23    fn new(api: *mut c_void) -> Self {
24        Self {
25            api: api as Self::CType,
26        }
27    }
28}
29
30#[derive(Copy, Clone)]
31pub struct GraphInterpreterApiInstance {
32    pub api: *mut tm_graph_interpreter_api,
33    pub ctx: *const tm_graph_interpreter_o,
34}
35
36#[derive(Copy, Clone)]
37pub struct GraphInterpreterApiInstanceMut {
38    pub api: *mut tm_graph_interpreter_api,
39    pub ctx: *mut tm_graph_interpreter_o,
40}
41
42impl ApiWithCtx for GraphInterpreterApi {
43    type Ctx = tm_graph_interpreter_o;
44    type ApiInstance = GraphInterpreterApiInstance;
45
46    #[inline]
47    fn wrap(self, ctx: *const Self::Ctx) -> Self::ApiInstance {
48        GraphInterpreterApiInstance { api: self.api, ctx }
49    }
50}
51
52impl ApiWithCtxMut for GraphInterpreterApi {
53    type ApiInstanceMut = GraphInterpreterApiInstanceMut;
54
55    #[inline]
56    fn wrap_mut(self, ctx: *mut Self::Ctx) -> Self::ApiInstanceMut {
57        GraphInterpreterApiInstanceMut { api: self.api, ctx }
58    }
59}
60
61impl GraphInterpreterApiInstanceMut {
62    #[inline]
63    pub fn read_variable_f32(&mut self, variable: &str) -> Option<f32> {
64        let variable = hash(variable.as_bytes());
65        let var = unsafe { (*self.api).read_variable.unwrap()(self.ctx, variable) };
66
67        if !var.data.is_null() {
68            let data = unsafe { slice::from_raw_parts(var.data as *mut u8, var.size as usize) };
69            Some(f32::from_ne_bytes(data.try_into().unwrap()))
70        } else {
71            None
72        }
73    }
74}