#运行时 #借用 #映射

rt_vec

从vec中进行运行时管理的可变借用

2个版本

0.1.1 2022年7月15日
0.1.0 2022年6月27日

#1092 in 数据结构

MIT/Apache

20KB
243

🗃️ rt_vec

Crates.io docs.rs CI Coverage Status

从vec中进行运行时管理的可变借用。

此库提供了一个vec,允许同时从不同元素进行可变借用。有关此映射实现的详细信息,请参阅 rt_map

用法

将以下内容添加到 Cargo.toml

rt_vec = "0.1.1" # or
rt_vec = { version = "0.1.1", features = ["unsafe_debug"] }

代码中

use rt_vec::RtVec;

struct A(u32);

let mut rt_vec = RtVec::new();

rt_vec.push(A(1));
rt_vec.push(A(2));

// We can validly have two mutable borrows from the `RtVec` map!
let mut a = rt_vec.borrow_mut(0);
let mut b = rt_vec.borrow_mut(1);
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_vec.borrow(0);
let _a_1 = rt_vec.borrow(0);
let b = rt_vec.borrow(1);

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_vec.try_borrow_mut(0);
let exists = if a_try_borrow_mut.is_ok() {
    "Ok(..)"
} else {
    "Err"
};
println!("a_try_borrow_mut: {}", exists); // prints "Err"

功能

"unsafe_debug"

启用 "unsafe_debug" 特性 rt_ref

许可证

许可方式为以下之一

任选其一。

贡献

除非您明确表示,否则根据Apache-2.0许可证定义的您提交的任何有意包含在作品中的贡献,均应按照上述方式双许可,不附加任何额外的条款或条件。

依赖项

~39KB