Crate deferred_reference[][src]

This crate helps with creating multiple mutable references to the contents of a variable without triggering undefined behavior. The Rust borrow rules dictate that it is undefined behavior to create more than one mutable reference to the same region, even if the mutable reference is not used. However, this can sometimes be a tad too restrictive if the programmer knows that two mutable references will not overlap. Using raw pointers, it is already possible to work-around the Rust borrow rules today, but this requires wizard-like skills and in-depth knowledge of handling raw pointers and this is more prone to error than using Rust references. With the introduction of non-lexical lifetimes in the Rust 2018 edition, the ergonomics around references have already significantly improved, but there are still some corner-cases where the programmer wished there was some way to create non-overlapping mutable references into the same location (e.g. disjoint indices of a slice or array), without resorting to manually managed raw pointers. In order to aid with this, this crate introduces the concept of a “deferred reference1. A deferred reference is almost exactly like a regular reference (e.g. a &T or a &mut T), but it differs from a regular reference in the following ways:

  • A deferred reference is not an actual reference, it is merely a smart pointer tied to the lifetime of the location it points to (regular raw pointers always have a static lifetime, and can thus become dangling if the location it points to is moved or dropped).
  • It is allowed to keep multiple deferred mutable references around (as long as these are not dereferenced in a way so that these create an overlap between a mutable reference and another (de)reference).

A deferred reference is embodied by an instance of the Deferred struct, which can be used like a regular Reference. There exist only two types of references and therefore there are two flavors of Deferred, namely Deferred<&T> and Deferred<&mut T>. Both of these can be used the same way as a regular reference, because Deferred<&T> implements the Deref trait and Deferred<&mut T> implements both the Deref trait and the DerefMut trait.

In order to obtain a Deferred<&T> or a Deferred<&mut T>, see the documentation at Deferred explaining the constructors for deferred immutable references and constructors for deferred mutable references.

Arrays and slices

The Deferred struct also provides some interesting functionality for deferred arrays and slices, for which it implements the Index and IndexMut traits in a way that it only creates references to the queried indices but not to the other disjoint subslices. This allows multiple threads to simultaneouslt mutate the same array or slice as long as these threads don’t create mutable references that overlap in index or in lifetime. Currently this functionality is available on stable Rust 1.51.0 for arrays [T; N] thanks to the introduction of the min_const_generics feature, but to use this functionality on slices [T], too, nightly Rust is required until the slice_ptr_len feature stabilizes. For more details, see the methods available for deferred references to slices and arrays.

Example

Here is an example of how one might use the Deferred struct:

use deferred_reference::{Defer, DeferMut, Deferred};
use core::cell::UnsafeCell;
use core::ops::DerefMut;
let buffer = Box::new(UnsafeCell::new([0u8; 1024])); // the `Box` is optional
// calling defer() or defer_mut() immutably borrows `buffer` for as long
// as the returned `Deferred` is in use.
let deferred: Deferred<&[u8; 1024]> = buffer.defer();
// SAFETY: this is safe, because we promise not to create an overlapping mutable reference
let mut deferred_mut: Deferred<&mut [u8; 1024]> = unsafe { buffer.defer_mut() };
// both `deferred` and `deferred_mut` can be safely immutably dereferenced simultaneously:
assert_eq!(&deferred[0], &deferred_mut[0]);
// we can mutate the `buffer` through `deferred_mut` as any other array.
// this implicity creates a temporary mutable reference into the array inside `buffer`.
// even though an immutable reference to `buffer` exists, this is okay because
// the inner array sits inside an `UnsafeCell` which allows interior mutability:
deferred_mut[0] = 42; 
// and observe the change through `deferred`:
assert_eq!(deferred[0], 42);
// all this time, both deferred references are alive, but because
// these are not actual references, this doesn't violate the Rust borrow
// rules and this is not undefined behavior. The lifetimes of the mutable
// and immutable references derived from the Deferred do not overlap,
// so the Rust borrow rules are respected all this time.
assert_eq!(&deferred[0], &deferred_mut[0]);
// this also works for multiple deferred mutable references!
// SAFETY: this is safe, because we promise not to create overlapping references
let mut deferred_mut2 = unsafe { buffer.defer_mut() };
// we can mutate the buffer through 2 distinct deferred mutable references
// (as long as we don't do this at the same time!)
deferred_mut[0] += 1; // the actual mutable borrow starts and ends here
// the next line does not overlap with the previous, thanks to non-lexical lifetimes:
deferred_mut2[0] += 1; 
assert_eq!(44, deferred[0]);
assert_eq!(deferred_mut[0], deferred_mut2[0]);
// however, the following is not okay, because this would create two overlapping
// mutable references and this is undefined behavior (hence the use of `unsafe` above):
//assert_eq!(&mut deferred_mut[0], &mut deferred_mut2[0]); // undefined behavior!
// because `Deferred` implements the `Index` and `IndexMut` trait, it is possible
// to create two references that overlap in lifetime, but are disjoint in index:
assert_eq!(&mut deferred_mut[1], &mut deferred_mut2[2]); // indices are disjoint, so no UB
// this is not possible with regular slice references, because these alias the entire slice:
//assert_eq!(&mut deferred_mut.deref_mut()[1], &mut deferred_mut2.deref_mut()[2]); // UB!

Why not use <[T]>::split_at_mut instead of Deferred?

The Rust core library function split_at_mut provides a convenient method to safely split a mutable reference into two mutable references. However, it has one big drawback: in order to call it, you must already have the mutable reference. This might not always be possible. For example, in a multi-threaded environment, some threads may want to temporarily keep an immutable reference to a slice index because these threads only read, while some threads need a temporary mutable reference into another slice index. This is not possible if one thread holds a mutable reference to the entire slice, because then the co-existance of any mutable and immutable references would trigger undefined behavior. With deferred references, this is no longer a problem, because an initial mutable reference is not required. In fact, the first mutable reference is not even created until the first time the Deferred<&mut> is dereferenced. This crate also provides a method Deferred::split_at_mut which can split a deferred reference to a slice or an array into two deferred references. This method does not create any intermediary references to the subslices.

#![no_std] environments

This crate is entirely #![no_std] and does not depend on the alloc crate. No additional Cargo.toml features need to be configured in order to support #![no_std] environments. This crate also does not have any dependencies in its Cargo.toml.

Miri tested

This crate is extensively tested using Miri using the -Zmiri-track-raw-pointers flag:

$ MIRIFLAGS="-Zmiri-track-raw-pointers" cargo miri test

Miri follows the Stacked Borrows model (by Ralf Jung et al.) and so does this crate. If you happen to spot any violations of this model in this crate, feel free to open a Github issue!

Footnotes


  1. The concept of “deferred references” is inspired by the concept of “Deferred Borrows” authored by Chris Fallin. However, these are not entirely the same concept. These differ in the sense that deferred borrows bring an extension to the Rust type system (called static path-dependent types) and its implementation is intended to live within the Rust compiler, while deferred references are implemented in Rust code that is already possible today with its existing type system. The trade-off made here is that this requires minimal use of unsafe code blocks with deferred references, while deferred borrows would work entirely within “safe Rust” if these were to be implemented in the Rust compiler. There are also some similarities between the two concepts: both concepts are statically applied during compile-time and due not incur any runtime overhead. Also, with both approaches an actual reference is not created until the reference is actually in use (i.e. dereferenced or borrowed for an extended period of time). 

Macros

defer

An unsafe macro to create a deferred immutable reference (i.e. a Deferred<&T>) to a place, without creating an intermediate reference. See the documentation at Deferred explaining the constructors for deferred immutable references for safe alternatives.

defer_mut

An unsafe macro to create a deferred mutable reference (i.e. a Deferred<&mut T>) to a place, without creating an intermediate reference. See the documentation at Deferred explaining the constructors for deferred mutable references for safer alternatives.

Structs

Deferred

A smart pointer which holds a “deferred reference” to an instance of type T: ?Sized. It has all the properties of a normal reference (&T or &mut T), except that it does not hold an actual reference. This makes it possible pass around multiple deferred references in unsafe code, without triggering undefined behavior due to existence of aliased mutable references. Deferred aims to make it easier to reason about the validity and lifetime of pointers during the act of dereferencing.

Traits

Defer

The Defer trait offers easy access to deferred immutable references to types that implement Defer.

DeferMut

The DeferMut trait offers easy access to deferred mutable references to types that implement DeferMut. This trait is already implemented on all types T: ?Sized for UnsafeCell<T> out-of-the-box and this should be sufficient for most purposes, but it is also possible to implement the Defer and DeferMut traits for your own types, please see the documentation of this trait on how to do this safely.

PointerLength

A trait which is only implemented for pointers for which the length of the pointee can be determined without creating a reference to the pointee and without accessing the pointee. This means that the pointer is not dereferenced.

Reference

This trait is implemented for all references. Rust has only two types of references to a type T: ?Sized, namely &T and &mut T. This trait is sealed and can not be implemented for any other types.

SliceLike

This trait is implemented for all slice-like structures. Currently there are only 2 of these types: arrays [T; N] and slices [T].

SlicePointerIndex

A helper trait used for indexing operations, which is modeled after the SliceIndex trait from the Rust core library, but which promises not to take a reference to the underlying slice.