#array #borrow #index

arref

Make borrow mut elements from an array easier

1 unstable release

0.1.0 Sep 26, 2022

#53 in #borrow

Download history 18/week @ 2024-01-11 5/week @ 2024-01-18 5/week @ 2024-02-01 24/week @ 2024-02-08 38/week @ 2024-02-15 61/week @ 2024-02-22 33/week @ 2024-02-29 34/week @ 2024-03-07 21/week @ 2024-03-14 37/week @ 2024-03-21 57/week @ 2024-03-28 49/week @ 2024-04-04 66/week @ 2024-04-11 54/week @ 2024-04-18 47/week @ 2024-04-25

222 downloads per month
Used in 10 crates (6 directly)

MIT license

6KB
50 lines

Getting mutable references to two elements from the same array is hard. This tiny lib provides method to make it easier.

[array_mut_ref!] checks whether the user borrows the same element at runtime.

use arref::array_mut_ref;
let mut arr = vec![1, 2, 3, 4];
let (a, b) = array_mut_ref!(&mut arr, [1, 2]);
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let (a, b, c) = array_mut_ref!(&mut arr, [1, 2, 0]);
assert_eq!(*c, 1);

// ⚠️ The following code will panic. Because we borrow the same element twice.
// let (a, b) = array_mut_ref!(&mut arr, [1, 1]);

Alternatively, you can use [mut_twice]. It won't panic if you borrow the same element twice. It'll return an Err(&mut T) instead.

use arref::mut_twice;
let mut arr = vec![1, 2, 3];
let (a, b) = mut_twice(&mut arr, 1, 2).unwrap();
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let result = mut_twice(&mut arr, 1, 1);
assert!(result.is_err());
if let Err(v) = result {
    assert_eq!(*v, 2);
}

lib.rs:

Getting mutable references to two elements from the same array is hard. This tiny lib provides method to make it easier.

[array_mut_ref!] checks whether the user borrows the same element at runtime.

use arref::array_mut_ref;
let mut arr = vec![1, 2, 3, 4];
let (a, b) = array_mut_ref!(&mut arr, [1, 2]);
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let (a, b, c) = array_mut_ref!(&mut arr, [1, 2, 0]);
assert_eq!(*c, 1);

// ⚠️ The following code will panic. Because we borrow the same element twice.
// let (a, b) = array_mut_ref!(&mut arr, [1, 1]);

Alternatively, you can use [mut_twice]. It won't panic if you borrow the same element twice. It'll return an Err(&mut T) instead.

use arref::mut_twice;
let mut arr = vec![1, 2, 3];
let (a, b) = mut_twice(&mut arr, 1, 2).unwrap();
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let result = mut_twice(&mut arr, 1, 1);
assert!(result.is_err());
if let Err(v) = result {
    assert_eq!(*v, 2);
}

No runtime deps