|
| 1 | +use core::ffi::CStr; |
| 2 | +use std::sync::OnceLock; |
| 3 | + |
| 4 | +use crate::ffi::NSInteger; |
| 5 | +use crate::rc::{autoreleasepool, Retained}; |
| 6 | +use crate::runtime::{AnyClass, NSObject}; |
| 7 | +use crate::{msg_send_id, ClassType}; |
| 8 | + |
| 9 | +// Marked `#[cold]` to tell the optimizer that errors are comparatively rare. |
| 10 | +// |
| 11 | +// And intentionally not `#[inline]`, we'll let the optimizer figure out if it |
| 12 | +// wants to do that or not. |
| 13 | +#[cold] |
| 14 | +pub(crate) unsafe fn encountered_error<E: ClassType>(err: *mut E) -> Retained<E> { |
| 15 | + // SAFETY: Caller ensures that the pointer is valid. |
| 16 | + unsafe { Retained::retain(err) }.unwrap_or_else(|| { |
| 17 | + let err = null_error(); |
| 18 | + assert!(E::IS_NSERROR_COMPATIBLE); |
| 19 | + // SAFETY: Just checked (via `const` assertion) that the `E` type is |
| 20 | + // either `NSError` or `NSObject`, and hence it is valid to cast the |
| 21 | + // `NSObject` that we have here to that. |
| 22 | + unsafe { Retained::cast_unchecked(err) } |
| 23 | + }) |
| 24 | +} |
| 25 | + |
| 26 | +/// Poor mans string equality in `const`. Implements `a == b`. |
| 27 | +const fn is_eq(a: &str, b: &str) -> bool { |
| 28 | + let a = a.as_bytes(); |
| 29 | + let b = b.as_bytes(); |
| 30 | + |
| 31 | + if a.len() != b.len() { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + let mut i = 0; |
| 36 | + while i < a.len() { |
| 37 | + if a[i] != b[i] { |
| 38 | + return false; |
| 39 | + } |
| 40 | + i += 1; |
| 41 | + } |
| 42 | + |
| 43 | + true |
| 44 | +} |
| 45 | + |
| 46 | +// TODO: Use inline `const` once in MSRV (or add proper trait bounds). |
| 47 | +trait IsNSError { |
| 48 | + const IS_NSERROR_COMPATIBLE: bool; |
| 49 | +} |
| 50 | + |
| 51 | +impl<T: ClassType> IsNSError for T { |
| 52 | + const IS_NSERROR_COMPATIBLE: bool = { |
| 53 | + if is_eq(T::NAME, "NSError") || is_eq(T::NAME, "NSObject") { |
| 54 | + true |
| 55 | + } else { |
| 56 | + // The post monomorphization error here is not nice, but it's |
| 57 | + // better than UB because the user used a type that cannot be |
| 58 | + // converted to NSError. |
| 59 | + // |
| 60 | + // TODO: Add a trait bound or similar instead. |
| 61 | + panic!("error parameter must be either `NSError` or `NSObject`") |
| 62 | + } |
| 63 | + }; |
| 64 | +} |
| 65 | + |
| 66 | +#[cold] // Mark the NULL error branch as cold |
| 67 | +fn null_error() -> Retained<NSObject> { |
| 68 | + static CACHED_NULL_ERROR: OnceLock<NSErrorWrapper> = OnceLock::new(); |
| 69 | + |
| 70 | + // We use a OnceLock here, since performance doesn't really matter, and |
| 71 | + // using an AtomicPtr would leak under (very) high initialization |
| 72 | + // contention. |
| 73 | + CACHED_NULL_ERROR.get_or_init(create_null_error).0.clone() |
| 74 | +} |
| 75 | + |
| 76 | +struct NSErrorWrapper(Retained<NSObject>); |
| 77 | + |
| 78 | +// SAFETY: NSError is immutable and thread safe. |
| 79 | +unsafe impl Send for NSErrorWrapper {} |
| 80 | +unsafe impl Sync for NSErrorWrapper {} |
| 81 | + |
| 82 | +#[cold] // Mark the error creation branch as cold |
| 83 | +fn create_null_error() -> NSErrorWrapper { |
| 84 | + // Wrap creation in an autoreleasepool, since we don't know anything about |
| 85 | + // the outside world, and we don't want to appear to leak. |
| 86 | + autoreleasepool(|_| { |
| 87 | + // TODO: Replace with c string literals once in MSRV. |
| 88 | + |
| 89 | + // SAFETY: The string is NUL terminated. |
| 90 | + let cls = unsafe { CStr::from_bytes_with_nul_unchecked(b"NSString\0") }; |
| 91 | + // Intentional dynamic lookup, we don't know if Foundation is linked. |
| 92 | + let cls = AnyClass::get(cls).unwrap_or_else(foundation_not_linked); |
| 93 | + |
| 94 | + // SAFETY: The string is NUL terminated. |
| 95 | + let domain = unsafe { CStr::from_bytes_with_nul_unchecked(b"__objc2.missingError\0") }; |
| 96 | + // SAFETY: The signate is correct, and the string is UTF-8 encoded and |
| 97 | + // NUL terminated. |
| 98 | + let domain: Retained<NSObject> = |
| 99 | + unsafe { msg_send_id![cls, stringWithUTF8String: domain.as_ptr()] }; |
| 100 | + |
| 101 | + // SAFETY: The string is valid. |
| 102 | + let cls = unsafe { CStr::from_bytes_with_nul_unchecked(b"NSError\0") }; |
| 103 | + // Intentional dynamic lookup, we don't know if Foundation is linked. |
| 104 | + let cls = AnyClass::get(cls).unwrap_or_else(foundation_not_linked); |
| 105 | + |
| 106 | + let domain: &NSObject = &domain; |
| 107 | + let code: NSInteger = 0; |
| 108 | + let user_info: Option<&NSObject> = None; |
| 109 | + // SAFETY: The signate is correct. |
| 110 | + let err: Retained<NSObject> = |
| 111 | + unsafe { msg_send_id![cls, errorWithDomain: domain, code: code, userInfo: user_info] }; |
| 112 | + NSErrorWrapper(err) |
| 113 | + }) |
| 114 | +} |
| 115 | + |
| 116 | +fn foundation_not_linked() -> &'static AnyClass { |
| 117 | + panic!("Foundation must be linked to get a proper error message on NULL errors") |
| 118 | +} |
| 119 | + |
| 120 | +#[cfg(test)] |
| 121 | +mod tests { |
| 122 | + use super::*; |
| 123 | + |
| 124 | + #[test] |
| 125 | + fn test_is_eq() { |
| 126 | + assert!(is_eq("NSError", "NSError")); |
| 127 | + assert!(!is_eq("nserror", "NSError")); |
| 128 | + assert!(!is_eq("CFError", "NSError")); |
| 129 | + assert!(!is_eq("NSErr", "NSError")); |
| 130 | + assert!(!is_eq("NSErrorrrr", "NSError")); |
| 131 | + } |
| 132 | + |
| 133 | + #[test] |
| 134 | + fn test_create() { |
| 135 | + let _ = create_null_error().0; |
| 136 | + } |
| 137 | +} |
0 commit comments