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
use std::ops::Deref;
use std::ptr::NonNull;
use std::rc::Rc;
use std::cell::UnsafeCell;
use std::fmt::Formatter;
pub struct RcView<T: ?Sized, U: ?Sized> {
#[allow(dead_code)]
whole: Rc<T>,
focus: NonNull<U>,
}
impl<T: ?Sized> From<Rc<T>> for RcView<T, T> {
fn from(whole: Rc<T>) -> Self {
RcView {
focus: NonNull::from(whole.as_ref()),
whole,
}
}
}
impl<T: ?Sized, U: std::fmt::Debug + ?Sized> std::fmt::Debug for RcView<T, U> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.deref().fmt(f) }
}
impl<T: ?Sized, U: std::fmt::Display + ?Sized> std::fmt::Display for RcView<T, U> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.deref().fmt(f) }
}
impl<T: ?Sized, U: ?Sized> RcView<T, U> {
pub fn new(whole: Rc<T>, to_focus: impl FnOnce(&T) -> &U) -> Self {
let focus = NonNull::from(to_focus(&whole));
RcView { whole, focus }
}
pub unsafe fn wrap(whole: Rc<T>, focus: &U) -> Self {
RcView {
whole,
focus: NonNull::from(focus),
}
}
pub fn map<V: ?Sized>(self, f: impl FnOnce(&U) -> &V) -> RcView<T, V> {
RcView {
focus: NonNull::from(f(unsafe { self.focus.as_ref() })),
whole: self.whole,
}
}
pub unsafe fn derive<V: ?Sized>(&self, focus: &V) -> RcView<T, V> {
RcView::<T, V>::wrap(self.whole.clone(), focus)
}
pub unsafe fn derive_take<V: ?Sized>(self, focus: &V) -> RcView<T, V> {
RcView::<T, V>::wrap(self.whole, focus)
}
}
impl<T: ?Sized, U: ?Sized> Deref for RcView<T, U> {
type Target = U;
fn deref(&self) -> &Self::Target {
unsafe { self.focus.as_ref() }
}
}
impl<T: ?Sized, U> From<RcView<UnsafeCell<T>, Option<U>>> for Option<U> {
fn from(mut this: RcView<UnsafeCell<T>, Option<U>>) -> Self {
unsafe { this.focus.as_mut() }.take()
}
}