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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Recursive reference.
//!
//!This crate provides a way to traverse recursive structures easily and safely.
//!Rust's lifetime rules will usually force you to either only walk forward through the structure,
//!or use recursion, calling your method recursively every time you go down a node,
//!and returning every time you want to go back up, which leads to terrible code.
//!
//!Instead, you can use the [`RecRef`] type, to safely and dynamically walk up
//!and down your recursive structure.
//!
//!# Examples
//!
//! Say we have a recursive linked list structure
//! ----------------------------------------------
//!```rust
//!enum List<T> {
//! Root(Box<Node<T>>),
//! Empty,
//!}
//!struct Node<T> {
//! value: T,
//! next: List<T>,
//!}
//!```
//!
//!We can use a [`RecRef`] directly
//!----------------------------------------------
//!```rust
//!use recursive_reference::*;
//!
//! # enum List<T> {
//! # Root(Box<Node<T>>),
//! # Empty,
//! # }
//! # struct Node<T> {
//! # value: T,
//! # next: List<T>,
//! # }
//!
//!fn main() -> Result<(), ()> {
//! // crate a list to test
//! let node1 = Node {
//! value: 5,
//! next: List::Empty,
//! };
//! let mut node2 = Node {
//! value: 2,
//! next: List::Root(Box::new(node1)),
//! };
//!
//! // create a `RecRef`
//! let mut rec_ref = RecRef::new(&mut node2);
//! // rec_ref is a smart pointer to the current node
//! assert_eq!(rec_ref.value, 2);
//!
//! // move forward through the list
//! RecRef::extend_result(&mut rec_ref, |node| match &mut node.next {
//! List::Root(next_node) => Ok(next_node),
//! List::Empty => Err(()),
//! })?;
//! assert_eq!(rec_ref.value, 5); // now we're at the second node
//!
//! // pop the `RecRef`, moving it back to the head
//! RecRef::pop(&mut rec_ref).ok_or(())?;
//! assert_eq!(rec_ref.value, 2);
//! Ok(())
//!}
//!```
//!
//!We can also wrap a [`RecRef`] in a walker struct
//!----------------------------------------------
//!Note: this time we are using a `RecRef<List<T>>` and not a `RecRef<Node<T>>`, to allow pointing
//!at the empty end of the list.
//!```rust
//!use recursive_reference::*;
//! # enum List<T> {
//! # Root(Box<Node<T>>),
//! # Empty,
//! # }
//! # struct Node<T> {
//! # value: T,
//! # next: List<T>,
//! # }
//!struct Walker<'a, T> {
//! rec_ref: RecRef<'a, Node<T>>,
//!}
//!impl<'a, T> Walker<'a, T> {
//! /// Crates a new Walker
//! pub fn new(node: &'a mut Node<T>) -> Self {
//! Walker {
//! rec_ref: RecRef::new(node),
//! }
//! }
//!
//! /// Returns `None` when at the tail end of the list.
//! /// Moves to the next node.
//! pub fn next(&mut self) -> Option<()> {
//! RecRef::extend_result(&mut self.rec_ref, |current| match &mut current.next {
//! List::Empty => Err(()),
//! List::Root(node) => Ok(node),
//! })
//! .ok()
//! }
//!
//! /// Returns `None` when at the head of the list.
//! /// Goes back to the previous node.
//! pub fn prev(&mut self) -> Option<()> {
//! RecRef::pop(&mut self.rec_ref)?;
//! Some(())
//! }
//!
//! /// Returns `None` when at the tail end of the list.
//! /// Returns `Some(reference)` where `reference` is a mutqable reference to the current value.
//! pub fn value_mut(&mut self) -> &mut T {
//! &mut self.rec_ref.value
//! }
//!}
//!
//!fn main() -> Result<(), ()> {
//! // crate a list to test
//! let node1 = Node {
//! value: 5,
//! next: List::Empty,
//! };
//! let mut node2 = Node {
//! value: 2,
//! next: List::Root(Box::new(node1)),
//! };
//!
//! // create a walker for the list
//! let mut walker = Walker::new(&mut node2);
//! // walker has mutable access to the node value
//! assert_eq!(*walker.value_mut(), 2);
//! // move to the next node
//! walker.next().ok_or(())?;
//! assert_eq!(*walker.value_mut(), 5);
//! assert_eq!(walker.next(), None); // currently at the end of the list
//! // move back
//! walker.prev().ok_or(())?;
//! assert_eq!(*walker.value_mut(), 2);
//! Ok(())
//!}
//!```
//! With a [`RecRef`] you can
//! ----------------------------------------------
//! * Use the current reference (i.e, the top reference).
//! the [`RecRef`] is a smart pointer to it.
//! * Freeze the current reference
//! and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions.
//! for example, push to the stack a reference to the child of the current node.
//! * Pop the stack to get back to the previous reference, unfreezing it.
//!
//! # Safety
//! The [`RecRef`] type is implemented using unsafe rust, but provides a safe interface.
//! The [`RecRef`] methods' types guarantee that the references will always have a legal lifetime
//! and will respect rust's borrow rules, even if that lifetime is not known in advance.
//!
//! The [`RecRef`] obeys rust's borrowing rules, by simulating freezing. Whenever
//! you extend a [`RecRef`] with a reference `child_ref` that is derived from the current
//! reference `parent_ref`, the [`RecRef`] freezes `parent_ref`, and no longer allows
//! `parent_ref` to be used.
//! When `child_ref` will be popped from the [`RecRef`],
//! `parent_ref` will be allowed to be used again.
//!
//! This is essentially the same as what would have happened if you wrote your functions recursively,
//! but it's decoupled from the actual call stack.
//!
//! Another important point to consider is the safety of
//! the actual call to [`extend`][RecRef::extend]: see its documentation.
extern crate alloc;
use *;
use PhantomData;
use ;
use NonNull;
use ResultVoidExt;
/// A Recursive reference.
/// This struct is used to allow recursively reborrowing mutable references in a dynamic
/// but safe way.
///
/// `RecRef<'a, T>` represents a reference to a value of type `T`, with lifetime `'a`,
/// which can move recursively into and out of its subfields of the same type `T`.
///
/// With a [`RecRef`] you can
/// ----------------------------------------------
/// * Use the current reference (i.e, the top reference).
/// the [`RecRef`] is a smart pointer to it.
/// * Freeze the current reference
/// and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions.
/// for example, push to the stack a reference to the child of the current node.
/// * Pop the stack to get back to the previous reference, unfreezing it.
///
/// The methods' types guarantee that the references will always have a legal lifetime
/// and will respect rust's borrow rules, even if that lifetime is not known in advance.
///
/// Internally, the [`RecRef`] stores a [`Vec`] of pointers, that it extends and pops from.
/// [`RecRef<T>`] represents a reference to a value of type `T`,
/// which can move recursively into and out of its subfields of the same type `T`.
/// Therefore, it implements `Deref` and `DerefMut` with `Item=T`.
/// [`RecRef<T>`] represents a reference to a value of type `T`,
/// which can move recursively into and out of its subfields of the same type `T`.
/// Therefore, it implements `Deref` and `DerefMut` with `Item=T`.
/// # Safety:
/// Behaviorally, A [`RecRef`] is the same as `&'a mut T`, and
/// should be [`Send`] for the same reason. Additionally, it contains a [`Vec`].
/// The [`Send`] instance for [`Vec`] contains the bound `A: Send` for the allocator type `A`,
/// so we should require that as well. However, we don't have direct access to the
/// default allocator type. So instead we require `Vec<&'a mut T>: Send`.
unsafe
/// # Safety:
/// Behaviorally, A [`RecRef`] is the same as `&'a mut T`, and
/// should be [`Sync`] for the same reason. Additionally, it contains a [`Vec`].
/// The [`Sync`] instance for [`Vec`] contains the bound `A: Sync` for the allocator type `A`,
/// so we should require that as well. However, we don't have direct access to the
/// default allocator type. So instead we require `Vec<&'a mut T>: Sync`.
unsafe