Skip to content

Commit

Permalink
Add lifetimes to RFC
Browse files Browse the repository at this point in the history
  • Loading branch information
4e554c4c committed Oct 25, 2018
1 parent d317332 commit 524f9f8
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions text/0000-linked-list-cursors.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ pub fn cursor_mut(&mut self) -> CursorMut<T>;
These would provide the following interface:

``` rust
impl<T> Cursor<T> {
impl<'list, T> Cursor<'list, T> {
/// Move to the subsequent element of the list if it exists or the empty
/// element
pub fn move_next(&mut self);
Expand All @@ -147,7 +147,7 @@ impl<T> Cursor<T> {
pub fn peek_before(&self) -> Option<&T>;
}

impl<T> CursorMut<T> {
impl<'list T> CursorMut<'list, T> {
/// Move to the subsequent element of the list if it exists or the empty
/// element
pub fn move_next(&mut self);
Expand All @@ -162,7 +162,7 @@ impl<T> CursorMut<T> {
pub fn peek_before(&mut self) -> Option<&mut T>;

/// Get an immutable cursor at the current element
pub fn as_cursor(&self) -> Cursor<T>;
pub fn as_cursor<'cm>(&'cm self) -> Cursor<'cm, T>;

// Now the list editing operations

Expand Down Expand Up @@ -190,6 +190,28 @@ impl<T> CursorMut<T> {
pub fn split_before(self) -> LinkedList<T>;
}
```
One should closely consider the lifetimes in this interface. Both `Cursor` and
`CursorMut` operate on data in their `LinkedList`. This is why, they both hold
the annotation of `'list`.

The lifetime elision for their constructors is correct as
```
pub fn cursor(&self) -> Cursor<T>
```
becomes
```
pub fn cursor<'list>(&'list self) -> Cursor<'list, T>
```
which is what we would expect. (the same goes for `CursorMut`). Furthermore, the
lifetime elision in `current`, `peek` and `peek_before` prevent leaking of data.
as the references they return borrow the cursor, so it cannot be moved or used
to edit the list while they live.

The only other lifetime annotation is with `as_cursor`. In this case, the
returned `Cursor` must borrow its generating `CursorMut`. Otherwise, it would be
possible to achieve a mutable and immutable reference to the same element at
once.

One question that arises from this interface is what happens if `move_next` is
called when a cursor is on the last element of the list, or is empty (or
`move_prev` and the beginning). A simple way to solve this is to make cursors
Expand Down

0 comments on commit 524f9f8

Please sign in to comment.