use std::os::raw::c_void;
use std::path::Path;
use std::ptr::NonNull;
use edgefirst_tflite_sys::TfLiteModel;
use crate::error::{Error, Result};
use crate::Library;
#[derive(Debug)]
#[allow(clippy::struct_field_names)]
pub struct Model<'lib> {
ptr: NonNull<TfLiteModel>,
model_mem: Vec<u8>,
lib: &'lib Library,
}
impl<'lib> Model<'lib> {
pub fn from_bytes(lib: &'lib Library, data: impl Into<Vec<u8>>) -> Result<Self> {
let model_mem: Vec<u8> = data.into();
let raw = unsafe {
lib.as_sys()
.TfLiteModelCreate(model_mem.as_ptr().cast::<c_void>(), model_mem.len())
};
let ptr = NonNull::new(raw)
.ok_or_else(|| Error::null_pointer("TfLiteModelCreate returned null"))?;
Ok(Self {
ptr,
model_mem,
lib,
})
}
pub fn from_file(lib: &'lib Library, path: impl AsRef<Path>) -> Result<Self> {
let data = std::fs::read(path.as_ref())
.map_err(|e| Error::invalid_argument(format!("{}: {e}", path.as_ref().display())))?;
Self::from_bytes(lib, data)
}
#[must_use]
pub fn data(&self) -> &[u8] {
&self.model_mem
}
pub(crate) fn as_ptr(&self) -> *mut TfLiteModel {
self.ptr.as_ptr()
}
}
impl Drop for Model<'_> {
fn drop(&mut self) {
unsafe {
self.lib.as_sys().TfLiteModelDelete(self.ptr.as_ptr());
}
}
}