orx_concurrent_vec/concurrent_slice/
unsafe_api.rs

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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use super::ConcurrentSlice;
use crate::ConcurrentElement;
use core::sync::atomic::Ordering;
use orx_pinned_vec::IntoConcurrentPinnedVec;

impl<T, P> ConcurrentSlice<'_, T, P>
where
    P: IntoConcurrentPinnedVec<ConcurrentElement<T>>,
{
    /// Returns:
    /// * a raw `*const T` pointer to the underlying data if element at the `i`-th position is pushed,
    /// * `None` otherwise.
    ///
    /// # Safety
    ///
    /// Please see below the safety guarantees and potential safety risks using the pointer obtained by this method.
    ///
    /// ## Safety Guarantees
    ///
    /// Pointer obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained pointer throughout the lifetime of the vec.
    /// It is guaranteed that it will be valid pointing to the correct position with initialized data.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out a pointer, using which can cause data races as follows:
    /// * The value of the position can be `replace`d or `set` or `update`d concurrently by another thread.
    /// * If at the same instant, we attempt to read using this pointer, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the position will not be being mutated
    /// while using the pointer to directly access the data.
    ///
    /// A common use case to this is the grow-only scenarios where added elements are not mutated:
    /// * elements can be added to the vector by multiple threads,
    /// * while already pushed elements can safely be accessed by other threads using `get_raw`.
    pub fn get_raw(&self, i: usize) -> Option<*const T> {
        self.idx(i).and_then(|i| self.vec.get_raw(i))
    }

    /// Returns a reference to the element at the `i`-th position of the vec.
    /// It returns `None` if index is out of bounds.
    ///
    /// # Safety
    ///
    /// All methods that return `&T` or `&mut T` references are marked as unsafe.
    /// Please see the reason and possible scenarios to use it safely below.
    ///
    /// ## Safety Guarantees
    ///
    /// Reference obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained reference throughout the lifetime of the vec.
    /// It is guaranteed that the reference will be valid pointing to the correct position.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out a reference, which can cause data races as follows:
    /// * The value of the position can be `replace`d or `set` or `update`d concurrently by another thread.
    /// * If at the same instant, we attempt to read using this reference, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the position will not be being mutated
    /// while using the reference to directly access the data.
    ///
    /// A common use case to this is the grow-only scenarios where added elements are not mutated:
    /// * elements can be added to the vector by multiple threads,
    /// * while already pushed elements can safely be accessed by other threads using `get`.
    ///
    /// # Examples
    ///
    /// As explained above, the following constructs a safe usage example of the unsafe get method.
    ///
    /// ```rust
    /// use orx_concurrent_vec::*;
    /// use std::time::Duration;
    ///
    /// #[derive(Debug, Default)]
    /// struct Metric {
    ///     sum: i32,
    ///     count: i32,
    /// }
    ///
    /// impl Metric {
    ///     fn aggregate(self, value: &i32) -> Self {
    ///         Self {
    ///             sum: self.sum + value,
    ///             count: self.count + 1,
    ///         }
    ///     }
    /// }
    ///
    /// // record measurements in random intervals, roughly every 2ms
    /// let measurements = ConcurrentVec::new();
    ///
    /// // collect metrics every 100 milliseconds
    /// let metrics = ConcurrentVec::new();
    ///
    /// std::thread::scope(|s| {
    ///     // thread to store measurements as they arrive
    ///     s.spawn(|| {
    ///         for i in 0..100 {
    ///             std::thread::sleep(Duration::from_millis(i % 5));
    ///
    ///             // collect measurements and push to measurements vec
    ///             measurements.push(i as i32);
    ///         }
    ///     });
    ///
    ///     // thread to collect metrics every 100 milliseconds
    ///     s.spawn(|| {
    ///         for _ in 0..10 {
    ///             // safely read from measurements vec to compute the metric
    ///             // since pushed elements are not being mutated
    ///             let len = measurements.len();
    ///             let mut metric = Metric::default();
    ///             for i in 0..len {
    ///                 if let Some(value) = unsafe { measurements.get_ref(i) } {
    ///                     metric = metric.aggregate(value);
    ///                 }
    ///             }
    ///
    ///             // push result to metrics
    ///             metrics.push(metric);
    ///
    ///             std::thread::sleep(Duration::from_millis(100));
    ///         }
    ///     });
    /// });
    ///
    /// let measurements: Vec<_> = measurements.to_vec();
    /// let averages: Vec<_> = metrics.to_vec();
    ///
    /// assert_eq!(measurements.len(), 100);
    /// assert_eq!(averages.len(), 10);
    /// ```
    pub unsafe fn get_ref(&self, i: usize) -> Option<&T> {
        self.idx(i).and_then(|i| self.vec.get_ref(i))
    }

    /// Returns an iterator to references of elements of the vec.
    ///
    /// See also [`iter`] and [`iter_cloned`] for thread-safe alternatives of concurrent access to elements.
    ///
    /// [`iter`]: crate::ConcurrentVec::iter
    /// [`iter_cloned`]: crate::ConcurrentVec::iter_cloned
    ///
    /// # Safety
    ///
    /// All methods that return `&T` or `&mut T` references are marked as unsafe.
    /// Please see the reason and possible scenarios to use it safely below.
    ///
    /// ## Safety Guarantees
    ///
    /// References obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained references throughout the lifetime of the vec.
    /// It is guaranteed that the references will be valid pointing to the correct positions.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out references that can cause data races as follows:
    /// * Values of elements in the vector can be concurrently mutated by methods such as `replace` or `update` by other threads.
    /// * If at the same instant, we attempt to read using these references, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the position will not be being mutated
    /// while using these references to directly access the data.
    ///
    /// A common use case to this is the grow-only scenarios where added elements are not mutated:
    /// * elements can be added to the vector by multiple threads,
    /// * while already pushed elements can safely be accessed by other threads using `iter`.
    ///
    /// # Examples
    ///
    /// As explained above, the following constructs a safe usage example of the unsafe iter method.
    ///
    /// ```rust
    /// use orx_concurrent_vec::*;
    /// use std::time::Duration;
    ///
    /// #[derive(Debug, Default)]
    /// struct Metric {
    ///     sum: i32,
    ///     count: i32,
    /// }
    ///
    /// impl Metric {
    ///     fn aggregate(self, value: &i32) -> Self {
    ///         Self {
    ///             sum: self.sum + value,
    ///             count: self.count + 1,
    ///         }
    ///     }
    /// }
    ///
    /// // record measurements in random intervals, roughly every 2ms
    /// let measurements = ConcurrentVec::new();
    ///
    /// // collect metrics every 100 milliseconds
    /// let metrics = ConcurrentVec::new();
    ///
    /// std::thread::scope(|s| {
    ///     // thread to store measurements as they arrive
    ///     s.spawn(|| {
    ///         for i in 0..100 {
    ///             std::thread::sleep(Duration::from_millis(i % 5));
    ///
    ///             // collect measurements and push to measurements vec
    ///             measurements.push(i as i32);
    ///         }
    ///     });
    ///
    ///     // thread to collect metrics every 100 milliseconds
    ///     s.spawn(|| {
    ///         for _ in 0..10 {
    ///             // safely read from measurements vec to compute the metric
    ///             // since pushed elements are never mutated
    ///             let metric = unsafe {
    ///                 measurements
    ///                     .iter_ref()
    ///                     .fold(Metric::default(), |x, value| x.aggregate(value))
    ///             };
    ///
    ///             // push result to metrics
    ///             metrics.push(metric);
    ///
    ///             std::thread::sleep(Duration::from_millis(100));
    ///         }
    ///     });
    /// });
    ///
    /// let measurements: Vec<_> = measurements.to_vec();
    /// let averages: Vec<_> = metrics.to_vec();
    ///
    /// assert_eq!(measurements.len(), 100);
    /// assert_eq!(averages.len(), 10);
    /// ```
    pub unsafe fn iter_ref(&self) -> impl Iterator<Item = &T> {
        let b = self.a + self.len;
        unsafe { self.vec.core.iter_over_range(self.a..b) }
            .flat_map(|x| unsafe { x.0.as_ref_with_order(Ordering::SeqCst) })
    }

    // mut

    /// Returns:
    /// * a raw `*mut T` pointer to the underlying data if element at the `i`-th position is pushed,
    /// * `None` otherwise.
    ///
    /// # Safety
    ///
    /// Please see below the safety guarantees and potential safety risks using the pointer obtained by this method.
    ///
    /// ## Safety Guarantees
    ///
    /// Pointer obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained pointer throughout the lifetime of the vec.
    /// It is guaranteed that it will be valid pointing to the correct position with initialized data.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out a pointer, using which can cause data races as follows:
    /// * The value of the position can be `replace`d or `set` or `update`d concurrently by another thread.
    /// * If at the same instant, we attempt to read using this pointer, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the position will not be being
    /// read or written by another thread while using the pointer to directly access the data.
    pub fn get_raw_mut(&self, i: usize) -> Option<*mut T> {
        self.idx(i).and_then(|i| self.vec.get_raw_mut(i))
    }

    /// Returns a mutable reference to the element at the `i`-th position of the vec.
    /// It returns `None` if index is out of bounds.
    ///
    /// See also [`get`] and [`swap`] for thread-safe alternatives of concurrent mutation of elements.
    ///
    /// [`get`]: crate::ConcurrentVec::get
    /// [`swap`]: crate::ConcurrentVec::swap
    ///
    /// # Safety
    ///
    /// All methods that leak out `&T` or `&mut T` references are marked as unsafe.
    /// Please see the reason and possible scenarios to use it safely below.
    ///
    /// ## Safety Guarantees
    ///
    /// Reference obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained reference throughout the lifetime of the vec.
    /// It is guaranteed that the reference will be valid pointing to the correct position.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out a reference, which can cause data races as follows:
    /// * The value of the position can be `replace`d or `set` or `update`d concurrently by another thread.
    /// * And it maybe read by safe access methods such as `map` or `cloned`.
    /// * If at the same instant, we attempt to read or write using this reference, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the position will not be being
    /// read or written by another thread while using the reference to directly access the data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use orx_concurrent_vec::*;
    ///
    /// let vec = ConcurrentVec::new();
    /// vec.extend(['a', 'b', 'c', 'd']);
    ///
    /// assert_eq!(unsafe { vec.get_mut(4) }, None);
    ///
    /// *unsafe { vec.get_mut(1).unwrap() } = 'x';
    /// assert_eq!(unsafe { vec.get_ref(1) }, Some(&'x'));
    ///
    /// assert_eq!(&vec, &['a', 'x', 'c', 'd']);
    /// ```
    pub unsafe fn get_mut(&self, i: usize) -> Option<&mut T> {
        self.idx(i).and_then(|i| self.vec.get_mut(i))
    }

    /// Returns an iterator to mutable references of elements of the vec.
    ///
    /// See also [`iter`], [`fill`] and [`fill_with`] for thread-safe alternatives of concurrent mutation of elements.
    ///
    /// [`iter`]: crate::ConcurrentVec::iter
    /// [`fill`]: crate::ConcurrentVec::fill
    /// [`fill_with`]: crate::ConcurrentVec::fill_with
    ///
    /// # Safety
    ///
    /// All methods that leak out `&T` or `&mut T` references are marked as unsafe.
    /// Please see the reason and possible scenarios to use it safely below.
    ///
    /// ## Safety Guarantees
    ///
    /// References obtained by this method will be valid:
    ///
    /// * `ConcurrentVec` prevents access to elements which are not added yet.
    /// * `ConcurrentOption` wrapper prevents access during initialization, and hence, prevents data race during initialization.
    /// * `PinnedVec` storage makes sure that memory location of the elements never change.
    ///
    /// Therefore, the caller can hold on the obtained references throughout the lifetime of the vec.
    /// It is guaranteed that the references will be valid pointing to the correct position.
    ///
    /// ## Unsafe Bits
    ///
    /// However, this method still leaks out references, which can cause data races as follows:
    /// * Values of elements can be concurrently read by other threads.
    /// * Likewise, they can be concurrently mutated by thread-safe mutation methods.
    /// * If at the same instant, we attempt to read or write using these references, we would end up with a data-race.
    ///
    /// ## Safe Usage
    ///
    /// This method can be safely used as long as the caller is able to guarantee that the elements will not be being
    /// read or written by another thread while using the reference to directly access the data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use orx_concurrent_vec::*;
    ///
    /// let vec = ConcurrentVec::from_iter([0, 1, 2, 3]);
    ///
    /// let iter = unsafe { vec.iter_mut() };
    /// for x in iter {
    ///     *x *= 2;
    /// }
    ///
    /// assert_eq!(&vec, &[0, 2, 4, 6]);
    /// ```
    pub unsafe fn iter_mut(&self) -> impl Iterator<Item = &mut T> {
        let b = self.a + self.len;
        unsafe { self.vec.core.iter_over_range(self.a..b) }
            .flat_map(|x| x.0.get_raw_mut().map(|p| &mut *p))
    }
}