fruity__bbqsrc/objc/sel/
mod.rs

1use super::BOOL;
2use std::{
3    ffi::CStr,
4    fmt,
5    os::raw::{c_char, c_void},
6    ptr::NonNull,
7};
8
9#[macro_use]
10mod macros;
11
12pub(crate) mod atomic;
13pub(crate) mod cached;
14
15/// A method selector.
16///
17/// Selectors can be safely created using the
18/// [`selector!`](../macro.selector.html) macro.
19///
20/// See [documentation](https://developer.apple.com/documentation/objectivec/sel).
21#[repr(transparent)]
22#[derive(Copy, Clone)]
23pub struct Sel(NonNull<c_void>);
24
25unsafe impl Send for Sel {}
26unsafe impl Sync for Sel {}
27
28impl PartialEq for Sel {
29    #[inline]
30    #[doc(alias = "sel_isEqual")]
31    fn eq(&self, other: &Self) -> bool {
32        extern "C" {
33            fn sel_isEqual(lhs: Sel, rhs: Sel) -> BOOL;
34        }
35        unsafe { sel_isEqual(*self, *other) }.into()
36    }
37}
38
39impl Eq for Sel {}
40
41impl fmt::Debug for Sel {
42    #[inline]
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        self.name().fmt(f)
45    }
46}
47
48impl Sel {
49    /// Registers a method name with the Objective-C runtime and returns the
50    /// selector.
51    ///
52    /// # Safety
53    ///
54    /// The name must be a non-null UTF-8 C string.
55    #[inline]
56    #[doc(alias = "sel_registerName")]
57    pub unsafe fn register(name: *const c_char) -> Self {
58        sel_registerName(name)
59    }
60
61    /// Creates a selector from a raw pointer.
62    ///
63    /// # Safety
64    ///
65    /// The pointer must point to valid selector data.
66    #[inline]
67    pub const unsafe fn from_ptr(ptr: *const c_void) -> Self {
68        Self(NonNull::new_unchecked(ptr as _))
69    }
70
71    /// Creates a selector from a raw non-null pointer.
72    ///
73    /// # Safety
74    ///
75    /// The pointer must point to valid selector data.
76    #[inline]
77    pub const unsafe fn from_non_null_ptr(ptr: NonNull<c_void>) -> Self {
78        Self(ptr)
79    }
80
81    /// Returns a raw nullable pointer to this selector's data.
82    #[inline]
83    pub const fn as_ptr(&self) -> *const c_void {
84        self.0.as_ptr()
85    }
86
87    /// Returns a raw non-null pointer to this selector's data.
88    #[inline]
89    pub const fn as_non_null_ptr(&self) -> NonNull<c_void> {
90        self.0
91    }
92
93    /// Returns the name of the method this selector refers to.
94    #[inline]
95    pub fn name(self) -> &'static CStr {
96        unsafe { CStr::from_ptr(sel_getName(self)) }
97    }
98}
99
100extern "C" {
101    fn sel_registerName(name: *const c_char) -> Sel;
102    fn sel_getName(sel: Sel) -> *const c_char;
103}