1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
//! 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.
//!
//! ```rust
//! 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.
//!
//! ```rust
//! 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);
//! }
//! ```
//!
/// It checks whether borrowing the same element at runtime, if so it'll panic.
///
/// ```rust
/// 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]);
/// ```
/// Get mutable references to two elements from the array.
///
/// If a0 and a1 point to the same element, it will return Err(&mut T).
/// ```rust
/// 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);
/// }
/// ```