Skip to main content

mtl_gpu/io/
scratch_buffer_allocator.rs

1//! IO scratch buffer allocator for Metal.
2
3use std::ffi::c_void;
4use std::ptr::NonNull;
5
6use mtl_foundation::{Referencing, UInteger};
7use mtl_sys::{msg_send_0, msg_send_1, sel};
8
9use super::IOScratchBuffer;
10
11/// Allocator for IO scratch buffers.
12///
13/// C++ equivalent: `MTL::IOScratchBufferAllocator`
14#[repr(transparent)]
15pub struct IOScratchBufferAllocator(pub(crate) NonNull<c_void>);
16
17impl IOScratchBufferAllocator {
18    /// Create from a raw pointer.
19    ///
20    /// # Safety
21    ///
22    /// The pointer must be a valid Metal IO scratch buffer allocator.
23    #[inline]
24    pub unsafe fn from_raw(ptr: *mut c_void) -> Option<Self> {
25        NonNull::new(ptr).map(Self)
26    }
27
28    /// Get the raw pointer.
29    #[inline]
30    pub fn as_raw(&self) -> *mut c_void {
31        self.0.as_ptr()
32    }
33
34    /// Create a new scratch buffer with the specified minimum size.
35    ///
36    /// C++ equivalent: `IOScratchBuffer* newScratchBuffer(NS::UInteger)`
37    pub fn new_scratch_buffer(&self, minimum_size: UInteger) -> Option<IOScratchBuffer> {
38        unsafe {
39            let ptr: *mut c_void = msg_send_1(
40                self.as_ptr(),
41                sel!(newScratchBufferWithMinimumSize:),
42                minimum_size,
43            );
44            IOScratchBuffer::from_raw(ptr)
45        }
46    }
47}
48
49impl Clone for IOScratchBufferAllocator {
50    fn clone(&self) -> Self {
51        unsafe {
52            msg_send_0::<*mut c_void>(self.as_ptr(), sel!(retain));
53        }
54        Self(self.0)
55    }
56}
57
58impl Drop for IOScratchBufferAllocator {
59    fn drop(&mut self) {
60        unsafe {
61            msg_send_0::<()>(self.as_ptr(), sel!(release));
62        }
63    }
64}
65
66impl Referencing for IOScratchBufferAllocator {
67    #[inline]
68    fn as_ptr(&self) -> *const c_void {
69        self.0.as_ptr()
70    }
71}
72
73unsafe impl Send for IOScratchBufferAllocator {}
74unsafe impl Sync for IOScratchBufferAllocator {}