Skip to main content

apple_cf/cv/
metal_texture_cache.rs

1//! `CVMetalTextureCache` wrapper.
2//!
3#![allow(clippy::missing_panics_doc)]
4
5//! ```rust,no_run
6//! use apple_cf::cv::CVMetalTextureCache;
7//!
8//! if let Some(cache) = CVMetalTextureCache::system_default() {
9//!     cache.flush();
10//! }
11//! ```
12
13use crate::ffi;
14use std::ffi::c_void;
15use std::fmt;
16
17#[link(name = "CoreVideo", kind = "framework")]
18extern "C" {
19    fn CVMetalTextureCacheGetTypeID() -> usize;
20}
21
22/// Owned wrapper around `CVMetalTextureCacheRef`.
23pub struct CVMetalTextureCache(*mut c_void);
24
25impl CVMetalTextureCache {
26    /// Create a texture cache using the system-default Metal device.
27    #[must_use]
28    pub fn system_default() -> Option<Self> {
29        let ptr = unsafe { ffi::cv_metal_texture_cache_create_system_default() };
30        Self::from_raw(ptr)
31    }
32
33    /// Wraps a +1 retained `CVMetalTextureCacheRef` and returns `None` for null.
34    #[must_use]
35    pub fn from_raw(ptr: *mut c_void) -> Option<Self> {
36        if ptr.is_null() {
37            None
38        } else {
39            Some(Self(ptr))
40        }
41    }
42
43    /// Borrow the raw cache pointer.
44    #[must_use]
45    pub const fn as_ptr(&self) -> *mut c_void {
46        self.0
47    }
48
49    /// Core Video type identifier.
50    #[must_use]
51    pub fn type_id() -> usize {
52        unsafe { CVMetalTextureCacheGetTypeID() }
53    }
54
55    /// Flush pending cached textures.
56    pub fn flush(&self) {
57        unsafe { ffi::cv_metal_texture_cache_flush(self.0) };
58    }
59}
60
61impl Clone for CVMetalTextureCache {
62    fn clone(&self) -> Self {
63        let retained = unsafe { ffi::cf_type_retain(self.0) };
64        Self(retained)
65    }
66}
67
68impl Drop for CVMetalTextureCache {
69    fn drop(&mut self) {
70        if !self.0.is_null() {
71            unsafe { ffi::cf_type_release(self.0) };
72        }
73    }
74}
75
76impl PartialEq for CVMetalTextureCache {
77    fn eq(&self, other: &Self) -> bool {
78        self.0 == other.0
79    }
80}
81
82impl Eq for CVMetalTextureCache {}
83
84impl std::hash::Hash for CVMetalTextureCache {
85    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
86        unsafe { ffi::cf_type_hash(self.0) }.hash(state);
87    }
88}
89
90impl fmt::Debug for CVMetalTextureCache {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.debug_struct("CVMetalTextureCache")
93            .field("ptr", &self.0)
94            .field("type_id", &Self::type_id())
95            .finish()
96    }
97}