Skip to content

Commit

Permalink
Merge #2077
Browse files Browse the repository at this point in the history
2077: Add TakeCell::get_mut function r=phil-levis a=daboross

### Pull Request Overview

This adds `TakeCell::get_mut`, a function with the signature `fn get_mut(&mut self) -> Option<&mut T>`. Specifically, it bypasses the Cell nature of take_cell for when you already have access to an `&mut TakeCell`.

This is entirely safe, and works similarly to the corresponding method in `Cell`, `Cell::get_mut`. It's made safe by the fact that the returned value is lifetime bound to the mutable borrow of the `TakeCell` itself, not to `'a` - and thus, requires no new unsafe code to implement.

This was useful for an odd interaction with the rubble interface when implementing tock_rubble - it needs to retrieve an `&mut [u8]` multiple times safely, and then also use that buffer as an `&'static mut [u8]` which can be taken out. Thus a `TakeCell`, with the addition of this `get_mut` method, works well.

### Testing Strategy

CI

### TODO or Help Wanted


### Documentation Updated

- [x] Updated the relevant files in `/docs`, or no updates are required.

### Formatting

- [x] Ran `make prepush`.


Co-authored-by: David Ross <David.Ross@wdc.com>
  • Loading branch information
bors[bot] and David Ross committed Sep 9, 2020
2 parents 602d0fb + 162efed commit 5daa83c
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions libraries/tock-cells/src/take_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ impl<'a, T: ?Sized> TakeCell<'a, T> {
self.val.replace(Some(val))
}

/// Retrieves a mutable reference to the inner value that only lives as long
/// as the reference to this does.
///
/// This escapes the "take" aspect of TakeCell in a way which is guaranteed
/// safe due to the returned reference sharing the lifetime of `&mut self`.
pub fn get_mut(&mut self) -> Option<&mut T> {
self.val.get_mut().as_mut().map(|v| &mut **v)
}

/// Allows `closure` to borrow the contents of the `TakeCell` if-and-only-if
/// it is not `take`n already. The state of the `TakeCell` is unchanged
/// after the closure completes.
Expand Down

0 comments on commit 5daa83c

Please sign in to comment.