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
use std::marker::PhantomData;
use crate::Node;
pub trait Lens: 'static + Sized {
type Source: Node;
type Target;
fn view<'a>(&self, data: &'a Self::Source) -> Self::Target;
}
pub trait LensExt: Lens {
fn then<Other>(self, other: Other) -> Then<Self, Other>
where
Other: Lens + Sized,
Self: Sized,
{
Then::new(self, other)
}
fn and<Other>(self, other: Other) -> And<Self, Other>
where
Other: Lens + Sized,
Self: Sized,
{
And::new(self, other)
}
fn index<I: 'static>(self, index: I) -> Then<Self, Index<Self::Target, I>>
where
Self: Sized,
I: Clone,
Self::Target: std::ops::Index<I> + Sized,
<<Self as Lens>::Target as std::ops::Index<I>>::Output: Sized + Clone,
{
Then::new(self, Index::new(index))
}
}
impl<T: Lens> LensExt for T {
}
#[derive(Debug, Copy)]
pub struct Then<A, B> {
a: A,
b: B,
}
impl<A, B> Then<A, B> {
pub fn new(a: A, b: B) -> Self
where
A: Lens,
B: Lens,
{
Self {
a,
b,
}
}
}
impl<A, B> Lens for Then<A, B>
where
A: Lens,
B: Lens<Source = A::Target>,
{
type Source = A::Source;
type Target = B::Target;
fn view<'a>(&self, data: &'a Self::Source) -> Self::Target {
self.b.view(&self.a.view(data))
}
}
impl<T: Clone, U: Clone> Clone for Then<T, U> {
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
}
}
}
pub struct And<A,B> {
a: A,
b: B,
}
impl<A,B> And<A,B> {
pub fn new(a: A, b: B) -> Self
where
A: Lens,
B: Lens,
{
Self {
a,
b,
}
}
}
impl<A,B> Lens for And<A,B>
where
A: Lens,
B: Lens<Source = A::Source>,
{
type Source = A::Source;
type Target = (A::Target, B::Target);
fn view<'a>(&self, data: &'a Self::Source) -> Self::Target {
(self.a.view(data), self.b.view(data))
}
}
pub struct Index<T,I> {
index: I,
output: PhantomData<T>,
}
impl<T,I> Index<T,I> {
pub fn new(index: I) -> Self {
Self {
index,
output: PhantomData::default(),
}
}
}
impl<T,I> Lens for Index<T,I>
where
T: 'static + std::ops::Index<I> + Sized,
I: 'static + Clone,
<T as std::ops::Index<I>>::Output: Sized + Clone,
{
type Source = T;
type Target = <T as std::ops::Index<I>>::Output;
fn view<'a>(&self, data: &'a Self::Source) -> Self::Target {
data[self.index.clone()].clone()
}
}