Rental - A Macro to generate self-referential structs

Documentation

Overview

It can sometimes occur in the course of designing an API that it would be convenient, or even necessary, to allow fields within a struct to hold references to other fields within that same struct. Rust's concept of ownership and borrowing is quite flexible, but can't quite express such a scenario yet.

Creating such a struct manually requires unsafe code to erase lifetime parameters from the field types. Accessing such a field directly would be completely unsafe as a result. This library addresses the issue by allowing access to the internal fields only under carefully controlled circumstances, through closures that are bounded by generic lifetimes to prevent infiltration or exfiltration of any data with an incorrect lifetime.

The API of this crate consists of the rental macro, which generates self-referential structs, and a few example instantiations to demonstrate the API provided by such structs (see RentRef, RentMut, RentRefMap, RentMutMap).

Use Cases

One instance where this crate is useful is when working with libloading. That crate provides a Library struct that defines methods to borrow Symbols from it. These symbols are bounded by the lifetime of the library, and are thus considered a borrow. Under normal circumstances, one would be unable to store both the library and the symbols within a single struct, but the macro defined in this crate allows you to define a struct that is capable of storing both simultaneously, like so:

```rust,ignore rental! { pub mod rent_libloading { use libloading;

    #[rental(deref_suffix)] // This struct will deref to the target of Symbol.
    pub struct RentSymbol<S: 'static> {
        lib: Box<libloading::Library>, // Library is boxed for stable deref.
        sym: libloading::Symbol<'lib, S>, // The 'lib lifetime borrows lib.
    }
}

}

fn main() { let lib = libloading::Library::new("mylib.so").unwrap(); // Open our dylib. if let Ok(rs) = rentlibloading::RentSymbol::trynew( Box::new(lib), |lib| unsafe { lib.get::symbol") }) // Loading Symbols is unsafe. { (*rs)(); // Call our function }; } ```

In this way we can store both the Library and the Symbol that borrows it in a single struct. We can even tell our struct to deref to the function pointer itself so we can easily call it. This is legal because the function pointer does not contain any of the special lifetimes introduced by the rental struct in its type signature, which means reborrowing will not expose them to the outside world. As an aside, the unsafe block for loading the symbol is necessary because the act of loading a symbol from a dylib is unsafe, and is unrelated to rental.

Limitations

There are a few limitations with the current implementation. These limitations aren't fundamental, but rather the result of bugs or pending features in rust itself, and will be lifted once the underlying language allows it.