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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use std::{
cell::{BorrowError, Cell, Ref, RefCell},
cmp::Ordering,
fmt::{self, Display},
hash::{Hash, Hasher},
mem,
ops::Deref,
};
use crate::cast;
#[derive(Debug)]
pub struct ARef<'a, T: ?Sized + 'a> {
value: &'a T,
borrow: Option<&'a Cell<isize>>,
}
impl<T: ?Sized> Drop for ARef<'_, T> {
fn drop(&mut self) {
if self.borrow.is_some() {
let me: ARef<T> = ARef {
value: self.value,
borrow: self.borrow,
};
let them: Ref<T> = unsafe { cast::transmute_unchecked(me) };
mem::drop(them);
}
}
}
impl<T: ?Sized> Deref for ARef<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value
}
}
impl<'a, T: ?Sized + 'a> ARef<'a, T> {
pub fn new_ptr(x: &'a T) -> Self {
ARef {
value: x,
borrow: None,
}
}
pub fn new_ref(x: Ref<'a, T>) -> Self {
let v: ARef<T> = unsafe { cast::transmute_unchecked(x) };
debug_assert!(v.borrow.is_some());
v
}
#[allow(clippy::should_implement_trait)]
pub fn clone(orig: &Self) -> Self {
if orig.borrow.is_none() {
ARef::new_ptr(orig.value)
} else {
let orig: &Ref<T> = unsafe { cast::ptr(orig) };
Self::new_ref(Ref::clone(orig))
}
}
pub fn map<U: ?Sized, F>(orig: ARef<'a, T>, f: F) -> ARef<'a, U>
where
F: FnOnce(&T) -> &U,
{
let res = ARef {
value: f(orig.value),
borrow: orig.borrow,
};
#[allow(clippy::mem_forget)]
mem::forget(orig);
res
}
pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: ARef<'a, T>, f: F) -> (ARef<'a, U>, ARef<'a, V>)
where
F: FnOnce(&T) -> (&U, &V),
{
if orig.borrow.is_none() {
let (a, b) = f(orig.value);
(ARef::new_ptr(a), ARef::new_ptr(b))
} else {
let orig: Ref<T> = unsafe { cast::transmute_unchecked(orig) };
let (a, b) = Ref::map_split(orig, f);
(ARef::new_ref(a), ARef::new_ref(b))
}
}
pub fn filter_map<U: ?Sized, F>(orig: ARef<'a, T>, f: F) -> Result<ARef<'a, U>, Self>
where
F: FnOnce(&T) -> Option<&U>,
{
match f(orig.value) {
Some(value) => {
let res = Ok(ARef {
value,
borrow: orig.borrow,
});
#[allow(clippy::mem_forget)]
mem::forget(orig);
res
}
None => Err(orig),
}
}
}
impl<T: Display + ?Sized> Display for ARef<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ARef::deref(self).fmt(f)
}
}
impl<T: Hash + ?Sized> Hash for ARef<'_, T> {
fn hash<H: Hasher>(&self, state: &mut H) {
ARef::deref(self).hash(state)
}
}
impl<A: PartialEq<B> + ?Sized, B: ?Sized> PartialEq<ARef<'_, B>> for ARef<'_, A> {
fn eq(&self, other: &ARef<'_, B>) -> bool {
ARef::deref(self).eq(ARef::deref(other))
}
}
impl<A: Eq + ?Sized> Eq for ARef<'_, A> {}
impl<A: PartialOrd<B> + ?Sized, B: ?Sized> PartialOrd<ARef<'_, B>> for ARef<'_, A> {
fn partial_cmp(&self, other: &ARef<'_, B>) -> Option<Ordering> {
ARef::deref(self).partial_cmp(ARef::deref(other))
}
}
impl<A: Ord + ?Sized> Ord for ARef<'_, A> {
fn cmp(&self, other: &Self) -> Ordering {
ARef::deref(self).cmp(ARef::deref(other))
}
}
pub trait AsARef<T: ?Sized> {
fn as_aref(&self) -> ARef<T>;
fn try_as_aref(&self) -> Result<ARef<T>, BorrowError>;
fn as_ref_cell(&self) -> Option<&RefCell<T>>;
}
impl<T: ?Sized> AsARef<T> for T {
fn as_aref(&self) -> ARef<T> {
ARef::new_ptr(self)
}
fn try_as_aref(&self) -> Result<ARef<T>, BorrowError> {
Ok(ARef::new_ptr(self))
}
fn as_ref_cell(&self) -> Option<&RefCell<T>> {
None
}
}
impl<T: ?Sized> AsARef<T> for RefCell<T> {
fn as_aref(&self) -> ARef<T> {
ARef::new_ref(self.borrow())
}
fn try_as_aref(&self) -> Result<ARef<T>, BorrowError> {
Ok(ARef::new_ref(self.try_borrow()?))
}
fn as_ref_cell(&self) -> Option<&RefCell<T>> {
Some(self)
}
}
#[cfg(test)]
mod test {
use std::{cell::RefCell, mem};
use super::*;
use crate::cast;
#[test]
fn test_from_ref_docs() {
let c = RefCell::new((5, 'b'));
let b1: ARef<(u32, char)> = ARef::new_ref(c.borrow());
let b2: ARef<u32> = ARef::map(b1, |t| &t.0);
assert_eq!(*b2, 5);
let cell = RefCell::new([1, 2, 3, 4]);
let borrow = ARef::new_ref(cell.borrow());
let (begin, end) = ARef::map_split(borrow, |slice| slice.split_at(2));
assert_eq!(*begin, [1, 2]);
assert_eq!(*end, [3, 4]);
}
#[test]
fn test_borrow_guards() {
let c = RefCell::new(5);
assert!(c.try_borrow_mut().is_ok());
let r1 = ARef::new_ref(c.borrow());
assert!(c.try_borrow_mut().is_err());
let r2 = c.borrow();
assert!(c.try_borrow_mut().is_err());
mem::drop(r1);
assert!(c.try_borrow_mut().is_err());
mem::drop(r2);
assert!(c.try_borrow_mut().is_ok());
}
#[test]
fn test_pointer_basics() {
let c = "test".to_owned();
let p = ARef::new_ptr(&c);
let p2 = ARef::map(p, |x| &x[1..3]);
assert_eq!(&*p2, "es");
}
#[test]
fn test_ref_map_dropping() {
let c = RefCell::new("test".to_owned());
let p = ARef::new_ref(c.borrow());
let p = ARef::map(p, |x| &x[1..3]);
assert_eq!(&*p, "es");
mem::drop(p);
assert!(c.try_borrow_mut().is_ok());
}
#[test]
fn test_ref_filter_map_dropping() {
let c = RefCell::new("test".to_owned());
let p = ARef::new_ref(c.borrow());
let p = ARef::filter_map(p, |x| Some(&x[1..3])).unwrap();
assert_eq!(&*p, "es");
mem::drop(p);
assert!(c.try_borrow_mut().is_ok());
}
#[test]
fn test_ref_as_expected() {
let orig = RefCell::new("test".to_owned());
let p = orig.borrow();
let p2 = Ref::clone(&p);
let (pointer, cell): (usize, usize) = unsafe { mem::transmute(p) };
assert_eq!(pointer, cast::ptr_to_usize(Ref::deref(&p2)));
assert_ne!(cell, 0);
let _ignore: Ref<String> = unsafe { mem::transmute((pointer, cell)) };
}
#[test]
fn test_as_aref() {
fn get_str(x: &impl AsARef<String>) -> ARef<str> {
ARef::map(x.as_aref(), |x| x.as_str())
}
let a = RefCell::new("hello".to_owned());
let b = "world".to_owned();
assert_eq!(&*get_str(&a), "hello");
assert_eq!(&*get_str(&b), "world");
}
}