global_cell 0.2.0

A thread-safe, async-friendly, performant global cell alternative built on Rust and Tokio primitives
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
use std::{
    cell::UnsafeCell, 
    hint::{likely, unlikely}, 
    mem::MaybeUninit, 
    panic::AssertUnwindSafe, 
    sync::{atomic::{AtomicBool, AtomicU8, Ordering}},
    future::Future
};
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard, Mutex};
use futures_util::future::FutureExt;
use crate::{traits::CellTrait, utils::yield_now};

/// A guard that resets the state of the RawCell if dropped before initialization completes.
/// 
/// Two key assumptions are made with this guard:
/// - The lock is only dropped if initialization fails or panics, in which case the destructor will be ran automatically.
///     - If initialization succeeds, the guard can be "forgotten", or the guard can be dropped before
///       initialization states are updated. For performance cells, the guard should be forgotten.
/// - The intended reset state for all failures is UNINIT, being 0.
#[repr(transparent)]
struct ResetOnDrop<'a> {
    state: &'a AtomicU8,
}
impl<'a> Drop for ResetOnDrop<'a> {
    fn drop(&mut self) {
        self.state.store(0, Ordering::Release);
    }
}

/// # RawCell
/// RawCell is a low-level primitive to offer performant access and interior mutability,
/// while being statically assignable and shareable across threads (send + sync).
/// 
/// RawCell is, by nature, unsafe; protection against race conditions is
/// undefined, providing unified write/read access to all threads that have access to it.
/// 
/// RawCell is async-aware and is tokio-compatible.
/// 
/// ## Performance
/// - AtomicU8: lock-free state management; fast
/// - UnsafeCell: zero-cost interior mutability; fast
/// - MaybeUninit: zero-cost uninitialized memory; fast
/// - RwLock: (parking lot) multiple concurrent readers, single writer; fast reads, moderate writes; SIGNIFICANT OVERHEAD
/// 
/// RwLock is the most significant performance bottleneck in RawCell. A potentially better alternative
/// if the cell will be used in mostly write-heavy contexts, a single-lock Mutex would be better.
/// 
/// ## Initialization
/// By default, the cell itself is not initialized; RawCell assumes a lazy implementation unless its
/// init field is explicitly called by the user at some point in time.
/// 
/// Even when initialized, the inner value is not necessarily guaranteed to be set; that is,
/// it may be "empty" or essentially set to None. In that case, reads/writes to the inner value
/// will return an Err.
#[repr(C, align(128))]
pub struct RawCell<T> {
    state: AtomicU8,
    value: UnsafeCell<MaybeUninit<RwLock<T>>>,
}

unsafe impl<T: Send> Send for RawCell<T> {}
unsafe impl<T: Sync> Sync for RawCell<T> {}

impl<T> RawCell<T> {
    const UNINIT: u8 = 0;
    const INITING: u8 = 1;
    const INITED: u8 = 2;

    const MAX_SPIN: u8 = 8;
}
impl<T: Send + Sync> const CellTrait<T> for RawCell<T> {
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
}
/// Require T: Send + Sync for concurrent access operations. Why?
/// - RwLock prefers T: Send + Sync to be Send + Sync itself.
/// - RawCell is designed for concurrent access; without Send + Sync, it would be
///   unsafe to share across threads.
/// - Enforcing Send + Sync at the type level prevents misuse and potential data races.
/// 
/// RawCell itself does not require T: Send + Sync, as the caller may
/// decide to manually implement uses for RawCell and require an auto-destructor, which is already implemented.
/// That's just not worth the hassle usually, so just use Send + Sync.
impl<T: Send + Sync> RawCell<T> {
    /// Creates a new, uninitialized RawCell.
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            state: AtomicU8::new(Self::UNINIT),
            value: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    /// Creates a new, initialized RawCell with the default value of T.
    /// RawCell will be initialized upon creation.
    #[inline(always)]
    pub fn default() -> Self
    where
        T: Default,
    {
        Self {
            state: AtomicU8::new(Self::INITED),
            value: UnsafeCell::new(MaybeUninit::new(RwLock::new(T::default()))),
        }
    }

    /// Creates a new, initialized RawCell with the provided value.
    /// RawCell will be initialized upon creation.
    #[inline(always)]
    pub const fn from(value: T) -> Self {
        Self {
            state: AtomicU8::new(Self::INITED),
            value: UnsafeCell::new(MaybeUninit::new(RwLock::new(value))),
        }
    }

    /// Checks if the RawCell has been initialized.
    #[inline(always)]
    pub fn is_initialized(&self) -> bool {
        self.state.load(Ordering::Acquire) == Self::INITED
    }

    /// Blocking init, optimized
    #[inline(always)]
    pub fn init<F>(&self, init_fn: F)
    where 
        F: FnOnce() -> T,
    {
        // Fast path: check if already initialized
        if likely(self.is_initialized()) {
            return;
        }

        let mut step = 0;
        loop {
            let state = self.state.load(Ordering::Acquire);

            match state {
                Self::INITED => return,
                Self::UNINIT => {
                    if self.state.compare_exchange(
                        Self::UNINIT,
                        Self::INITING,
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ).is_ok() {
                        // Safe to use ResetOnDrop: init_fn panics causes destructor,
                        // UNINIT state = 0, guard forgotten on success
                        let guard = ResetOnDrop { state: &self.state };
                        let value = init_fn();

                        // If init_fn panicked, the guard would have dropped and set the cell back to UNINIT;
                        // if we're here, init_fn succeeded.

                        unsafe {
                            (*self.value.get()).as_mut_ptr().write(RwLock::new(value));
                        }
                        std::mem::forget(guard);
                        self.state.store(Self::INITED, Ordering::Release);
                        return;
                    }
                }
                Self::INITING => {
                    if step > Self::MAX_SPIN {
                        std::thread::yield_now();
                    } else {
                        for _ in 0..(1 << step) {
                            std::hint::spin_loop();
                        }
                    }
                }
                _ => unsafe { std::hint::unreachable_unchecked() },
            }

            step += 1;
        }
    }

    /// Async init, optimized
    #[inline(always)]
    pub async fn init_async<F, Fut>(&self, init_fn: F)
    where 
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        // Fast path: check if already initialized
        if likely(self.is_initialized()) {
            return;
        }

        let mut step = 0;
        loop {
            let state = self.state.load(Ordering::Acquire);

            match state {
                Self::INITED => return,
                Self::UNINIT => {
                    if self.state.compare_exchange(
                        Self::UNINIT,
                        Self::INITING,
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ).is_ok() {
                        // Safe to use ResetOnDrop: init_fn panics causes destructor,
                        // UNINIT state = 0, guard forgotten on success
                        let guard = ResetOnDrop { state: &self.state };

                        // Here, instead of letting the future poll itself, we manually catch
                        // the unwind to ensure the guard is dropped correctly.
                        let value = AssertUnwindSafe(init_fn())
                            .catch_unwind()
                            .await;

                        if let Ok(value) = value {
                            unsafe {
                                (*self.value.get()).as_mut_ptr().write(RwLock::new(value));
                            }
                            std::mem::forget(guard);
                            self.state.store(Self::INITED, Ordering::Release);
                        } else {
                            std::panic::resume_unwind(value.err().unwrap());
                        }
                        return;
                    }
                }
                Self::INITING => {
                    if step > Self::MAX_SPIN {
                        yield_now().await;
                    } else {
                        for _ in 0..(1 << step) {
                            std::hint::spin_loop();
                        }
                    }
                }
                _ => unsafe { std::hint::unreachable_unchecked() },
            }

            step += 1;
        }
    }

    /// Fetches the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner(&self) -> &RwLock<T> {
        debug_assert!(self.is_initialized(), "RawCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { (*self.value.get()).assume_init_ref() }
    }

    /// Fetches the inner value mutably, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner_mut(&self) -> &mut RwLock<T> {
        debug_assert!(self.is_initialized(), "RawCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { (*self.value.get()).assume_init_mut() }
    }

    /// Fetches a read lock to the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn read(&self) -> RwLockReadGuard<'_, T> {
        debug_assert!(self.is_initialized(), "RawCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { (*self.value.get()).assume_init_ref().read() }
    }

    /// Fetches a write lock to the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn write(&self) -> RwLockWriteGuard<'_, T> {
        debug_assert!(self.is_initialized(), "RawCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { (*self.value.get()).assume_init_ref().write() }
    }
}
impl<T> Drop for RawCell<T> {
    fn drop(&mut self) {
        // We can't use Send + Sync related bounds here.
        // Automatically determine initialization and dropping.
        if self.state.load(Ordering::Acquire) == Self::INITED {
            unsafe {
                std::ptr::drop_in_place(
                    (*self.value.get()).assume_init_mut()
                )
            }
        }
    }
}

/// # RawMutexCell
/// RawMutexCell is a low-level primitive based on RawCell, but geared towards
/// write-heavy access patterns. Instead of RwLock, the Cell utilizes a Mutex internally
/// for unified read/write access.
/// 
/// Refer to RawCell documentation for more information.
/// 
/// This does come with downsides, that being:
/// - slower read access
/// - no concurrent access
/// - easier deadlocks
#[repr(C, align(128))]
pub struct RawMutexCell<T> {
    state: AtomicU8,
    value: UnsafeCell<MaybeUninit<Mutex<T>>>,
}
unsafe impl<T: Send> Send for RawMutexCell<T> {}
unsafe impl<T: Sync> Sync for RawMutexCell<T> {}
impl<T> const CellTrait<T> for RawMutexCell<T> {
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
}
/// RawMutexCell doesn't require T: Send + Sync at the type level, since all reads/writes
/// are parallel. For async initializations, RawMutexCell automatically uses a
/// `state` to determine whether it is safe to update the Mutex.
/// 
/// As for async/multiple access to the Mutex itself, the caller must prevent UB themselves;
/// optionally, T can implement Send + Sync.
impl<T> RawMutexCell<T> {
    const UNINIT: u8 = 0;
    const INITING: u8 = 1;
    const INITED: u8 = 2;

    // NOTE: MAX_SPIN must be less than 32 (for u32) or 64 (for u64)
    // safe: 8 < 32 < 64
    const MAX_SPIN: u8 = 8;

    /// Creates a new, uninitialized RawMutexCell.
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            state: AtomicU8::new(Self::UNINIT),
            value: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    /// Creates a new, initialized RawMutexCell with the default value of T.
    /// RawMutexCell will be initialized upon creation.
    #[inline(always)]
    pub fn default() -> Self
    where
        T: Default,
    {
        Self {
            state: AtomicU8::new(Self::INITED),
            value: UnsafeCell::new(MaybeUninit::new(Mutex::new(T::default()))),
        }
    }

    /// Creates a new, initialized RawMutexCell with the provided value.
    /// RawMutexCell will be initialized upon creation.
    #[inline(always)]
    pub const fn from(value: T) -> Self {
        Self {
            state: AtomicU8::new(Self::INITED),
            value: UnsafeCell::new(MaybeUninit::new(Mutex::new(value))),
        }
    }

    /// Checks if the RawMutexCell has been initialized.
    #[inline(always)]
    pub fn is_initialized(&self) -> bool {
        self.state.load(Ordering::Acquire) == Self::INITED
    }

    /// Blocking init, optimized
    #[inline(always)]
    pub fn init<F>(&self, init_fn: F)
    where
        F: FnOnce() -> T,
    {
        let mut step = 0;
        loop {
            match self.state.compare_exchange(
                Self::UNINIT,
                Self::INITING,
                Ordering::Acquire,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    // Safe to use ResetOnDrop: init_fn panics causes destructor,
                    // UNINIT state = 0, guard forgotten on success
                    let guard = ResetOnDrop { state: &self.state };
                    let value = init_fn();

                    unsafe {
                        (*self.value.get()).write(Mutex::new(value));
                    }
                    std::mem::forget(guard);
                    self.state.store(Self::INITED, Ordering::Release);
                    return;
                }
                Err(state) => match state {
                    Self::INITING => {
                        if step > Self::MAX_SPIN {
                            std::thread::yield_now();
                        } else {
                            for _ in 0..(1 << step) {
                                std::hint::spin_loop();
                            }
                        }
                    }
                    Self::INITED => return,
                    _ => unsafe { std::hint::unreachable_unchecked() },
                },
            }

            step += 1;
        }
    }

    /// Async init, optimized
    #[inline(always)]
    pub async fn init_async<F, Fut>(&self, init_fn: F)
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        let mut step = 0;
        loop {
            match self.state.compare_exchange(
                Self::UNINIT,
                Self::INITING,
                Ordering::Acquire,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    // Safe to use ResetOnDrop: init_fn panics causes destructor,
                    // UNINIT state = 0, guard forgotten on success
                    let guard = ResetOnDrop { state: &self.state };
                    // catch unwind to ensure guard is dropped correctly
                    let value = AssertUnwindSafe(init_fn())
                        .catch_unwind()
                        .await;

                    if let Ok(value) = value {
                        unsafe {
                            (*self.value.get()).write(Mutex::new(value));
                        }
                        std::mem::forget(guard);
                        self.state.store(Self::INITED, Ordering::Release);
                    } else {
                        std::panic::resume_unwind(value.err().unwrap());
                    }
                    return;
                }
                Err(state) => match state {
                    Self::INITING => {
                        if step > Self::MAX_SPIN {
                            yield_now().await;
                        } else {
                            for _ in 0..(1 << step) {
                                std::hint::spin_loop();
                            }
                        }
                    }
                    Self::INITED => return,
                    _ => unsafe { std::hint::unreachable_unchecked() },
                },
            }

            step += 1;
        }
    }

    /// Fetches the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner(&self) -> &Mutex<T> {
        debug_assert!(self.is_initialized(), "RawMutexCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { &*(*self.value.get()).as_ptr() }
    }

    /// Fetches the inner value mutably, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner_mut(&self) -> &mut Mutex<T> {
        debug_assert!(self.is_initialized(), "RawMutexCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { &mut *(*self.value.get()).as_mut_ptr() }
    }
}
impl<T> Drop for RawMutexCell<T> {
    fn drop(&mut self) {
        if self.is_initialized() {
            unsafe {
                std::ptr::drop_in_place(self.inner_mut());
            }
        }
    }
}

/// # RawOnceCell
/// A RawCell variant that can only be initialized once. Helpful for a lazy-initialized static.
/// RawOnceCell can never be dropped once initialized.
#[repr(C, align(128))]
pub struct RawOnceCell<T> {
    state: AtomicU8,
    value: UnsafeCell<MaybeUninit<T>>,
}
unsafe impl<T: Send> Send for RawOnceCell<T> {}
unsafe impl<T: Sync> Sync for RawOnceCell<T> {}
impl<T> const CellTrait<T> for RawOnceCell<T> {
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
}
impl<'a, T> RawOnceCell<T> {
    const UNINIT: u8 = 0;
    const INITING: u8 = 1;
    const INITED: u8 = 2;

    /// Creates a new, uninitialized RawOnceCell.
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            state: AtomicU8::new(Self::UNINIT),
            value: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    /// Checks if the RawOnceCell has been initialized.
    #[inline(always)]
    pub fn is_initialized(&self) -> bool {
        self.state.load(Ordering::Acquire) == Self::INITED
    }

    /// Creates a new, initialized RawOnceCell with the provided value.
    /// RawOnceCell will be initialized upon creation.
    #[inline(always)]
    pub const fn from(value: T) -> Self {
        Self {
            state: AtomicU8::new(Self::INITED),
            value: UnsafeCell::new(MaybeUninit::new(value)),
        }
    }

    /// Initializes the RawOnceCell if it has not been initialized yet.
    #[inline(always)]
    pub fn init<F>(&self, init_fn: F)
    where
        F: FnOnce() -> T,
    {
        if likely(self.is_initialized()) {
            return;
        }

        let mut step = 0;
        loop {
            let state = self.state.load(Ordering::Acquire);

            match state {
                Self::INITED => return,
                Self::UNINIT => {
                    if self.state.compare_exchange(
                        Self::UNINIT,
                        Self::INITING,
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ).is_ok() {
                        // Safe to use ResetOnDrop: init_fn panics causes destructor,
                        // UNINIT state = 0, guard forgotten on success
                        let guard = ResetOnDrop { state: &self.state };
                        unsafe {
                            (*self.value.get()).as_mut_ptr().write(init_fn());
                        }
                        std::mem::forget(guard);
                        self.state.store(Self::INITED, Ordering::Release);
                        return;
                    }
                }
                Self::INITING => {
                    if step > 8 {
                        std::thread::yield_now();
                    } else {
                        for _ in 0..(1 << step) {
                            std::hint::spin_loop();
                        }
                    }
                }
                _ => unsafe { std::hint::unreachable_unchecked() },
            }

            step += 1;
        }
    }

    /// Initializes the RawOnceCell asynchronously if it has not been initialized yet.
    #[inline(always)]
    pub async fn init_async<F, Fut>(&self, init_fn: F)
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        if likely(self.is_initialized()) {
            return;
        }

        let mut step = 0;
        loop {
            let state = self.state.load(Ordering::Acquire);

            match state {
                Self::INITED => return,
                Self::UNINIT => {
                    if self.state.compare_exchange(
                        Self::UNINIT,
                        Self::INITING,
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ).is_ok() {
                        // Safe to use ResetOnDrop: init_fn panics causes destructor,
                        // UNINIT state = 0, guard forgotten on success
                        let guard = ResetOnDrop { state: &self.state };
                        // catch unwind to ensure guard is dropped correctly
                        let value = AssertUnwindSafe(init_fn())
                            .catch_unwind()
                            .await;

                        if let Ok(value) = value {
                            unsafe {
                                (*self.value.get()).as_mut_ptr().write(value);
                            }
                            std::mem::forget(guard);
                            self.state.store(Self::INITED, Ordering::Release);
                        } else {
                            std::panic::resume_unwind(value.err().unwrap());
                        }
                        return;
                    }
                }
                Self::INITING => {
                    if step > 8 {
                        yield_now().await;
                    } else {
                        for _ in 0..(1 << step) {
                            std::hint::spin_loop();
                        }
                    }
                }
                _ => unsafe { std::hint::unreachable_unchecked() },
            }

            step += 1;
        }
    }

    /// Initialize the RawOnceCell if not already initialized, returning a reference to the inner value.
    #[inline(always)]
    pub fn get_or_init<F>(&self, init_fn: F) -> &'a T
    where
        F: FnOnce() -> T,
    {
        if !self.is_initialized() {
            self.init(init_fn);
        }
        unsafe { self.inner() }
    }

    /// Fetches the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner(&self) -> &'a T {
        debug_assert!(self.is_initialized(), "RawOnceCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { &*(*self.value.get()).as_ptr() }
    }
}
// Drop is intentionally not implemented for RawOnceCell to prevent dropping once initialized.

/// # RawDirectCell
/// RawDirectCell is a low-level primitive that offers direct access to its inner value,
/// without any locks or synchronization mechanisms. It is designed for single-threaded
/// contexts or scenarios where the user can guarantee exclusive access to the cell.
/// 
/// RawDirectCell doesn't support asynchronous operations or concurrent initializations;
/// it is the user's responsibility to ensure safe access patterns.
#[repr(C, align(128))]
pub struct RawDirectCell<T> {
    value: UnsafeCell<MaybeUninit<T>>,
    state: AtomicBool
}
impl<T> const CellTrait<T> for RawDirectCell<T> {
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
}
impl<T> RawDirectCell<T> {
    /// Creates a new, uninitialized RawDirectCell.
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            value: UnsafeCell::new(MaybeUninit::uninit()),
            state: AtomicBool::new(false),
        }
    }

    /// Initializes the RawDirectCell with the provided value.
    #[inline(always)]
    pub fn init<F>(&self, init_fn: F)
    where
        F: FnOnce() -> T,
    {
        if self.is_initialized() {
            return;
        }

        unsafe {
            (*self.value.get()).as_mut_ptr().write(init_fn());
        }
        self.state.store(true, Ordering::Release);
    }

    /// Determines if the RawDirectCell has been initialized.
    #[inline(always)]
    pub fn is_initialized(&self) -> bool {
        self.state.load(Ordering::Acquire)
    }

    /// Fetches the inner value, initializing it if necessary.
    #[inline(always)]
    pub fn get_or_init<F>(&self, init_fn: F) -> &T
    where
        F: FnOnce() -> T,
    {
        if unlikely(!self.is_initialized()) {
            self.init(init_fn);
        }
        unsafe { self.inner() }
    }

    /// Fetches the inner value, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner(&self) -> &T {
        debug_assert!(self.is_initialized(), "RawDirectCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { &*(*self.value.get()).as_ptr() }
    }

    /// Fetches the inner value mutably, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn inner_mut(&self) -> &mut T {
        debug_assert!(self.is_initialized(), "RawDirectCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { &mut *(*self.value.get()).as_mut_ptr() }
    }
}
impl<T> Drop for RawDirectCell<T> {
    fn drop(&mut self) {
        if self.is_initialized() {
            unsafe {
                std::ptr::drop_in_place(self.inner_mut());
            }
        }
    }
}

/// # RawOptionCell
/// A RawCell variant that can hold an Option<T>, allowing for "empty" states even
/// after initialization.
#[repr(C, align(128))]
pub struct RawOptionCell<T> {
    inner: RawCell<Option<T>>,
}
unsafe impl<T: Send> Send for RawOptionCell<T> {}
unsafe impl<T: Sync> Sync for RawOptionCell<T> {}
impl<T: Send + Sync> const CellTrait<Option<T>> for RawOptionCell<T> {
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
}
impl<T: Send + Sync> RawOptionCell<T> {
    /// Creates a new, uninitialized RawOptionCell.
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            inner: RawCell::new(),
        }
    }

    /// Initializes the RawOptionCell with the provided value.
    #[inline(always)]
    pub fn init<F>(&self, init_fn: F)
    where
        F: FnOnce() -> Option<T>,
    {
        self.inner.init(init_fn);
    }

    /// Async initializes the RawOptionCell with the provided value.
    #[inline(always)]
    pub async fn init_async<F, Fut>(&self, init_fn: F)
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Option<T>>,
    {
        self.inner.init_async(init_fn).await;
    }

    /// Fetches a read lock to the inner Option<T>, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn read(&self) -> RwLockReadGuard<'_, Option<T>> {
        debug_assert!(self.inner.is_initialized(), "RawOptionCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { self.inner.read() }
    }

    /// Fetches a write lock to the inner Option<T>, assuming initialization has already occurred.
    #[inline(always)]
    pub unsafe fn write(&self) -> RwLockWriteGuard<'_, Option<T>> {
        debug_assert!(self.inner.is_initialized(), "RawOptionCell is not initialized");
        // SAFETY: caller ensured initialization
        unsafe { self.inner.write() }
    }
}
// Drop is automatically handled by RawCell's Drop implementation.