Skip to main content

apple_accelerate/
bnns.rs

1use crate::ffi;
2use core::ffi::c_void;
3use core::ptr;
4
5/// Thin owner for the deprecated-but-still-available BNNS filter APIs.
6pub struct Filter {
7    ptr: ffi::BNNSFilter,
8}
9
10unsafe impl Send for Filter {}
11unsafe impl Sync for Filter {}
12
13impl Drop for Filter {
14    fn drop(&mut self) {
15        if !self.ptr.is_null() {
16            // SAFETY: `ptr` was returned by a BNNS filter constructor and is owned by this wrapper.
17            unsafe { ffi::BNNSFilterDestroy(self.ptr) };
18            self.ptr = ptr::null_mut();
19        }
20    }
21}
22
23impl Filter {
24    /// Create a BNNS convolution filter from caller-owned raw layer/filter parameter structs.
25    ///
26    /// # Safety
27    ///
28    /// The pointers must refer to valid BNNS parameter structs for the duration of the call.
29    #[must_use]
30    pub unsafe fn from_convolution(
31        layer_params: *const c_void,
32        filter_params: *const c_void,
33    ) -> Option<Self> {
34        let ptr = ffi::BNNSFilterCreateLayerConvolution(layer_params, filter_params);
35        if ptr.is_null() {
36            None
37        } else {
38            Some(Self { ptr })
39        }
40    }
41
42    /// Create a BNNS fully connected filter from caller-owned raw layer/filter parameter structs.
43    ///
44    /// # Safety
45    ///
46    /// The pointers must refer to valid BNNS parameter structs for the duration of the call.
47    #[must_use]
48    pub unsafe fn from_fully_connected(
49        layer_params: *const c_void,
50        filter_params: *const c_void,
51    ) -> Option<Self> {
52        let ptr = ffi::BNNSFilterCreateLayerFullyConnected(layer_params, filter_params);
53        if ptr.is_null() {
54            None
55        } else {
56            Some(Self { ptr })
57        }
58    }
59
60    #[must_use]
61    pub const fn as_ptr(&self) -> *mut c_void {
62        self.ptr
63    }
64
65    /// Apply the filter to caller-owned raw buffers.
66    ///
67    /// # Safety
68    ///
69    /// `input` and `output` must match the layout and lengths described when the filter was created.
70    pub unsafe fn apply(&self, input: *const c_void, output: *mut c_void) -> i32 {
71        ffi::BNNSFilterApply(self.ptr, input, output)
72    }
73}