paralight 0.0.11

A lightweight parallelism library for indexed structures
Documentation
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
407
408
// Copyright 2024-2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::ptr::NonNull;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};

/// An ergonomic wrapper around a [`Mutex`]-[`Condvar`] pair.
pub struct Status<T> {
    mutex: Mutex<T>,
    condvar: Condvar,
}

impl<T> Status<T> {
    /// Creates a new status initialized with the given value.
    pub fn new(t: T) -> Self {
        Self {
            mutex: Mutex::new(t),
            condvar: Condvar::new(),
        }
    }

    /// Attempts to set the status to the given value and notifies one waiting
    /// thread.
    ///
    /// Fails if the [`Mutex`] is poisoned.
    pub fn try_notify_one(&self, t: T) -> Result<(), PoisonError<MutexGuard<'_, T>>> {
        *self.mutex.lock()? = t;
        self.condvar.notify_one();
        Ok(())
    }

    /// Sets the status to the given value and notifies all waiting threads.
    pub fn notify_all(&self, t: T) {
        *self.mutex.lock().unwrap() = t;
        self.condvar.notify_all();
    }

    /// Waits until the predicate is true on this status.
    ///
    /// This returns a [`MutexGuard`], allowing to further inspect or modify the
    /// status.
    pub fn wait_while(&self, predicate: impl FnMut(&mut T) -> bool) -> MutexGuard<'_, T> {
        self.condvar
            .wait_while(self.mutex.lock().unwrap(), predicate)
            .unwrap()
    }
}

/// A Proxy trait for types that have a lifetime parameter.
///
/// Because Rust doesn't directly support higher-kinded types, we use a generic
/// associated type with a lifetime parameter to represent that.
pub trait LifetimeParameterized {
    type T<'a>: ?Sized;
}

/// A lifetime-erased reference, where the underlying type is generic over a
/// lifetime. This acts as a [`&'a T<'a>`](reference) but whose lifetime can be
/// adjusted via the `unsafe` function [`get()`](Self::get).
pub struct DynLifetimeView<T: LifetimeParameterized> {
    ptr: Option<NonNull<T::T<'static>>>,
}

impl<T: LifetimeParameterized> DynLifetimeView<T> {
    /// Creates a new empty reference.
    pub fn empty() -> Self {
        Self { ptr: None }
    }

    /// Sets the underlying value to the given reference. Subsequent calls to
    /// [`get()`](Self::get) must ensure that the obtained reference doesn't
    /// outlive the reference that was set here.
    // The cast is necessary because the lifetime is coerced to 'static.
    #[allow(clippy::unnecessary_cast)]
    pub fn set(&mut self, value: &T::T<'_>) {
        self.ptr = NonNull::new(NonNull::from(value).as_ptr() as *mut T::T<'static>);
    }

    /// Clears the underlying reference. Subsequent calls to
    /// [`get()`](Self::get) will obtain [`None`].
    pub fn clear(&mut self) {
        self.ptr = None;
    }

    /// Returns the reference that was previously set with [`set()`](Self::set),
    /// or [`None`] if no reference was set or if the last reference was
    /// erased by a call to [`clear()`](Self::clear).
    ///
    /// # Safety
    ///
    /// The underlying object must be valid and not mutated during the whole
    /// output lifetime.
    // The cast is necessary because the lifetime is coerced to 'a.
    #[allow(clippy::unnecessary_cast)]
    pub unsafe fn get<'a>(&self) -> Option<&'a T::T<'a>> {
        self.ptr.map(|static_ptr| {
            let ptr = static_ptr.as_ptr() as *mut T::T<'a>;
            // SAFETY:
            // - This pointer points to a valid initialized `T`, as previously set via
            //   `set()`.
            // - The underlying `T` outlives the output lifetime, as ensured by the caller.
            // - The underlying `T` isn't mutated during the whole output lifetime, as
            //   ensured by the caller.
            unsafe { &*ptr }
        })
    }
}

/// SAFETY:
///
/// A [`DynLifetimeView`] acts as a [`&'a T<'a>`](reference). Therefore it is
/// [`Send`] if and only if `T<'_>` is [`Sync`].
unsafe impl<T: LifetimeParameterized> Send for DynLifetimeView<T> where for<'a> T::T<'a>: Sync {}
/// SAFETY:
///
/// A [`DynLifetimeView`] acts as a [`&'a T<'a>`](reference). Therefore it is
/// [`Sync`] if and only if `T<'_>` is [`Sync`].
unsafe impl<T: LifetimeParameterized> Sync for DynLifetimeView<T> where for<'a> T::T<'a>: Sync {}

#[cfg(test)]
mod test {
    use super::*;
    use std::sync::{Arc, Barrier, RwLock};

    // A type that doesn't have a lifetime parameter trivially implements
    // `LifetimeParameterized`.
    impl LifetimeParameterized for i32 {
        type T<'a> = Self;
    }

    #[test]
    fn view_basic_usage() {
        let mut view = DynLifetimeView::<i32>::empty();

        let mut foo = 42;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(*bar, 42);

        foo = 1;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(*bar, 1);

        let abc = 123;
        view.set(&abc);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(*bar, 123);
    }

    #[test]
    fn view_multi_threaded() {
        const NUM_THREADS: usize = 2;

        let view = Arc::new(RwLock::new(DynLifetimeView::<i32>::empty()));
        let steps: Arc<[_; 6]> = Arc::new(std::array::from_fn(|_| Barrier::new(NUM_THREADS + 1)));

        let main = std::thread::spawn({
            let view = view.clone();
            let steps = steps.clone();
            move || {
                let mut foo = 42;
                view.write().unwrap().set(&foo);

                steps[0].wait();

                steps[1].wait();

                foo = 1;
                view.write().unwrap().set(&foo);

                steps[2].wait();

                steps[3].wait();

                let abc = 123;
                view.write().unwrap().set(&abc);

                steps[4].wait();

                steps[5].wait();
            }
        });

        let threads: [_; NUM_THREADS] = std::array::from_fn(move |_| {
            std::thread::spawn({
                let view = view.clone();
                let steps = steps.clone();
                move || {
                    steps[0].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(*reference, 42);
                    drop(guard);

                    steps[1].wait();

                    steps[2].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(*reference, 1);
                    drop(guard);

                    steps[3].wait();

                    steps[4].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(*reference, 123);
                    drop(guard);

                    steps[5].wait();
                }
            })
        });

        main.join().unwrap();
        for t in threads {
            t.join().unwrap();
        }
    }

    // This ignored test showcases how to misuse the unsafe API by mutating a value
    // while it is referenced. Running it under Miri returns a failure.
    #[ignore]
    #[cfg_attr(coverage_nightly, coverage(off))]
    #[test]
    #[allow(unused_assignments)]
    fn view_bad_mut() {
        let mut view = DynLifetimeView::<i32>::empty();
        let mut foo = 42;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        // Undefined behavior: This mutates `foo` while a reference to it `bar` is
        // active.
        foo = 1;
        assert_eq!(*bar, 1);
    }

    // This ignored test showcases how to misuse the unsafe API by obtaining a
    // reference whose lifetime extends beyond the underlying value's. Running it
    // under Miri returns a failure.
    #[ignore]
    #[cfg_attr(coverage_nightly, coverage(off))]
    #[test]
    fn view_bad_lifetime() {
        let mut view = DynLifetimeView::<i32>::empty();
        {
            let foo = 42;
            view.set(&foo);
        }
        // Undefined behavior: This obtains a reference to `foo` which isn't live
        // anymore.
        let bar = unsafe { view.get().unwrap() };
        assert_ne!(*bar, 42);
    }

    impl LifetimeParameterized for &i32 {
        type T<'a> = &'a i32;
    }

    #[test]
    fn dyn_lifetime_view_basic_usage() {
        let mut view = DynLifetimeView::<&i32>::empty();

        let x = 42;
        let mut foo = &x;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(**bar, 42);

        let y = 1;
        foo = &y;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(**bar, 1);

        let z = 123;
        let abc = &z;
        view.set(&abc);
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(**bar, 123);
    }

    #[test]
    fn dyn_lifetime_view_multi_threaded() {
        const NUM_THREADS: usize = 2;

        let view = Arc::new(RwLock::new(DynLifetimeView::<&i32>::empty()));
        let steps: Arc<[_; 6]> = Arc::new(std::array::from_fn(|_| Barrier::new(NUM_THREADS + 1)));

        let main = std::thread::spawn({
            let view = view.clone();
            let steps = steps.clone();
            move || {
                let x = 42;
                let mut foo = &x;
                view.write().unwrap().set(&foo);

                steps[0].wait();

                steps[1].wait();

                let y = 1;
                foo = &y;
                view.write().unwrap().set(&foo);

                steps[2].wait();

                steps[3].wait();

                let z = 123;
                let abc = &z;
                view.write().unwrap().set(&abc);

                steps[4].wait();

                steps[5].wait();
            }
        });

        let threads: [_; NUM_THREADS] = std::array::from_fn(move |_| {
            std::thread::spawn({
                let view = view.clone();
                let steps = steps.clone();
                move || {
                    steps[0].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(**reference, 42);
                    drop(guard);

                    steps[1].wait();

                    steps[2].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(**reference, 1);
                    drop(guard);

                    steps[3].wait();

                    steps[4].wait();

                    let guard = view.read().unwrap();
                    let reference = unsafe { guard.get().unwrap() };
                    assert_eq!(**reference, 123);
                    drop(guard);

                    steps[5].wait();
                }
            })
        });

        main.join().unwrap();
        for t in threads {
            t.join().unwrap();
        }
    }

    // This ignored test showcases how to misuse the unsafe API by mutating a value
    // while it is referenced. Running it under Miri returns a failure.
    #[ignore]
    #[cfg_attr(coverage_nightly, coverage(off))]
    #[test]
    #[allow(unused_assignments)]
    fn dyn_lifetime_view_bad_mut() {
        let mut view = DynLifetimeView::<&i32>::empty();
        let x = 42;
        let mut foo = &x;
        view.set(&foo);
        let bar = unsafe { view.get().unwrap() };
        let y = 1;
        // Undefined behavior: This mutates `foo` while a reference to it `bar` is
        // active.
        foo = &y;
        assert_eq!(**bar, 1);
    }

    // This ignored test showcases how to misuse the unsafe API by obtaining a
    // reference whose lifetime extends beyond the underlying value's. Running it
    // under Miri returns a failure.
    #[ignore]
    #[cfg_attr(coverage_nightly, coverage(off))]
    #[test]
    fn dyn_lifetime_view_bad_lifetime() {
        let x = 42;
        let mut view = DynLifetimeView::<&i32>::empty();
        {
            let foo = &x;
            view.set(&foo);
        }
        // Undefined behavior: This obtains a reference to `foo` which isn't live
        // anymore.
        let bar = unsafe { view.get().unwrap() };
        assert_eq!(**bar, 42);
    }
}