1use crate::{sys, Error, Mat, Result};
2use std::{marker::PhantomData, rc::Rc};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum ParamKind {
12 Scalar,
14 Int,
16 Float,
18 Array,
20 Text,
22}
23
24pub struct ParamDict {
26 raw: sys::ncnn_paramdict_t,
27 _thread: PhantomData<Rc<()>>,
28}
29impl ParamDict {
30 pub fn new() -> Result<Self> {
32 let raw = unsafe { sys::ncnn_paramdict_create() };
33 if raw.is_null() {
34 return Err(Error::Native(-100));
35 }
36 Ok(Self {
37 raw,
38 _thread: PhantomData,
39 })
40 }
41 fn check(id: i32) -> Result<()> {
42 if !(0..32).contains(&id) {
43 return Err(Error::invalid("Parameter id must be 0..32"));
44 }
45 Ok(())
46 }
47 pub fn set_int(&mut self, id: i32, value: i32) -> Result<()> {
49 Self::check(id)?;
50 unsafe {
51 sys::ncnn_paramdict_set_int(self.raw, id, value);
52 }
53 Ok(())
54 }
55 pub fn set_float(&mut self, id: i32, value: f32) -> Result<()> {
57 Self::check(id)?;
58 unsafe {
59 sys::ncnn_paramdict_set_float(self.raw, id, value);
60 }
61 Ok(())
62 }
63 pub fn kind(&self, id: i32) -> Result<Option<ParamKind>> {
67 Self::check(id)?;
68 let code = unsafe { sys::ncnn_paramdict_get_type(self.raw, id) };
69 Ok(match code {
70 1 => Some(ParamKind::Scalar),
71 2 => Some(ParamKind::Int),
72 3 => Some(ParamKind::Float),
73 4..=6 => Some(ParamKind::Array),
74 7 => Some(ParamKind::Text),
75 _ => None,
76 })
77 }
78 pub fn get_int(&self, id: i32, default: i32) -> Result<i32> {
80 Self::check(id)?;
81 unsafe { Ok(sys::ncnn_paramdict_get_int(self.raw, id, default)) }
82 }
83 pub fn get_float(&self, id: i32, default: f32) -> Result<f32> {
85 Self::check(id)?;
86 unsafe { Ok(sys::ncnn_paramdict_get_float(self.raw, id, default)) }
87 }
88 pub fn set_array(&mut self, id: i32, value: &Mat) -> Result<()> {
90 Self::check(id)?;
91 let copy = value.deep_clone()?;
92 unsafe {
93 sys::ncnn_paramdict_set_array(self.raw, id, copy.raw);
94 }
95 Ok(())
96 }
97 pub fn set_bytes(&mut self, id: i32, value: &[u8]) -> Result<()> {
99 Self::check(id)?;
100 unsafe {
101 crate::error::status(sys::ncnn_rs_param_set_string(
102 self.raw,
103 id,
104 value.as_ptr(),
105 value.len(),
106 ))
107 }
108 }
109 pub fn get_bytes(&self, id: i32) -> Result<Vec<u8>> {
111 Self::check(id)?;
112 unsafe {
113 let size = sys::ncnn_rs_param_get_string(self.raw, id, std::ptr::null_mut(), 0);
114 if size == usize::MAX {
115 return Err(Error::Native(-100));
116 }
117 let mut bytes = vec![0; size];
118 if sys::ncnn_rs_param_get_string(self.raw, id, bytes.as_mut_ptr(), size) != size {
119 return Err(Error::Native(-100));
120 }
121 Ok(bytes)
122 }
123 }
124 pub fn as_raw(&self) -> sys::ncnn_paramdict_t {
126 self.raw
127 }
128}
129impl Drop for ParamDict {
130 fn drop(&mut self) {
131 unsafe {
132 sys::ncnn_paramdict_destroy(self.raw);
133 }
134 }
135}