saa 3.3.0

Low-level synchronization primitives providing both asynchronous and synchronous interfaces.
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! [`Gate`] is a synchronization primitive that blocks tasks from entering a critical section until
//! they are allowed to do so.

#![deny(unsafe_code)]

use std::marker::PhantomData;
use std::pin::Pin;
#[cfg(not(feature = "loom"))]
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed};
use std::task::{Context, Poll};

#[cfg(feature = "loom")]
use loom::sync::atomic::AtomicUsize;

use crate::opcode::Opcode;
use crate::sync_primitive::SyncPrimitive;
use crate::wait_queue::WaitQueue;

/// [`Gate`] is a synchronization primitive that blocks tasks from entering a critical section until
/// they are allowed to do so.
#[derive(Debug, Default)]
pub struct Gate {
    /// [`Gate`] state.
    state: AtomicUsize,
}

/// Tasks holding a [`Pager`] can remotely get a permit to enter the [`Gate`].
#[derive(Debug, Default)]
pub struct Pager<'g> {
    /// The [`Gate`] that the [`Pager`] is registered in and the wait queue entry for the [`Pager`].
    entry: Option<WaitQueue>,
    /// The [`Pager`] cannot outlive the [`Gate`] it is registered in.
    _phantom: PhantomData<&'g Gate>,
}

/// The state of a [`Gate`].
///
/// [`Gate`] can be in one of three states.
///
/// * `Controlled` - The default state where tasks can enter the [`Gate`] if permitted.
/// * `Sealed` - The [`Gate`] is sealed and tasks immediately get rejected when attempting to enter.
/// * `Open` - The [`Gate`] is open and tasks can immediately enter it.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum State {
    /// The default state where tasks can enter the [`Gate`] if permitted.
    Controlled = 0_u8,
    /// The [`Gate`] is sealed and tasks immediately get rejected when they attempt to enter it.
    Sealed = 1_u8,
    /// The [`Gate`] is open and tasks can immediately enter it.
    Open = 2_u8,
}

/// Errors raised when accessing a [`Gate`].
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum Error {
    /// The [`Gate`] rejected the task.
    Rejected = 4_u8,
    /// The [`Gate`] has been sealed.
    Sealed = 8_u8,
    /// Spurious failure to enter a [`Gate`] in a [`Controlled`](State::Controlled) state.
    ///
    /// This can happen if a task holding a [`Pager`] gets cancelled or drops the [`Pager`] before
    /// the [`Gate`] has permitted or rejected the task; the task causes all the other waiting tasks
    /// of the [`Gate`] to get this error.
    SpuriousFailure = 12_u8,
    /// The [`Pager`] is not registered in any [`Gate`].
    NotRegistered = 16_u8,
    /// The wrong asynchronous/synchronous mode was used in a [`Pager`].
    WrongMode = 20_u8,
    /// The result is not ready.
    NotReady = 24_u8,
}

impl Gate {
    /// Mask to get the state value from `u8`.
    const STATE_MASK: u8 = 0b11;

    /// Returns the current state of the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// assert_eq!(gate.state(Relaxed), State::Controlled);
    /// ```
    #[inline]
    pub fn state(&self, mo: Ordering) -> State {
        State::from(self.state.load(mo) & WaitQueue::DATA_MASK)
    }

    /// Resets the [`Gate`] to its initial state if it is not in a [`Controlled`](State::Controlled)
    /// state.
    ///
    /// Returns the previous state of the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// assert_eq!(gate.reset(), None);
    ///
    /// gate.seal();
    ///
    /// assert_eq!(gate.reset(), Some(State::Sealed));
    /// ```
    #[inline]
    pub fn reset(&self) -> Option<State> {
        match self.state.fetch_update(Relaxed, Relaxed, |value| {
            let state = State::from(value & WaitQueue::DATA_MASK);
            if state == State::Controlled {
                None
            } else {
                debug_assert_eq!(value & WaitQueue::ADDR_MASK, 0);
                Some((value & WaitQueue::ADDR_MASK) | u8::from(state) as usize)
            }
        }) {
            Ok(state) => Some(State::from(state & WaitQueue::DATA_MASK)),
            Err(_) => None,
        }
    }

    /// Permits waiting tasks to enter the [`Gate`] if the [`Gate`] is in a
    /// [`Controlled`](State::Controlled) state.
    ///
    /// Returns the number of permitted tasks.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the [`Gate`] is not in a [`Controlled`](State::Controlled) state.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    ///
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// loop {
    ///     if gate.permit() == Ok(1) {
    ///         break;
    ///     }
    /// }
    ///
    /// thread.join().unwrap();
    /// ```
    #[inline]
    pub fn permit(&self) -> Result<usize, State> {
        let (state, count) = self.wake_all(None, None);
        if state == State::Controlled {
            Ok(count)
        } else {
            debug_assert_eq!(count, 0);
            Err(state)
        }
    }

    /// Rejects waiting tasks to enter the [`Gate`] if the [`Gate`] is in a
    /// [`Controlled`](State::Controlled) state.
    ///
    /// Returns the number of rejected tasks.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the [`Gate`] is not in a [`Controlled`](State::Controlled) state.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::Error;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    ///
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Err(Error::Rejected));
    /// });
    ///
    /// loop {
    ///     if gate.reject() == Ok(1) {
    ///         break;
    ///     }
    /// }
    ///
    /// thread.join().unwrap();
    /// ```
    #[inline]
    pub fn reject(&self) -> Result<usize, State> {
        let (state, count) = self.wake_all(None, Some(Error::Rejected));
        if state == State::Controlled {
            Ok(count)
        } else {
            debug_assert_eq!(count, 0);
            Err(state)
        }
    }

    /// Opens the [`Gate`] to allow any tasks to enter it.
    ///
    /// Returns the number of tasks that were waiting to enter it.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    /// assert_eq!(gate.state(Relaxed), State::Controlled);
    ///
    /// let (prev_state, count) = gate.open();
    ///
    /// assert_eq!(prev_state, State::Controlled);
    /// assert_eq!(count, 0);
    /// assert_eq!(gate.state(Relaxed), State::Open);
    /// ```
    #[inline]
    pub fn open(&self) -> (State, usize) {
        self.wake_all(Some(State::Open), None)
    }

    /// Seals the [`Gate`] to disallow tasks to enter.
    ///
    /// Returns the previous state of the [`Gate`] and the number of tasks that were waiting to
    /// enter the gate.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// let (prev_state, count) = gate.seal();
    ///
    /// assert_eq!(prev_state, State::Controlled);
    /// assert_eq!(count, 0);
    /// assert_eq!(gate.state(Relaxed), State::Sealed);
    /// ```
    #[inline]
    pub fn seal(&self) -> (State, usize) {
        self.wake_all(Some(State::Sealed), Some(Error::Sealed))
    }

    /// Enters the [`Gate`] asynchronously.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future;
    /// use saa::Gate;
    ///
    /// let gate = Gate::default();
    ///
    /// let a = async {
    ///     assert!(gate.enter_async().await.is_ok());
    /// };
    /// let b = async {
    ///     gate.permit();
    /// };
    /// future::join(a, b);
    /// ```
    #[inline]
    pub async fn enter_async(&self) -> Result<State, Error> {
        let mut pager = Pager::default();
        pager
            .entry
            .replace(WaitQueue::new_async(Opcode::Wait, Self::noop, self.addr()));
        let mut pinned_pager = Pin::new(&mut pager);
        self.push_wait_queue_entry(&mut pinned_pager, || {});
        pinned_pager.await
    }

    /// Enters the [`Gate`] asynchronously with a wait callback provided.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future;
    /// use saa::Gate;
    ///
    /// let gate = Gate::default();
    ///
    /// let a = async {
    ///     let mut wait = false;
    ///     assert!(gate.enter_async_with(|| wait = true).await.is_ok());
    /// };
    /// let b = async {
    ///    gate.permit();
    /// };
    /// future::join(a, b);
    /// ```
    #[inline]
    pub async fn enter_async_with<F: FnOnce()>(&self, wait_callback: F) -> Result<State, Error> {
        let mut pager = Pager::default();
        pager
            .entry
            .replace(WaitQueue::new_async(Opcode::Wait, Self::noop, self.addr()));
        let mut pinned_pager = Pin::new(&mut pager);
        self.push_wait_queue_entry(&mut pinned_pager, wait_callback);
        pinned_pager.await
    }

    /// Enters the [`Gate`] synchronously.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    /// let thread_1 = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// let gate_clone = gate.clone();
    /// let thread_2 = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// let mut cnt = 0;
    /// while cnt != 2 {
    ///     if let Ok(n) = gate.permit() {
    ///         cnt += n;
    ///     }
    /// }
    ///
    /// thread_1.join().unwrap();
    /// thread_2.join().unwrap();
    /// ```
    #[inline]
    pub fn enter_sync(&self) -> Result<State, Error> {
        self.enter_sync_with(|| ())
    }

    /// Enters the [`Gate`] synchronously with a wait callback provided.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    /// let thread_1 = thread::spawn(move || {
    ///     let mut wait = false;
    ///     assert_eq!(gate_clone.enter_sync_with(|| wait = true), Ok(State::Controlled));
    /// });
    ///
    /// let gate_clone = gate.clone();
    /// let thread_2 = thread::spawn(move || {
    ///     let mut wait = false;
    ///     assert_eq!(gate_clone.enter_sync_with(|| wait = true), Ok(State::Controlled));
    /// });
    ///
    /// let mut cnt = 0;
    /// while cnt != 2 {
    ///     if let Ok(n) = gate.permit() {
    ///         cnt += n;
    ///     }
    /// }
    ///
    /// thread_1.join().unwrap();
    /// thread_2.join().unwrap();
    /// ```
    #[inline]
    pub fn enter_sync_with<F: FnOnce()>(&self, wait_callback: F) -> Result<State, Error> {
        let mut pager = Pager::default();
        pager
            .entry
            .replace(WaitQueue::new_sync(Opcode::Wait, self.addr()));
        let mut pinned_pager = Pin::new(&mut pager);
        self.push_wait_queue_entry(&mut pinned_pager, wait_callback);
        pinned_pager.poll_sync()
    }

    /// Registers a [`Pager`] to allow it to get a permit to enter the [`Gate`] remotely.
    ///
    /// Returns `false` if the [`Pager`] was already registered.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Error, Pager, State};
    ///
    /// let gate = Gate::default();
    ///
    /// let mut pager = Pager::default();
    /// let mut pinned_pager = Pin::new(&mut pager);
    ///
    /// assert!(gate.register_async(&mut pinned_pager));
    ///
    /// assert_eq!(gate.open().1, 1);
    ///
    /// assert_eq!(pinned_pager.poll_sync(), Err(Error::WrongMode));
    ///
    /// async {
    ///     assert_eq!(pinned_pager.await, Ok(State::Open));
    /// };
    /// ```
    #[inline]
    pub fn register_async<'g>(&'g self, pager: &mut Pin<&mut Pager<'g>>) -> bool {
        if pager.entry.is_some() {
            return false;
        }
        pager
            .entry
            .replace(WaitQueue::new_async(Opcode::Wait, Self::noop, self.addr()));
        self.push_wait_queue_entry(pager, || ());
        true
    }

    /// Registers a [`Pager`] to allow it get a permit to enter the [`Gate`] remotely.
    ///
    /// Returns `false` if the [`Pager`] was already registered.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Pager, State};
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let mut pager = Pager::default();
    /// let mut pinned_pager = Pin::new(&mut pager);
    ///
    /// assert!(gate.register_sync(&mut pinned_pager));
    /// assert!(!gate.register_sync(&mut pinned_pager));
    ///
    /// let gate_clone = gate.clone();
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.permit(), Ok(1));
    /// });
    ///
    /// thread.join().unwrap();
    ///
    /// assert_eq!(pinned_pager.poll_sync(), Ok(State::Controlled));
    /// ```
    #[inline]
    pub fn register_sync<'g>(&'g self, pager: &mut Pin<&mut Pager<'g>>) -> bool {
        if pager.entry.is_some() {
            return false;
        }
        pager
            .entry
            .replace(WaitQueue::new_sync(Opcode::Wait, self.addr()));
        self.push_wait_queue_entry(pager, || ());
        true
    }

    /// Wakes up all the waiting tasks and updates the state.
    ///
    /// Returns `(prev_state, count)` where `prev_state` is the previous state of the gate and
    /// `count` is the number of tasks that were woken up.
    fn wake_all(&self, next_state: Option<State>, error: Option<Error>) -> (State, usize) {
        match self.state.fetch_update(AcqRel, Acquire, |value| {
            if let Some(new_value) = next_state {
                Some(u8::from(new_value) as usize)
            } else {
                Some(value & WaitQueue::DATA_MASK)
            }
        }) {
            Ok(value) | Err(value) => {
                let mut count = 0;
                let entry_addr = value & WaitQueue::ADDR_MASK;
                let prev_state = State::from(value & WaitQueue::DATA_MASK);
                let next_state = next_state.unwrap_or(prev_state);
                let result = Self::into_u8(next_state, error);
                if entry_addr != 0 {
                    WaitQueue::iter_forward(
                        WaitQueue::addr_to_ptr(entry_addr),
                        false,
                        |entry, _| {
                            entry.set_result(result);
                            count += 1;
                            false
                        },
                    );
                }
                (prev_state, count)
            }
        }
    }

    /// Pushes the wait queue entry.
    #[inline]
    fn push_wait_queue_entry<F: FnOnce()>(
        &self,
        entry: &mut Pin<&mut Pager>,
        mut wait_callback: F,
    ) {
        if let Some(entry) = entry.entry.as_ref() {
            let pinned_entry = Pin::new(entry);
            loop {
                let state = self.state.load(Acquire);
                match State::from(state & WaitQueue::DATA_MASK) {
                    State::Controlled => {
                        if let Some(returned) =
                            self.try_push_wait_queue_entry(pinned_entry, state, wait_callback)
                        {
                            wait_callback = returned;
                            continue;
                        }
                    }
                    State::Sealed => {
                        entry.set_result(Self::into_u8(State::Sealed, Some(Error::Sealed)));
                    }
                    State::Open => {
                        entry.set_result(Self::into_u8(State::Open, None));
                    }
                }
                break;
            }
        }
    }

    /// Noop function.
    #[inline]
    fn noop(_entry: &WaitQueue) {
        unreachable!("Noop function called");
    }

    /// Converts `(State, Error)` into `u8`.
    #[inline]
    fn into_u8(state: State, error: Option<Error>) -> u8 {
        u8::from(state) | error.map_or(0_u8, u8::from)
    }

    /// Converts `(State, Error)` into `u8`.
    #[inline]
    fn from_u8(value: u8) -> (State, Option<Error>) {
        let state = State::from(value & Self::STATE_MASK);
        let error = value & !(Self::STATE_MASK);
        if error != 0 {
            (state, Some(Error::from(error)))
        } else {
            (state, None)
        }
    }
}

impl Drop for Gate {
    #[inline]
    fn drop(&mut self) {
        if self.state.load(Relaxed) & WaitQueue::ADDR_MASK == 0 {
            return;
        }
        self.seal();
    }
}

impl SyncPrimitive for Gate {
    #[inline]
    fn state(&self) -> &AtomicUsize {
        &self.state
    }

    #[inline]
    fn max_shared_owners() -> usize {
        usize::MAX
    }
}

impl<'g> Pager<'g> {
    /// Returns `true` if the [`Pager`] is registered in a [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Pager, State};
    ///
    /// let gate = Gate::default();
    ///
    /// let mut pager = Pager::default();
    ///
    ///
    /// let mut pinned_pager = Pin::new(&mut pager);
    /// assert!(!pinned_pager.is_registered());
    ///
    /// assert!(gate.register_sync(&mut pinned_pager));
    /// assert!(pinned_pager.is_registered());
    ///
    /// assert_eq!(gate.open().1, 1);
    /// ```
    #[inline]
    pub fn is_registered(&self) -> bool {
        self.entry.is_some()
    }

    /// Returns `true` if the [`Pager`] can only be polled synchronously.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Pager, State};
    ///
    /// let gate = Gate::default();
    ///
    /// let mut pager = Pager::default();
    /// let mut pinned_pager = Pin::new(&mut pager);
    ///
    /// assert!(gate.register_sync(&mut pinned_pager));
    /// assert!(pinned_pager.is_sync());
    ///
    /// assert_eq!(gate.open().1, 1);
    ///
    /// assert_eq!(pinned_pager.poll_sync(), Ok(State::Open));
    /// assert!(!pinned_pager.is_sync());
    /// ```
    #[inline]
    pub fn is_sync(&self) -> bool {
        self.entry.as_ref().is_some_and(WaitQueue::is_sync)
    }

    /// Waits for a permit to enter the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Pager, State};
    ///
    /// let gate = Gate::default();
    ///
    /// let mut pager = Pager::default();
    /// let mut pinned_pager = Pin::new(&mut pager);
    ///
    /// assert!(gate.register_sync(&mut pinned_pager));
    ///
    /// assert_eq!(gate.open().1, 1);
    ///
    /// assert_eq!(pinned_pager.poll_sync(), Ok(State::Open));
    /// ```
    #[inline]
    pub fn poll_sync(self: &mut Pin<&mut Pager<'g>>) -> Result<State, Error> {
        let Some(entry) = self.entry.as_ref() else {
            // The `Pager` is not registered in any `Gate`.
            return Err(Error::NotRegistered);
        };
        let result = entry.poll_result_sync();
        if result == WaitQueue::ERROR_WRONG_MODE {
            return Err(Error::WrongMode);
        }
        self.entry.take();
        let (state, error) = Gate::from_u8(result);
        error.map_or(Ok(state), Err)
    }

    /// Tries to get the result.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`] or the result is not ready.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::Pin;
    ///
    /// use saa::Gate;
    /// use saa::gate::{Error, Pager, State};
    ///
    /// let gate = Gate::default();
    ///
    /// let mut pager = Pager::default();
    /// let mut pinned_pager = Pin::new(&mut pager);
    ///
    /// assert!(gate.register_sync(&mut pinned_pager));
    ///
    /// assert_eq!(pinned_pager.try_poll(), Err(Error::NotReady));
    /// assert_eq!(gate.open().1, 1);
    ///
    /// assert_eq!(pinned_pager.try_poll(), Ok(State::Open));
    /// assert_eq!(pinned_pager.poll_sync(), Ok(State::Open));
    /// ```
    #[inline]
    pub fn try_poll(&self) -> Result<State, Error> {
        let Some(entry) = self.entry.as_ref() else {
            // The `Pager` is not registered in any `Gate`.
            return Err(Error::NotRegistered);
        };

        if let Some(result) = entry.try_acknowledge_result() {
            let (state, error) = Gate::from_u8(result);
            error.map_or(Ok(state), Err)
        } else {
            Err(Error::NotReady)
        }
    }
}

impl Drop for Pager<'_> {
    #[inline]
    fn drop(&mut self) {
        let Some(entry) = self.entry.as_mut() else {
            return;
        };
        if entry.try_acknowledge_result().is_none() {
            let gate: &Gate = entry.sync_primitive_ref();
            gate.wake_all(None, Some(Error::SpuriousFailure));
            entry.acknowledge_result_sync();
        }
    }
}

impl Future for Pager<'_> {
    type Output = Result<State, Error>;

    #[inline]
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Some(entry) = self.entry.as_ref() else {
            // The `Pager` is not registered in any `Gate`.
            return Poll::Ready(Err(Error::NotRegistered));
        };
        if let Poll::Ready(result) = entry.poll_result_async(cx) {
            self.entry.take();
            if result == WaitQueue::ERROR_WRONG_MODE {
                return Poll::Ready(Err(Error::WrongMode));
            }
            let (state, error) = Gate::from_u8(result);
            return Poll::Ready(error.map_or(Ok(state), Err));
        }
        Poll::Pending
    }
}

impl From<State> for u8 {
    #[inline]
    fn from(value: State) -> Self {
        match value {
            State::Controlled => 0_u8,
            State::Sealed => 1_u8,
            State::Open => 2_u8,
        }
    }
}

impl From<u8> for State {
    #[inline]
    fn from(value: u8) -> Self {
        State::from(value as usize)
    }
}

impl From<usize> for State {
    #[inline]
    fn from(value: usize) -> Self {
        match value {
            0 => State::Controlled,
            1 => State::Sealed,
            _ => State::Open,
        }
    }
}

impl From<Error> for u8 {
    #[inline]
    fn from(value: Error) -> Self {
        match value {
            Error::Rejected => 4_u8,
            Error::Sealed => 8_u8,
            Error::SpuriousFailure => 12_u8,
            Error::NotRegistered => 16_u8,
            Error::WrongMode => 20_u8,
            Error::NotReady => 24_u8,
        }
    }
}

impl From<u8> for Error {
    #[inline]
    fn from(value: u8) -> Self {
        Error::from(value as usize)
    }
}

impl From<usize> for Error {
    #[inline]
    fn from(value: usize) -> Self {
        match value {
            4 => Error::Rejected,
            8 => Error::Sealed,
            12 => Error::SpuriousFailure,
            16 => Error::NotRegistered,
            20 => Error::WrongMode,
            _ => Error::NotReady,
        }
    }
}