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
120
121
122
123
124
125
126
127
128
129
130
131
132
pub use *;
pub use *;
use ;
/// Seek asynchronously through a shared slice with a list of indices.
///
/// SelectIndicesPar provides a [ParallelIterator](https://docs.rs/rayon/1.5.1/rayon/iter/trait.ParallelIterator.html)
/// that can split a contiguous, immutable slice of objects
/// (`&[T]`) into individual, shared references (`&T`).
/// Seek asynchronously through an exclusive slice with a list of indices.
///
/// SelectIndicesParMut provides a [ParallelIterator](https://docs.rs/rayon/1.5.1/rayon/iter/trait.ParallelIterator.html)
/// that can split a contiguous, mutable slice of objects (`&mut [T]`)
/// into individual, exclusive references (`&mut T`).
///
/// The lifetimes of the references are linked to the original slice,
/// so the iterator cannot produce dangling references.
/// ```compile_fail
/// # use select_indices::prelude::*;
/// let refs: Vec<&mut i8>; // Vec of mutable elements within 'data'
///
/// {
/// let mut data = vec![1, 2, 3, 4, 5];
///
/// // Collect mutable references
/// refs = data.par_select_indices_mut(&[0,1,2]).collect();
/// }
///
/// // Compiler error: 'data' was dropped, references are invalid
/// refs.into_iter().for_each(|x| *x += 1);
/// ```
///
/// Mutable references collected from the iterator also cannot
/// violate the borrow checker.
///
/// ```compile_fail
/// # use select_indices::prelude::*;
/// let mut refs: Vec<&mut i8>;
/// let mut data = vec![1, 2, 3, 4, 5];
/// {
/// // first mutable borrow
/// refs = data.par_select_indices_mut(&[0, 1, 2, 3, 4]).collect();
/// }
///
/// data.sort(); // Compiler error: second mutable borrow
/// data[4] = 9; // Compiler error: second mutable borrow
/// *refs[4] = 65; // first borrow used here
/// ```
///
/// Lastly, collected references cannot violate the borrow checker
/// when sent to other threads (as far as I can tell).
/// ```compile_fail
/// # use select_indices::prelude::*;
/// # use std::thread;
/// let mut data = [1,2,3,4,5];
///
/// {
/// let mut refs: Vec<&mut i8> = data.par_select_indices_mut(&[3,4]).collect();
///
/// // refs is moved out of this thread
/// thread::spawn(move || *refs[0] = 99);
/// }
///
/// data[3] = 57; // Compile error: Assignment to borrowed data
/// ```