#map #run-time #borrow

rt_map

Runtime managed mutable borrowing from a map

7 releases (4 breaking)

0.5.2 Jul 15, 2022
0.5.1 Jun 25, 2022
0.5.0 Oct 16, 2021
0.4.0 Aug 8, 2021
0.1.0 Jun 26, 2021

#20 in #borrow

Download history 92/week @ 2023-11-20 83/week @ 2023-11-27 36/week @ 2023-12-04 84/week @ 2023-12-11 80/week @ 2023-12-18 354/week @ 2023-12-25 227/week @ 2024-01-01 129/week @ 2024-01-08 44/week @ 2024-01-15 71/week @ 2024-01-22 282/week @ 2024-01-29 60/week @ 2024-02-05 72/week @ 2024-02-12 33/week @ 2024-02-19 92/week @ 2024-02-26 212/week @ 2024-03-04

412 downloads per month
Used in 29 crates (via resman)

MIT/Apache

22KB
315 lines

🗃️ rt_map

Crates.io docs.rs CI Coverage Status

Runtime managed mutable borrowing from a map.

This library provides a map that allows mutable borrows to different entries at the same time. For a map implementation of this, see rt_vec.

The implementation is extracted and slightly modified from shred.

Usage

Add the following to Cargo.toml

rt_map = "0.5.2" # or
rt_map = { version = "0.5.2", features = ["unsafe_debug"] }

In code:

use rt_map::RtMap;

struct A(u32);

fn main() {
    let mut rt_map = RtMap::new();

    rt_map.insert('a', A(1));
    rt_map.insert('b', A(2));

    // We can validly have two mutable borrows from the `RtMap` map!
    let mut a = rt_map.borrow_mut(&'a');
    let mut b = rt_map.borrow_mut(&'b');
    a.0 = 2;
    b.0 = 3;

    // We need to explicitly drop the A and B borrows, because they are runtime
    // managed borrows, and rustc doesn't know to drop them before the immutable
    // borrows after this.
    drop(a);
    drop(b);

    // Multiple immutable borrows to the same value are valid.
    let a_0 = rt_map.borrow(&'a');
    let _a_1 = rt_map.borrow(&'a');
    let b = rt_map.borrow(&'b');

    println!("A: {}", a_0.0);
    println!("B: {}", b.0);

    // Trying to mutably borrow a value that is already borrowed (immutably
    // or mutably) returns `Err`.
    let a_try_borrow_mut = rt_map.try_borrow_mut(&'a');
    let exists = if a_try_borrow_mut.is_some() {
        "Ok(..)"
    } else {
        "Err"
    };
    println!("a_try_borrow_mut: {}", exists); // prints "Err"
}

Features

"unsafe_debug"

Enables the "unsafe_debug" feature of rt_ref.

See Also

  • anymap: Map of any type, without multiple mutable borrows.
  • resman: Map of any type, with runtime managed borrowing.
  • shred: Like resman, plus a task dispatcher.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~39KB