1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use alloc::string::ToString;
use core::cmp::Ordering;
use core::ffi::c_void;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::NonNull;
use core::{fmt, str};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use objc2::msg_send;
use objc2::rc::{DefaultId, Id, Shared};
use objc2::Encode;
use super::{NSCopying, NSObject};
object! {
unsafe pub struct NSValue<T>: NSObject {
value: PhantomData<T>,
}
}
unsafe impl<T: Sync> Sync for NSValue<T> {}
unsafe impl<T: Send> Send for NSValue<T> {}
impl<T: 'static + Copy + Encode> NSValue<T> {
pub fn get(&self) -> T {
if let Some(encoding) = self.encoding() {
assert!(T::ENCODING.equivalent_to_str(encoding), "Wrong encoding");
unsafe { self.get_unchecked() }
} else {
panic!("Missing NSValue encoding");
}
}
pub unsafe fn get_unchecked(&self) -> T {
let mut value = MaybeUninit::<T>::uninit();
let ptr: *mut c_void = value.as_mut_ptr().cast();
let _: () = unsafe { msg_send![self, getValue: ptr] };
unsafe { value.assume_init() }
}
pub fn encoding(&self) -> Option<&str> {
let result: Option<NonNull<c_char>> = unsafe { msg_send![self, objCType] };
result.map(|s| unsafe { CStr::from_ptr(s.as_ptr()) }.to_str().unwrap())
}
pub fn new(value: T) -> Id<Self, Shared> {
let cls = Self::class();
let bytes: *const T = &value;
let bytes: *const c_void = bytes.cast();
let encoding = CString::new(T::ENCODING.to_string()).unwrap();
unsafe {
let obj: *mut Self = msg_send![cls, alloc];
let obj: *mut Self = msg_send![
obj,
initWithBytes: bytes,
objCType: encoding.as_ptr(),
];
Id::new(obj).unwrap()
}
}
}
unsafe impl<T: 'static> NSCopying for NSValue<T> {
type Ownership = Shared;
type Output = NSValue<T>;
}
impl<T: 'static> alloc::borrow::ToOwned for NSValue<T> {
type Owned = Id<NSValue<T>, Shared>;
fn to_owned(&self) -> Self::Owned {
self.copy()
}
}
impl<T: 'static + Copy + Encode + Ord> Ord for NSValue<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.get().cmp(&other.get())
}
}
impl<T: 'static + Copy + Encode + PartialOrd> PartialOrd for NSValue<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.get().partial_cmp(&other.get())
}
}
impl<T: 'static + Copy + Encode + Default> DefaultId for NSValue<T> {
type Ownership = Shared;
#[inline]
fn default_id() -> Id<Self, Self::Ownership> {
Self::new(Default::default())
}
}
impl<T: 'static + Copy + Encode + fmt::Display> fmt::Display for NSValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.get().fmt(f)
}
}
#[cfg(test)]
mod tests {
use alloc::format;
use crate::{NSRange, NSValue};
use objc2::rc::{Id, Shared};
use objc2::Encode;
#[test]
fn test_value() {
let val = NSValue::new(13u32);
assert_eq!(val.get(), 13);
assert!(u32::ENCODING.equivalent_to_str(val.encoding().unwrap()));
}
#[test]
fn test_equality() {
let val1 = NSValue::new(123u32);
let val2 = NSValue::new(123u32);
assert_eq!(val1, val1);
assert_eq!(val1, val2);
let val3 = NSValue::new(456u32);
assert_ne!(val1, val3);
}
#[test]
fn test_equality_across_types() {
let val1 = NSValue::new(123);
let val2: Id<NSValue<u32>, Shared> = NSValue::new(123);
let val2: Id<NSValue<u8>, Shared> = unsafe { core::mem::transmute(val2) };
assert_ne!(val1, val2);
}
#[test]
#[ignore = "Output is different depending on OS version and runtime"]
fn test_debug() {
fn assert_debug(val: impl core::fmt::Debug, expected: &str) {
assert_eq!(format!("{:?}", val), format!("{:?}", expected));
}
let val = NSValue::new(0xabu8);
let expected = "<ab>";
assert_debug(val, expected);
let val = NSValue::new(0x12i8);
let expected = "<12>";
assert_debug(val, expected);
let val = NSValue::new(0xdeadbeefu32);
let expected = "<efbeadde>";
assert_debug(val, expected);
let val = NSValue::new(1.0f32);
let expected = &format!(
"<{:08x}>",
u32::from_le_bytes(1.0f32.to_le_bytes()).reverse_bits()
);
assert_debug(val, expected);
}
#[test]
fn test_value_nsrange() {
let val = NSValue::new(NSRange::from(1..2));
assert!(NSRange::ENCODING.equivalent_to_str(val.encoding().unwrap()));
let range: NSRange = unsafe { objc2::msg_send![&val, rangeValue] };
assert_eq!(range, NSRange::from(1..2));
#[cfg(not(feature = "gnustep-1-7"))]
assert_eq!(val.get(), NSRange::from(1..2));
}
}