@@ -132,22 +132,22 @@ pub fn cursor_mut(&mut self) -> CursorMut<T>;
132
132
These would provide the following interface:
133
133
134
134
``` rust
135
- impl <T > Cursor <T > {
135
+ impl <' list , T > Cursor <' list , T > {
136
136
/// Move to the subsequent element of the list if it exists or the empty
137
137
/// element
138
138
pub fn move_next (& mut self );
139
139
/// Move to the previous element of the list
140
140
pub fn move_prev (& mut self );
141
141
142
142
/// Get the current element
143
- pub fn current (& self ) -> Option <& T >;
143
+ pub fn current (& self ) -> Option <& ' list T >;
144
144
/// Get the following element
145
- pub fn peek (& self ) -> Option <& T >;
145
+ pub fn peek (& self ) -> Option <& ' list T >;
146
146
/// Get the previous element
147
- pub fn peek_before (& self ) -> Option <& T >;
147
+ pub fn peek_before (& self ) -> Option <& ' list T >;
148
148
}
149
149
150
- impl <T > CursorMut <T > {
150
+ impl <' list T > CursorMut <' list , T > {
151
151
/// Move to the subsequent element of the list if it exists or the empty
152
152
/// element
153
153
pub fn move_next (& mut self );
@@ -162,7 +162,7 @@ impl<T> CursorMut<T> {
162
162
pub fn peek_before (& mut self ) -> Option <& mut T >;
163
163
164
164
/// Get an immutable cursor at the current element
165
- pub fn as_cursor ( & self ) -> Cursor <T >;
165
+ pub fn as_cursor <' cm >( & ' cm self ) -> Cursor <' cm , T >;
166
166
167
167
// Now the list editing operations
168
168
@@ -190,6 +190,30 @@ impl<T> CursorMut<T> {
190
190
pub fn split_before (self ) -> LinkedList <T >;
191
191
}
192
192
```
193
+ One should closely consider the lifetimes in this interface. Both ` Cursor ` and
194
+ ` CursorMut ` operate on data in their ` LinkedList ` . This is why, they both hold
195
+ the annotation of ` 'list ` .
196
+
197
+ The lifetime elision for their constructors is correct as
198
+ ```
199
+ pub fn cursor(&self) -> Cursor<T>
200
+ ```
201
+ becomes
202
+ ```
203
+ pub fn cursor<'list>(&'list self) -> Cursor<'list, T>
204
+ ```
205
+ which is what we would expect. (the same goes for ` CursorMut ` ).
206
+
207
+ Since ` Cursor ` cannot mutate its list, ` current ` , ` peek ` and ` peek_before ` all
208
+ live as long as ` 'list ` . However, in ` CursorMut ` we must be careful to make
209
+ these methods borrow. Otherwise, one could produce multiple mutable references
210
+ to the same element.
211
+
212
+ The only other lifetime annotation is with ` as_cursor ` . In this case, the
213
+ returned ` Cursor ` must borrow its generating ` CursorMut ` . Otherwise, it would be
214
+ possible to achieve a mutable and immutable reference to the same element at
215
+ once.
216
+
193
217
One question that arises from this interface is what happens if ` move_next ` is
194
218
called when a cursor is on the last element of the list, or is empty (or
195
219
` move_prev ` and the beginning). A simple way to solve this is to make cursors
0 commit comments