apple_vision/classify/
mod.rs1use core::ffi::c_char;
4use core::ptr;
5use std::ffi::CString;
6use std::path::Path;
7
8use crate::error::{from_swift, VisionError};
9use crate::ffi;
10
11#[derive(Debug, Clone, PartialEq)]
14#[allow(clippy::derive_partial_eq_without_eq)]
15pub struct Classification {
16 pub identifier: String,
17 pub confidence: f32,
18}
19
20pub fn classify_image_in_path(
26 path: impl AsRef<Path>,
27) -> Result<Vec<Classification>, VisionError> {
28 let path_str = path
29 .as_ref()
30 .to_str()
31 .ok_or_else(|| VisionError::InvalidArgument("non-UTF-8 path".into()))?;
32 let path_c = CString::new(path_str)
33 .map_err(|e| VisionError::InvalidArgument(format!("path NUL byte: {e}")))?;
34
35 let mut out_array: *mut core::ffi::c_void = ptr::null_mut();
36 let mut out_count: usize = 0;
37 let mut err_msg: *mut c_char = ptr::null_mut();
38
39 let status = unsafe {
40 ffi::vn_classify_image_in_path(
41 path_c.as_ptr(),
42 &mut out_array,
43 &mut out_count,
44 &mut err_msg,
45 )
46 };
47 if status != ffi::status::OK {
48 return Err(unsafe { from_swift(status, err_msg) });
49 }
50 if out_array.is_null() || out_count == 0 {
51 return Ok(Vec::new());
52 }
53 let typed = out_array.cast::<ffi::ClassificationRaw>();
54 let mut v = Vec::with_capacity(out_count);
55 for i in 0..out_count {
56 let raw = unsafe { &*typed.add(i) };
57 let id = if raw.identifier.is_null() {
58 String::new()
59 } else {
60 unsafe { core::ffi::CStr::from_ptr(raw.identifier) }
61 .to_string_lossy()
62 .into_owned()
63 };
64 v.push(Classification {
65 identifier: id,
66 confidence: raw.confidence,
67 });
68 }
69 unsafe { ffi::vn_classifications_free(out_array, out_count) };
70 Ok(v)
71}