orengine 0.7.0-alpha.1

Optimized ring engine for Rust. It is a lighter and faster asynchronous library than tokio-rs, async-std, may, and even smol.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! This module provides an asynchronous `read-write lock` (e.g. [`std::sync::RwLock`])
//! type [`LocalRWLock`].
//!
//! It allows for asynchronous read or write locking and unlocking, and provides
//! ownership-based locking through [`LocalReadLockGuard`] and [`LocalWriteLockGuard`].
use crate::get_task_from_context;
use crate::runtime::local_executor;
use crate::runtime::task::Task;
use crate::sync::{AsyncRWLock, AsyncReadLockGuard, AsyncWriteLockGuard, LockStatus};
use std::cell::UnsafeCell;
use std::future::Future;
use std::mem::ManuallyDrop;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::task::{Context, Poll};

// region guards

/// RAII structure used to release the shared read access of a lock when
/// dropped.
///
/// This structure is created by the [`LocalRWLock::read`](LocalRWLock::read)
/// and [`LocalRWLock::try_read`](LocalRWLock::try_read).
pub struct LocalReadLockGuard<'rw_lock, T: ?Sized> {
    local_rw_lock: &'rw_lock LocalRWLock<T>,
    // impl !Send
    no_send_marker: std::marker::PhantomData<*const ()>,
}

impl<'rw_lock, T: ?Sized> LocalReadLockGuard<'rw_lock, T> {
    /// Creates a new `LocalReadLockGuard`.
    #[inline(always)]
    fn new(local_rw_lock: &'rw_lock LocalRWLock<T>) -> Self {
        Self {
            local_rw_lock,
            no_send_marker: std::marker::PhantomData,
        }
    }
}

impl<'rw_lock, T: ?Sized> AsyncReadLockGuard<'rw_lock, T> for LocalReadLockGuard<'rw_lock, T> {
    type RWLock = LocalRWLock<T>;

    fn rw_lock(&self) -> &'rw_lock Self::RWLock {
        self.local_rw_lock
    }

    #[inline(always)]
    unsafe fn leak(self) -> &'rw_lock Self::RWLock {
        ManuallyDrop::new(self).local_rw_lock
    }
}

impl<T: ?Sized> Deref for LocalReadLockGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.local_rw_lock.get_inner().value
    }
}

impl<T: ?Sized> Drop for LocalReadLockGuard<'_, T> {
    fn drop(&mut self) {
        unsafe {
            self.local_rw_lock.read_unlock();
        }
    }
}

/// RAII structure used to release the exclusive write access of a lock when
/// dropped.
///
/// This structure is created by the [`LocalRWLock::write`](LocalRWLock::write)
/// and [`LocalRWLock::try_write`](LocalRWLock::try_write).
pub struct LocalWriteLockGuard<'rw_lock, T: ?Sized> {
    local_rw_lock: &'rw_lock LocalRWLock<T>,
    // impl !Send
    no_send_marker: std::marker::PhantomData<*const ()>,
}

impl<'rw_lock, T: ?Sized> LocalWriteLockGuard<'rw_lock, T> {
    /// Creates a new `LocalWriteLockGuard`.
    #[inline(always)]
    fn new(local_rw_lock: &'rw_lock LocalRWLock<T>) -> Self {
        Self {
            local_rw_lock,
            no_send_marker: std::marker::PhantomData,
        }
    }
}

impl<'rw_lock, T: ?Sized> AsyncWriteLockGuard<'rw_lock, T> for LocalWriteLockGuard<'rw_lock, T> {
    type RWLock = LocalRWLock<T>;

    fn rw_lock(&self) -> &'rw_lock Self::RWLock {
        self.local_rw_lock
    }

    #[inline(always)]
    unsafe fn leak(self) -> &'rw_lock Self::RWLock {
        ManuallyDrop::new(self).local_rw_lock
    }
}

impl<T: ?Sized> Deref for LocalWriteLockGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.local_rw_lock.get_inner().value
    }
}

impl<T: ?Sized> DerefMut for LocalWriteLockGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.local_rw_lock.get_inner().value
    }
}

impl<T: ?Sized> Drop for LocalWriteLockGuard<'_, T> {
    fn drop(&mut self) {
        unsafe {
            self.local_rw_lock.write_unlock();
        }
    }
}

// endregion

// region futures

/// `ReadLockWait` is a future that will be resolved when the read lock is acquired.
pub struct ReadLockWait<'rw_lock, T: ?Sized> {
    was_called: bool,
    local_rw_lock: &'rw_lock LocalRWLock<T>,
    // impl !Send
    no_send_marker: std::marker::PhantomData<*const ()>,
}

impl<'rw_lock, T: ?Sized> ReadLockWait<'rw_lock, T> {
    /// Creates a new `ReadLockWait`.
    #[inline(always)]
    fn new(local_rw_lock: &'rw_lock LocalRWLock<T>) -> Self {
        Self {
            was_called: false,
            local_rw_lock,
            no_send_marker: std::marker::PhantomData,
        }
    }
}

impl<'rw_lock, T: ?Sized> Future for ReadLockWait<'rw_lock, T> {
    type Output = LocalReadLockGuard<'rw_lock, T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        if !this.was_called {
            let task = unsafe { get_task_from_context!(cx) };
            this.local_rw_lock.get_inner().wait_queue_read.push(task);
            this.was_called = true;
            return Poll::Pending;
        }

        Poll::Ready(LocalReadLockGuard::new(this.local_rw_lock))
    }
}

/// `WriteLockWait` is a future that will be resolved when the write lock is acquired.
pub struct WriteLockWait<'rw_lock, T: ?Sized> {
    was_called: bool,
    local_rw_lock: &'rw_lock LocalRWLock<T>,
    // impl !Send
    no_send_marker: std::marker::PhantomData<*const ()>,
}

impl<'rw_lock, T: ?Sized> WriteLockWait<'rw_lock, T> {
    /// Creates a new `WriteLockWait`.
    #[inline(always)]
    fn new(local_rw_lock: &'rw_lock LocalRWLock<T>) -> Self {
        Self {
            was_called: false,
            local_rw_lock,
            no_send_marker: std::marker::PhantomData,
        }
    }
}

impl<'rw_lock, T: ?Sized> Future for WriteLockWait<'rw_lock, T> {
    type Output = LocalWriteLockGuard<'rw_lock, T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        if !this.was_called {
            let task = unsafe { get_task_from_context!(cx) };
            this.local_rw_lock.get_inner().wait_queue_write.push(task);
            this.was_called = true;
            return Poll::Pending;
        }

        Poll::Ready(LocalWriteLockGuard::new(this.local_rw_lock))
    }
}

// endregion

/// Inner structure of [`LocalRWLock`] for internal use via [`UnsafeCell`].
struct Inner<T: ?Sized> {
    wait_queue_read: Vec<Task>,
    wait_queue_write: Vec<Task>,
    number_of_readers: isize,
    value: T,
}

/// An asynchronous version of a [`reader-writer lock`](std::sync::RwLock)
///
/// This type of lock allows a number of readers or at most one writer at any
/// point in time. The write portion of this lock typically allows modification
/// of the underlying data (exclusive access) and the read portion of this lock
/// typically allows for read-only access (shared access).
///
/// In comparison, a [`LocalMutex`](crate::sync::LocalMutex)
/// does not distinguish between readers or writers
/// that acquire the lock, therefore blocking any tasks waiting for the lock to
/// become available. An `RWLock` will allow any number of readers to acquire the
/// lock as long as a writer is not holding the lock.
///
/// The type parameter `T` represents the data that this lock protects. It is
/// required that `T` satisfies [`Sync`] to allow concurrent access through readers. The RAII guards
/// returned from the locking methods implement [`Deref`] (and [`DerefMut`]
/// for the `write` methods) to allow access to the content of the lock.
///
/// # The difference between `LocalRWLock` and [`RWLock`](crate::sync::RWLock)
///
/// The `LocalRWLock` works with `local tasks`.
///
/// Read [`Executor`](crate::Executor) for more details.
///
///
/// # Incorrect usage
///
/// ```rust
/// use orengine::sync::{AsyncRWLock, LocalRWLock};
///
/// // Incorrect usage, because in local runtime all tasks are executed sequentially.
/// async fn inc_counter(counter: &LocalRWLock<u32>) {
///     let mut guard = counter.write().await;
///     *guard += 1;
/// }
/// ```
///
/// Use [`Local`](crate::Local) instead.
///
/// ```rust
/// use orengine::Local;
///
/// // Correct usage, because in local runtime all tasks are executed sequentially.
/// async fn inc_counter(counter: Local<u32>) {
///     *counter.borrow_mut() += 1;
/// }
/// ```
///
/// # Example with correct usage
///
/// ```rust
/// use std::collections::HashMap;
/// use std::rc::Rc;
/// use orengine::sync::{AsyncRWLock, LocalRWLock};
///
/// # async fn write_to_the_dump_file(key: usize, value: usize) {}
///
/// // Correct usage, because after `write_to_log_file(*key, *value).await` and before the future is resolved
/// // another task can modify the storage. So, we need to lock the storage.
/// async fn dump_storage(storage: Rc<LocalRWLock<HashMap<usize, usize>>>) {
///     let mut read_guard = storage.read().await;
///     
///     for (key, value) in read_guard.iter() {
///         write_to_the_dump_file(*key, *value).await;
///     }
///
///     // read lock is released when `guard` goes out of scope
/// }
/// ```
pub struct LocalRWLock<T: ?Sized> {
    // impl !Send
    no_send_marker: std::marker::PhantomData<*const ()>,
    inner: UnsafeCell<Inner<T>>,
}

impl<T: ?Sized> LocalRWLock<T> {
    /// Creates a new `LocalRWLock`.
    #[inline(always)]
    pub const fn new(value: T) -> Self
    where
        T: Sized,
    {
        Self {
            inner: UnsafeCell::new(Inner {
                wait_queue_read: Vec::new(),
                wait_queue_write: Vec::new(),
                number_of_readers: 0,
                value,
            }),
            no_send_marker: std::marker::PhantomData,
        }
    }

    /// Returns a mutable reference to the inner value.
    #[inline(always)]
    #[allow(clippy::mut_from_ref, reason = "It is Sync and `local`")]
    fn get_inner(&self) -> &mut Inner<T> {
        unsafe { &mut *self.inner.get() }
    }
}

impl<T: ?Sized> AsyncRWLock<T> for LocalRWLock<T> {
    type ReadLockGuard<'rw_lock>
        = LocalReadLockGuard<'rw_lock, T>
    where
        T: 'rw_lock,
        Self: 'rw_lock;
    type WriteLockGuard<'rw_lock>
        = LocalWriteLockGuard<'rw_lock, T>
    where
        T: 'rw_lock,
        Self: 'rw_lock;

    #[inline(always)]
    fn get_lock_status(&self) -> LockStatus {
        #[allow(clippy::cast_sign_loss, reason = "false positive")]
        match self.get_inner().number_of_readers {
            0 => LockStatus::Unlocked,
            n if n > 0 => LockStatus::ReadLocked(n as usize),
            _ => LockStatus::WriteLocked,
        }
    }

    #[inline(always)]
    #[allow(clippy::future_not_send, reason = "Because it is `local`")]
    async fn write<'rw_lock>(&'rw_lock self) -> Self::WriteLockGuard<'rw_lock>
    where
        T: 'rw_lock,
    {
        let inner = self.get_inner();

        if inner.number_of_readers == 0 {
            debug_assert!(inner.wait_queue_read.is_empty());

            inner.number_of_readers = -1;
            return LocalWriteLockGuard::new(self);
        }

        WriteLockWait::new(self).await
    }

    #[inline(always)]
    #[allow(clippy::future_not_send, reason = "Because it is `local`")]
    async fn read<'rw_lock>(&'rw_lock self) -> Self::ReadLockGuard<'rw_lock>
    where
        T: 'rw_lock,
    {
        let inner = self.get_inner();

        if inner.number_of_readers > -1 {
            inner.number_of_readers += 1;
            return LocalReadLockGuard::new(self);
        }

        ReadLockWait::new(self).await
    }

    #[inline(always)]
    fn try_write(&self) -> Option<Self::WriteLockGuard<'_>> {
        let inner = self.get_inner();

        if inner.number_of_readers == 0 {
            debug_assert!(inner.wait_queue_read.is_empty());

            inner.number_of_readers = -1;
            Some(LocalWriteLockGuard::new(self))
        } else {
            None
        }
    }

    #[inline(always)]
    fn try_read(&self) -> Option<Self::ReadLockGuard<'_>> {
        let inner = self.get_inner();
        if inner.number_of_readers > -1 {
            inner.number_of_readers += 1;
            Some(LocalReadLockGuard::new(self))
        } else {
            None
        }
    }

    #[inline(always)]
    fn get_mut(&mut self) -> &mut T {
        &mut self.inner.get_mut().value
    }

    #[inline(always)]
    unsafe fn read_unlock(&self) {
        if cfg!(debug_assertions) {
            assert_ne!(
                self.get_inner().number_of_readers,
                -1,
                "LocalRWLock is locked for write"
            );

            assert_ne!(
                self.get_inner().number_of_readers,
                0,
                "LocalRWLock is already unlocked"
            );
        }

        let inner = self.get_inner();
        inner.number_of_readers -= 1;

        if inner.number_of_readers == 0 {
            debug_assert!(inner.wait_queue_read.is_empty());
            let task = inner.wait_queue_write.pop();
            if task.is_some() {
                inner.number_of_readers = -1;
                local_executor().exec_task(unsafe { task.unwrap_unchecked() });
            }
        }
    }

    #[inline(always)]
    unsafe fn write_unlock(&self) {
        if cfg!(debug_assertions) {
            assert_ne!(
                self.get_inner().number_of_readers,
                0,
                "LocalRWLock is already unlocked"
            );

            assert!(
                self.get_inner().number_of_readers <= 0,
                "LocalRWLock is locked for read"
            );
        }

        let inner = self.get_inner();

        let task = inner.wait_queue_write.pop();
        if task.is_none() {
            let mut readers_count = inner.wait_queue_read.len();

            #[allow(clippy::cast_possible_wrap, reason = "false positive")]
            {
                inner.number_of_readers = readers_count as isize;
            }

            while readers_count > 0 {
                let task = inner.wait_queue_read.pop();
                local_executor().exec_task(unsafe { task.unwrap_unchecked() });
                readers_count -= 1;
            }
        } else {
            local_executor().exec_task(unsafe { task.unwrap_unchecked() });
        }
    }

    #[inline(always)]
    unsafe fn get_read_locked(&self) -> Self::ReadLockGuard<'_> {
        if cfg!(debug_assertions) {
            assert_ne!(
                self.get_inner().number_of_readers,
                -1,
                "LocalRWLock is locked for write"
            );

            assert_ne!(
                self.get_inner().number_of_readers,
                0,
                "LocalRWLock is unlocked"
            );
        }

        LocalReadLockGuard::new(self)
    }

    #[inline(always)]
    unsafe fn get_write_locked(&self) -> Self::WriteLockGuard<'_> {
        if cfg!(debug_assertions) {
            assert_ne!(
                self.get_inner().number_of_readers,
                0,
                "LocalRWLock is unlocked, but get_write_locked is called"
            );

            assert!(
                self.get_inner().number_of_readers <= 0,
                "LocalRWLock is locked for read"
            );
        }

        LocalWriteLockGuard::new(self)
    }
}

unsafe impl<T: ?Sized + Sync> Sync for LocalRWLock<T> {}

/// ```compile_fail
/// use orengine::sync::{LocalRWLock, AsyncRWLock};
/// use orengine::yield_now;
///
/// fn check_send<T: Send>(value: T) -> T { value }
///
/// async fn test() {
///     let mutex = LocalRWLock::new(0);
///
///     let guard = check_send(mutex.read()).await;
///     yield_now().await;
///     assert_eq!(*guard, 0);
///     drop(guard);
/// }
/// ```
///
/// ```compile_fail
/// use orengine::sync::{LocalRWLock, AsyncRWLock};
/// use orengine::yield_now;
///
/// fn check_send<T: Send>(value: T) -> T { value }
///
/// async fn test() {
///     let mutex = LocalRWLock::new(0);
///
///     let guard = check_send(mutex.write()).await;
///     yield_now().await;
///     assert_eq!(*guard, 0);
///     drop(guard);
/// }
/// ```
#[allow(dead_code, reason = "It is used only in compile tests")]
fn test_compile_local_rw_lock() {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as orengine;
    use crate::sync::{AsyncWaitGroup, LocalWaitGroup};
    use crate::yield_now;
    use std::rc::Rc;

    #[orengine::test::test_local]
    fn test_local_rw_lock() {
        let rw_lock = Rc::new(LocalRWLock::new(0));
        let wg = Rc::new(LocalWaitGroup::new());
        let read_wg = Rc::new(LocalWaitGroup::new());

        for i in 1..=15 {
            let mutex = rw_lock.clone();
            local_executor().exec_local_future(async move {
                let value = mutex.read().await;
                assert_eq!(mutex.get_inner().number_of_readers, i);
                assert_eq!(*value, 0);
                yield_now().await;
                assert_eq!(mutex.get_inner().number_of_readers, 16 - i);
                assert_eq!(*value, 0);
            });
        }

        for _ in 1..=15 {
            let wg = wg.clone();
            let read_wg = read_wg.clone();
            wg.add(1);
            let mutex = rw_lock.clone();
            local_executor().exec_local_future(async move {
                assert_eq!(mutex.get_inner().number_of_readers, 15);
                let mut value = mutex.write().await;
                {
                    let read_wg = read_wg.clone();
                    let mutex = mutex.clone();
                    read_wg.add(1);

                    local_executor().exec_local_future(async move {
                        assert_eq!(mutex.get_inner().number_of_readers, -1);
                        let value = mutex.read().await;
                        assert_ne!(*value, 0);
                        assert_ne!(mutex.get_inner().number_of_readers, 0);
                        read_wg.done();
                    });
                }

                assert_eq!(mutex.get_inner().number_of_readers, -1);
                *value += 1;

                wg.done();
            });
        }

        wg.wait().await;
        read_wg.wait().await;

        let value = rw_lock.read().await;
        assert_eq!(*value, 15);
        assert_ne!(rw_lock.get_inner().number_of_readers, 0);
    }

    #[orengine::test::test_local]
    fn test_try_local_rw_lock() {
        const NUMBER_OF_READERS: isize = 5;
        let rw_lock = Rc::new(LocalRWLock::new(0));

        for i in 1..=NUMBER_OF_READERS {
            let mutex = rw_lock.clone();
            local_executor().exec_local_future(async move {
                let lock = mutex.try_read().expect("Failed to get read lock!");
                assert_eq!(mutex.get_inner().number_of_readers, i);
                yield_now().await;
                drop(lock);
            });
        }

        assert_eq!(rw_lock.get_inner().number_of_readers, NUMBER_OF_READERS);
        assert!(
            rw_lock.try_write().is_none(),
            "Successful attempt to acquire write lock when rw_lock locked for read"
        );

        yield_now().await;

        assert_eq!(rw_lock.get_inner().number_of_readers, 0);
        let mut write_lock = rw_lock.try_write().expect("Failed to get write lock!");
        *write_lock += 1;
        assert_eq!(*write_lock, 1);

        assert_eq!(rw_lock.get_inner().number_of_readers, -1);
        assert!(
            rw_lock.try_read().is_none(),
            "Successful attempt to acquire read lock when rw_lock locked for write"
        );
        assert!(
            rw_lock.try_write().is_none(),
            "Successful attempt to acquire write lock when rw_lock locked for write"
        );
    }
}