#reference #lifetime #borrow #scoped #abort #static #runtime-checked

no-std scoped_reference

Runtime-checked borrow lifetimes

4 releases

0.1.3 Feb 4, 2023
0.1.2 Nov 29, 2022
0.1.1 Nov 29, 2022
0.1.0 Nov 27, 2022

#7 in #abort

Download history 1/week @ 2024-02-19 4/week @ 2024-02-26 41/week @ 2024-03-11 40/week @ 2024-04-01

81 downloads per month

MIT/Apache

11KB
193 lines

Scoped Reference

Crates.io Docs.rs

This crate provides runtime-checked borrow lifetimes. It allows one to store references of the form &'a T as structs with lifetime 'static. This is useful in situations where a reference with a shorter lifetime cannot be stored naturally.

The following example demonstrates the use of scoped references. Scoped references come in both mutable and immutable variants. If the underlying reference is dropped while scoped borrows to it still exist, then the program panics. Note that a panic will always cause an immediate abort - unwinding is not allowed - because allowing unwinding could lead to dangling references and undefined behavior.

struct StaticBorrow(ScopedBorrow<i32>);

let mut x = 10;
let borrowed_x = &mut x;
let mut scoped_ref = ScopedReference::new_mut(borrowed_x);

let mut mut_ref_to_x = scoped_ref.borrow_mut();
*mut_ref_to_x = 9;

// Panic: mut_ref_to_x is still out!
// drop(scoped_ref);

drop(mut_ref_to_x);

let static_borrow = StaticBorrow(scoped_ref.borrow());
assert_eq!(*static_borrow.0, 9);

// Panic: static_borrow is still out!
// drop(scoped_ref);

drop(static_borrow);
drop(scoped_ref);

No runtime deps

Features