atom_box 0.3.0

A safe idiomatic Rust implementation of Atomic Box using hazard pointers
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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! # Atom Box
//!
//! This crate provides a safe idiomatic Rust API for an Atomic Box with safe memory
//! reclamation when used in multi-threaded concurrent lock-free data structures.
//!
//! Under the covers it uses Hazard Pointers to ensure memory is only reclaimed when all references
//! are dropped.
//!
//! The main type provided is the `AtomBox`.
//!
//! # Examples
//!
//! ```
//! use atom_box::AtomBox;
//! use std::{sync::Arc, thread};
//!
//! const ITERATIONS: usize = 1000;
//!
//! let atom_box1 = Arc::new(AtomBox::new(0));
//! let atom_box2 = Arc::new(AtomBox::new(0));
//!
//! let a_box1 = atom_box1.clone();
//! let handle1 = thread::spawn(move || {
//!     let mut current_value = 0;
//!     for _ in 1..=ITERATIONS {
//!         let new_value = a_box1.load();
//!         assert!(*new_value >= current_value, "Value should not decrease");
//!         current_value = *new_value;
//!     }
//! });
//!
//! let a_box1 = atom_box1.clone();
//! let a_box2 = atom_box2.clone();
//! let handle2 = thread::spawn(move || {
//!     for i in 1..=ITERATIONS {
//!         let guard1 = a_box1.swap(i);
//!         let value1 = *guard1;
//!         let guard2 = a_box2.swap_from_guard(guard1);
//!         assert!(
//!             *guard2 <= value1,
//!             "Value in first box should be greater than or equal to value in second box"
//!         );
//!     }
//! });
//!
//! handle1.join().unwrap();
//! handle2.join().unwrap();
//! ```

#![no_std]
#![warn(missing_docs)]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
use crate::sync::{AtomicPtr, Ordering};
use core::ops::Deref;

pub mod domain;
mod sync;

use crate::domain::{Domain, HazardPointer};
use alloc::boxed::Box;

#[cfg(not(loom))]
const SHARED_DOMAIN_ID: usize = 0;

#[cfg(not(loom))]
static SHARED_DOMAIN: Domain<SHARED_DOMAIN_ID> = Domain::default();

mod macros {
    // The loom atomics do not have const constructors. So we cannot use them in const functions.
    // This macro enables us to create a const function in normal compilation and a non const
    // function when compiling for loom.
    #[cfg(not(loom))]
    macro_rules! conditional_const {
        ($( #[doc = $doc:expr] )* $visibility:vis fn $( $token:tt )*) => {
            $( #[doc = $doc] )*
            $visibility const fn $( $token )*
        };
    }
    #[cfg(loom)]
    macro_rules! conditional_const {
        ($( #[doc = $doc:expr] )* $visibility:vis fn $( $token:tt )*) => {
            $( #[doc = $doc] )*
            $visibility fn $( $token )*
        };
    }
    pub(crate) use conditional_const;
}

/// A box which can safely be shared between threads and atomically updated.
///
/// Memory will be safely reclaimed after all threads have dropped their references to any give
/// value.
///
/// # Example
///
/// ```
/// use atom_box::AtomBox;
/// use std::thread;
///
/// const ITERATIONS: usize = 1000;
///
/// let atom_box1: &'static _ = AtomBox::new_static(0);
/// let atom_box2: &'static _ = AtomBox::new_static(0);
///
/// let handle1 = thread::spawn(move || {
///     let mut current_value = 0;
///     for _ in 1..=ITERATIONS {
///         let new_value = atom_box1.load();
///         assert!(*new_value >= current_value, "Value should not decrease");
///         current_value = *new_value;
///     }
/// });
///
/// let handle2 = thread::spawn(move || {
///     for i in 1..=ITERATIONS {
///         let guard1 = atom_box1.swap(i);
///         let value1 = *guard1;
///         let guard2 = atom_box2.swap_from_guard(guard1);
///         assert!(
///             *guard2 <= value1,
///             "Value in first box should be greater than or equal to value in second box"
///         );
///     }
/// });
///
/// handle1.join().unwrap();
/// handle2.join().unwrap();
/// ```
#[derive(Debug)]
pub struct AtomBox<'domain, T, const DOMAIN_ID: usize> {
    ptr: AtomicPtr<T>,
    domain: &'domain Domain<DOMAIN_ID>,
}

#[cfg(not(loom))]
impl<T> AtomBox<'static, T, SHARED_DOMAIN_ID> {
    /// Creates a new `AtomBox` associated with the shared (global) domain.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new("Hello");
    ///
    /// let value = atom_box.load();
    /// assert_eq!(*value, "Hello");
    ///
    /// atom_box.store("World");
    /// let value = atom_box.load();
    /// assert_eq!(*value, "World");
    /// ```
    pub fn new(value: T) -> Self {
        let ptr = AtomicPtr::new(Box::into_raw(Box::new(value)));
        Self {
            ptr,
            domain: &SHARED_DOMAIN,
        }
    }

    /// Creates a new `AtomBox` with a static lifetime.
    ///
    /// A convenience constructor for `Box::leak(Box::new(Self::new(value)))`.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    /// let atom_box: &'static _ = AtomBox::new_static(50);
    /// let value = atom_box.load();
    ///
    /// assert_eq!(
    ///     *value, 50,
    ///     "We are able to get the original value by loading it"
    /// );
    /// let handle1 = std::thread::spawn(move || {
    ///     let h_box = atom_box;
    ///     let value = h_box.load();
    ///     assert_eq!(
    ///         *value, 50,
    ///         "The value should be accessible in multiple threads"
    ///     );
    /// });
    /// let handle2 = std::thread::spawn(move || {
    ///     let h_box = atom_box;
    ///     let value = h_box.load();
    ///     assert_eq!(
    ///         *value, 50,
    ///         "The value should be accessible in multiple threads"
    ///     );
    /// });
    /// handle1.join().unwrap();
    /// handle2.join().unwrap();
    /// ```
    pub fn new_static(value: T) -> &'static mut Self {
        Box::leak(Box::new(Self::new(value)))
    }
}

impl<'domain, T, const DOMAIN_ID: usize> AtomBox<'domain, T, DOMAIN_ID> {
    /// Creates a new `AtomBox` and associates it with the given domain.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::{AtomBox, domain::Domain, domain::ReclaimStrategy};
    ///
    /// const CUSTOM_DOMAIN_ID: usize = 42;
    /// static CUSTOM_DOMAIN: Domain<CUSTOM_DOMAIN_ID> = Domain::new(ReclaimStrategy::Eager);
    ///
    /// let atom_box = AtomBox::new_with_domain("Hello World", &CUSTOM_DOMAIN);
    /// assert_eq!(*atom_box.load(), "Hello World");
    /// ```
    pub fn new_with_domain(value: T, domain: &'domain Domain<DOMAIN_ID>) -> Self {
        let ptr = AtomicPtr::new(Box::into_raw(Box::new(value)));
        Self { ptr, domain }
    }

    /// Loads the value stored in the `AtomBox`.
    ///
    /// Returns a `LoadGuard` which can be dereferenced into the value.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new("Hello World");
    ///
    /// let value = atom_box.load();
    /// assert_eq!(*value, "Hello World");
    /// ```
    pub fn load(&self) -> LoadGuard<'domain, T, DOMAIN_ID> {
        let haz_ptr = self.domain.acquire_haz_ptr();
        // load pointer
        let mut original_ptr = self.ptr.load(Ordering::Relaxed);

        let ptr = loop {
            // protect pointer
            haz_ptr.protect(original_ptr as *mut usize);

            core::sync::atomic::fence(Ordering::SeqCst);

            // check pointer
            let current_ptr = self.ptr.load(Ordering::Acquire);
            if current_ptr == original_ptr {
                // The pointer is the same, we have successfully protected its value.
                break current_ptr;
            }
            haz_ptr.reset();
            original_ptr = current_ptr;
        };
        LoadGuard {
            ptr,
            domain: self.domain,
            haz_ptr: Some(haz_ptr),
        }
    }

    /// Stores a new value in the `AtomBox`
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new("Hello");
    /// atom_box.store("World");
    ///
    /// let value = atom_box.load();
    /// assert_eq!(*value, "World");
    /// ```
    pub fn store(&self, value: T) {
        let _ = self.swap(value);
    }

    /// Stores the value protected by the `StoreGuard` in the `AtomBox`
    ///
    /// # Panics
    ///
    /// Panics if the guard is associated with a different domain.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box1 = AtomBox::new("Hello");
    /// let atom_box2 = AtomBox::new("World");
    ///
    /// let guard = atom_box1.swap("Bye Bye");
    ///
    /// atom_box2.store_from_guard(guard);
    /// let value = atom_box2.load();
    /// assert_eq!(*value, "Hello");
    /// ```
    pub fn store_from_guard(&self, value: StoreGuard<'domain, T, DOMAIN_ID>) {
        let _ = self.swap_from_guard(value);
    }

    /// Stores the value into the `AtomBox` and returns a `StoreGuard` which dereferences into the
    /// previous value.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new("Hello World");
    ///
    /// let guard = atom_box.swap("Bye Bye");
    /// assert_eq!(*guard, "Hello World");
    /// ```
    pub fn swap(&self, new_value: T) -> StoreGuard<'domain, T, DOMAIN_ID> {
        let new_ptr = Box::into_raw(Box::new(new_value));
        let old_ptr = self.ptr.swap(new_ptr, Ordering::AcqRel);
        StoreGuard {
            ptr: old_ptr,
            domain: self.domain,
        }
    }

    /// Stores the value into the `AtomBox` and returns a `StoreGuard` which dereferences into the
    /// previous value.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Panics
    ///
    /// Panics if the guard is associated with a different domain.
    ///
    /// # Example
    ///
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box1 = AtomBox::new("Hello");
    /// let atom_box2 = AtomBox::new("World");
    ///
    /// let guard1 = atom_box1.swap("Bye Bye");
    ///
    /// let guard2 = atom_box2.swap_from_guard(guard1);
    /// assert_eq!(*guard2, "World");
    /// ```
    ///
    /// The following example will fail to compile.
    ///
    /// ```compile_fail
    /// use atom_box::{AtomBox, domain::{Domain, ReclaimStrategy}};
    ///
    /// const CUSTOM_DOMAIN_ID: usize = 42;
    /// static CUSTOM_DOMAIN: Domain<CUSTOM_DOMAIN_ID> = Domain::new(ReclaimStrategy::Eager);
    ///
    /// let atom_box1 = AtomBox::new_with_domain("Hello", &CUSTOM_DOMAIN);
    /// let atom_box2 = AtomBox::new("World");
    ///
    /// let guard = atom_box1.swap("Bye bye");
    /// atom_box2.swap_from_guard(guard);
    /// ```
    pub fn swap_from_guard(
        &self,
        new_value: StoreGuard<'domain, T, DOMAIN_ID>,
    ) -> StoreGuard<'domain, T, DOMAIN_ID> {
        assert!(
            core::ptr::eq(new_value.domain, self.domain),
            "Cannot use guarded value from different domain"
        );

        let new_ptr = new_value.ptr;
        core::mem::forget(new_value);
        let old_ptr = self.ptr.swap(new_ptr as *mut T, Ordering::AcqRel);
        StoreGuard {
            ptr: old_ptr,
            domain: self.domain,
        }
    }

    /// Stores a value into the `AtomBox` if its current value equals `current_value`.
    ///
    /// The return value is a result indicating whether the new value was written.
    /// On success, this value is guaranteed to be equal to `current_value` and the return value is
    /// a StoreGuard which dereferences to the old value.
    /// On failure, the `Err` contains a LoadGuard which dereferences to the `current_value`.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Example
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new(0);
    /// let mut current_value = atom_box.load();
    /// let initial_value = *current_value;
    /// let _ = loop {
    ///     let new_value = *current_value + 1;
    ///     match atom_box.compare_exchange(current_value, new_value) {
    ///         Ok(value) => {
    ///             break value;
    ///         }
    ///         Err(value) => {
    ///             current_value = value;
    ///         }
    ///     }
    /// };
    /// let new_value = atom_box.load();
    /// assert!(
    ///     *new_value > initial_value,
    ///     "Value should have been increased"
    /// );
    /// ```
    pub fn compare_exchange(
        &self,
        current_value: LoadGuard<'domain, T, DOMAIN_ID>,
        new_value: T,
    ) -> Result<StoreGuard<'domain, T, DOMAIN_ID>, LoadGuard<'domain, T, DOMAIN_ID>> {
        let new_ptr = Box::into_raw(Box::new(new_value));
        match self.ptr.compare_exchange(
            current_value.ptr as *mut T,
            new_ptr,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(ptr) => Ok(StoreGuard {
                ptr,
                domain: self.domain,
            }),
            Err(ptr) => Err(LoadGuard {
                ptr,
                domain: self.domain,
                haz_ptr: None,
            }),
        }
    }

    /// Stores a value into the `AtomBox` if its current value equals `current_value`.
    ///
    /// The return value is a result indicating whether the new value was written.
    /// On success, this value is guaranteed to be equal to `current_value` and the return value is
    /// a StoreGuard which dereferences to the old value.
    /// On failure, the `Err` contains a LoadGuard which dereferences to the `current_value`.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Panics
    ///
    /// Panics if the guard is associated with a different domain.
    ///
    /// # example
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box1 = AtomBox::new(0);
    /// let atom_box2 = AtomBox::new(1);
    ///
    /// let mut guard = atom_box2.swap(2);
    /// let mut current_value = atom_box1.load();
    /// let _ = loop {
    ///     match atom_box1.compare_exchange_from_guard(current_value, guard) {
    ///         Ok(value) => {
    ///             break value;
    ///         }
    ///         Err((value, returned_guard)) => {
    ///             current_value = value;
    ///             guard = returned_guard;
    ///         }
    ///     }
    /// };
    /// let new_value = atom_box1.load();
    /// assert!(*new_value == 1, "value should have been increased");
    /// ```
    ///
    /// The following example will fail to compile.
    ///
    /// ```compile_fail
    /// use atom_box::{AtomBox, domain::{Domain, ReclaimStrategy}};
    ///
    /// const CUSTOM_DOMAIN_ID: usize = 42;
    /// static CUSTOM_DOMAIN: Domain<CUSTOM_DOMAIN_ID> = Domain::new(ReclaimStrategy::Eager);
    ///
    /// let atom_box1 = AtomBox::new_with_domain("hello", &CUSTOM_DOMAIN);
    /// let atom_box2 = AtomBox::new("world");
    ///
    /// let guard = atom_box1.swap("bye bye");
    /// let current_value = atom_box2.load();
    /// let _ = atom_box2.compare_exchange_from_guard(current_value, guard);
    /// ```
    pub fn compare_exchange_from_guard(
        &self,
        current_value: LoadGuard<'domain, T, DOMAIN_ID>,
        new_value: StoreGuard<'domain, T, DOMAIN_ID>,
    ) -> Result<
        StoreGuard<'domain, T, DOMAIN_ID>,
        (
            LoadGuard<'domain, T, DOMAIN_ID>,
            StoreGuard<'domain, T, DOMAIN_ID>,
        ),
    > {
        assert!(
            core::ptr::eq(new_value.domain, self.domain),
            "Cannot use guarded value from different domain"
        );

        let new_ptr = new_value.ptr;
        match self.ptr.compare_exchange(
            current_value.ptr as *mut T,
            new_ptr as *mut T,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(ptr) => {
                core::mem::forget(new_value);
                Ok(StoreGuard {
                    ptr,
                    domain: self.domain,
                })
            }
            Err(ptr) => Err((
                LoadGuard {
                    ptr,
                    domain: self.domain,
                    haz_ptr: None,
                },
                new_value,
            )),
        }
    }

    /// Stores a value into the `AtomBox` if the current value is the same as the `current` value.
    ///
    /// Unlike [`AtomBox::compare_exchange`], this function is allowed to spuriously fail even when the
    /// comparison succeeds, which can result in more efficient code on some platforms. The
    /// return value is a result indicating whether the new value was written and containing the
    /// previous value.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Example
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box = AtomBox::new(0);
    /// let mut current_value = atom_box.load();
    /// let initial_value = *current_value;
    /// let _ = loop {
    ///     let new_value = *current_value + 1;
    ///     match atom_box.compare_exchange_weak(current_value, new_value) {
    ///         Ok(value) => {
    ///             break value;
    ///         }
    ///         Err(value) => {
    ///             current_value = value;
    ///         }
    ///     }
    /// };
    /// let new_value = atom_box.load();
    /// assert!(
    ///     *new_value > initial_value,
    ///     "Value should have been increased"
    /// );
    /// ```
    pub fn compare_exchange_weak(
        &self,
        current_value: LoadGuard<'domain, T, DOMAIN_ID>,
        new_value: T,
    ) -> Result<StoreGuard<'domain, T, DOMAIN_ID>, LoadGuard<'domain, T, DOMAIN_ID>> {
        let new_ptr = Box::into_raw(Box::new(new_value));
        match self.ptr.compare_exchange_weak(
            current_value.ptr as *mut T,
            new_ptr,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(ptr) => Ok(StoreGuard {
                ptr,
                domain: self.domain,
            }),
            Err(ptr) => Err(LoadGuard {
                ptr,
                domain: self.domain,
                haz_ptr: None,
            }),
        }
    }

    /// Stores a value into the `AtomBox` if the current value is the same as the `current` value.
    ///
    /// Unlike [`AtomBox::compare_exchange_from_guard`], this function is allowed to spuriously fail even when the
    /// comparison succeeds, which can result in more efficient code on some platforms. The
    /// return value is a result indicating whether the new value was written and containing the
    /// previous value.
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on
    /// pointers.
    ///
    /// # Panics
    ///
    /// Panics if the guard is associated with a different domain.
    ///
    /// # example
    /// ```
    /// use atom_box::AtomBox;
    ///
    /// let atom_box1 = AtomBox::new(0);
    /// let atom_box2 = AtomBox::new(1);
    ///
    /// let mut guard = atom_box2.swap(2);
    /// let mut current_value = atom_box1.load();
    /// let _ = loop {
    ///     match atom_box1.compare_exchange_weak_from_guard(current_value, guard) {
    ///         Ok(value) => {
    ///             break value;
    ///         }
    ///         Err((value, returned_guard)) => {
    ///             current_value = value;
    ///             guard = returned_guard;
    ///         }
    ///     }
    /// };
    /// let new_value = atom_box1.load();
    /// assert!(*new_value == 1, "value should have been increased");
    /// ```
    ///
    /// The following example will fail to compile.
    ///
    /// ```compile_fail
    /// use atom_box::{AtomBox, domain::{Domain, ReclaimStrategy}};
    ///
    /// const CUSTOM_DOMAIN_ID: usize = 42;
    /// static CUSTOM_DOMAIN: Domain<CUSTOM_DOMAIN_ID> = Domain::new(ReclaimStrategy::Eager);
    ///
    /// let atom_box1 = AtomBox::new_with_domain("hello", &CUSTOM_DOMAIN);
    /// let atom_box2 = AtomBox::new("world");
    ///
    /// let guard = atom_box1.swap("bye bye");
    /// let current_value = atom_box2.load();
    /// let _ = atom_box2.compare_exchange_weak_from_guard(current_value, guard);
    /// ```
    pub fn compare_exchange_weak_from_guard(
        &self,
        current_value: LoadGuard<'domain, T, DOMAIN_ID>,
        new_value: StoreGuard<'domain, T, DOMAIN_ID>,
    ) -> Result<
        StoreGuard<'domain, T, DOMAIN_ID>,
        (
            LoadGuard<'domain, T, DOMAIN_ID>,
            StoreGuard<'domain, T, DOMAIN_ID>,
        ),
    > {
        assert!(
            core::ptr::eq(new_value.domain, self.domain),
            "Cannot use guarded value from different domain"
        );

        let new_ptr = new_value.ptr;
        match self.ptr.compare_exchange_weak(
            current_value.ptr as *mut T,
            new_ptr as *mut T,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(ptr) => {
                core::mem::forget(new_value);
                Ok(StoreGuard {
                    ptr,
                    domain: self.domain,
                })
            }
            Err(ptr) => Err((
                LoadGuard {
                    ptr,
                    domain: self.domain,
                    haz_ptr: None,
                },
                new_value,
            )),
        }
    }
}

impl<'domain, T, const DOMAIN_ID: usize> Drop for AtomBox<'domain, T, DOMAIN_ID> {
    fn drop(&mut self) {
        // # Safety
        //
        // The pointer to this object was originally created via box into raw.
        // The heap allocated value cannot be dropped via external code.
        // We are the only person with this pointer since we have an exclusive reference to the box
        // and we would not have this pointer if we had given it out in a StoreGuard. There might
        // be other people referencing it as a read only value where it is protected
        // via hazard pointers.
        // We are safe to flag it for retire, where it will be reclaimed when it is no longer
        // protected by any hazard pointers.
        let ptr = self.ptr.load(Ordering::Relaxed);
        unsafe { self.domain.retire(ptr) };
    }
}

/// Contains a reference to a value that was previously contained in an `AtomBox`.
///
/// Returned from the store methods method on `AtomBox`. This value can be passed to the
/// `from_guard` methods to store this value in an `AtomBox` associated with the same domain.
///
/// Dereferences to the value.
pub struct StoreGuard<'domain, T, const DOMAIN_ID: usize> {
    ptr: *const T,
    domain: &'domain Domain<DOMAIN_ID>,
}

impl<T, const DOMAIN_ID: usize> Deref for StoreGuard<'_, T, DOMAIN_ID> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        // # Safety
        //
        // The pointer is protected by the hazard pointer so will not have been dropped
        // The pointer was created via a Box so is aligned and there are no mutable references
        // since we do not give any out.
        unsafe { self.ptr.as_ref().expect("Non null") }
    }
}

impl<T, const DOMAIN_ID: usize> Drop for StoreGuard<'_, T, DOMAIN_ID> {
    fn drop(&mut self) {
        // # Safety
        //
        // The pointer to this object was originally created via box into raw.
        // The heap allocated value cannot be dropped via external code.
        // We are the only person with this pointer in a store guard. There might
        // be other people referencing it as a read only value where it is protected
        // via hazard pointers.
        // We are safe to flag it for retire, where it will be reclaimed when it is no longer
        // protected by any hazard pointers.
        unsafe { self.domain.retire(self.ptr as *mut T) };
    }
}

/// Contains a reference to a value that was stored in a `AtomBox`.
///
/// Returned as the result of calling [`AtomBox::load`].
///
/// The value is guaranteed not to be dropped before this guard is dropped.
///
/// Dereferences to the value.
pub struct LoadGuard<'domain, T, const DOMAIN_ID: usize> {
    ptr: *const T,
    domain: &'domain Domain<DOMAIN_ID>,
    haz_ptr: Option<HazardPointer<'domain>>,
}

impl<T, const DOMAIN_ID: usize> Drop for LoadGuard<'_, T, DOMAIN_ID> {
    fn drop(&mut self) {
        if let Some(haz_ptr) = self.haz_ptr.take() {
            self.domain.release_hazard_ptr(haz_ptr);
        }
    }
}

impl<T, const DOMAIN_ID: usize> Deref for LoadGuard<'_, T, DOMAIN_ID> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        // # Safety
        //
        // The pointer is protected by the hazard pointer so will not have been dropped
        // The pointer was created via a Box so is aligned and there are no mutable references
        // since we do not give any out.
        unsafe { self.ptr.as_ref().expect("Non null") }
    }
}

#[cfg(not(loom))]
#[cfg(test)]
mod test {
    use super::*;

    pub(crate) use core::sync::atomic::AtomicUsize;

    static TEST_DOMAIN: domain::Domain<1> = Domain::new(domain::ReclaimStrategy::Eager);

    struct DropTester<'a, T> {
        drop_count: &'a AtomicUsize,
        value: T,
    }

    impl<'a, T> Drop for DropTester<'a, T> {
        fn drop(&mut self) {
            self.drop_count.fetch_add(1, Ordering::AcqRel);
        }
    }

    impl<'a, T> Deref for DropTester<'a, T> {
        type Target = T;
        fn deref(&self) -> &Self::Target {
            &self.value
        }
    }

    #[test]
    fn single_thread_retire() {
        let atom_box = AtomBox::new(20);

        let value = atom_box.load();
        assert_eq!(
            *value, 20,
            "The correct values is returned when dereferencing"
        );
        assert_eq!(
            value.ptr,
            value.haz_ptr.as_ref().unwrap().0.load(Ordering::Acquire),
            "The hazard pointer is protecting the correct pointer"
        );

        {
            // Immediately retire the original value
            let guard = atom_box.swap(30);
            assert_eq!(
                guard.ptr, value.ptr,
                "The guard returned after swap contains a pointer to the old value"
            );
            let new_value = atom_box.load();
            assert_eq!(*new_value, 30, "The new value has been set correctly");
        }
        assert_eq!(
            *value, 20,
            "We are still able to access the old value as a result of the original load"
        );
        drop(value);
        let _ = atom_box.swap(40);
        let final_value = atom_box.load();
        assert_eq!(
            *final_value, 40,
            "When we load again we get a handle to the latest value"
        );
    }

    #[test]
    fn drop_test() {
        let drop_count = AtomicUsize::new(0);
        let value = DropTester {
            drop_count: &drop_count,
            value: 20,
        };
        let atom_box = AtomBox::new_with_domain(value, &TEST_DOMAIN);

        let value = atom_box.load();
        assert_eq!(
            drop_count.load(Ordering::Acquire),
            0,
            "No values have been dropped yet"
        );
        assert_eq!(**value, 20, "The correct value is returned via load");
        assert_eq!(
            value.ptr as *mut usize,
            value.haz_ptr.as_ref().unwrap().0.load(Ordering::Acquire),
            "The value is protected by the hazard pointer"
        );

        {
            // Immediately retire the original value
            let guard = atom_box.swap(DropTester {
                drop_count: &drop_count,
                value: 30,
            });
            assert_eq!(
                guard.ptr, value.ptr,
                "When we swap the value we get back a guard that contains a pointer to the old value"
            );
            let new_value = atom_box.load();
            assert_eq!(
                **new_value, 30,
                "When we dereference the load, we get back a reference to the new value"
            );
            drop(guard);
        }
        assert_eq!(
            drop_count.load(Ordering::SeqCst),
            0,
            "Value should not be dropped while there is an active reference to it"
        );
        assert_eq!(
            **value, 20,
            "We are still able to access the original value since we have been holding a load guard"
        );
        drop(value);
        let _ = atom_box.swap(DropTester {
            drop_count: &drop_count,
            value: 40,
        });
        let final_value = atom_box.load();
        assert_eq!(**final_value, 40, "The value has been updated");
        assert_eq!(
            drop_count.load(Ordering::SeqCst),
            2,
            "Both of the old values should now be dropped"
        );
    }

    #[test]
    fn swap_from_guard_test() {
        let drop_count = AtomicUsize::new(0);
        let drop_count_for_placeholder = AtomicUsize::new(0);
        let value1 = DropTester {
            drop_count: &drop_count,
            value: 10,
        };
        let value2 = DropTester {
            drop_count: &drop_count,
            value: 20,
        };
        let atom_box1 = AtomBox::new_with_domain(value1, &TEST_DOMAIN);
        let atom_box2 = AtomBox::new_with_domain(value2, &TEST_DOMAIN);

        {
            // Immediately retire the original value
            let guard1 = atom_box1.swap(DropTester {
                drop_count: &drop_count_for_placeholder,
                value: 30,
            });
            let guard2 = atom_box2.swap_from_guard(guard1);
            let _ = atom_box1.swap_from_guard(guard2);
            let new_value1 = atom_box1.load();
            let new_value2 = atom_box2.load();
            assert_eq!(
                **new_value1, 20,
                "The values in the boxes should have been swapped"
            );
            assert_eq!(
                **new_value2, 10,
                "The values in the boxes should have been swapped"
            );
        }
        assert_eq!(
            drop_count_for_placeholder.load(Ordering::Acquire),
            1,
            "The placeholder value should have been dropped"
        );
        assert_eq!(
            drop_count.load(Ordering::Acquire),
            0,
            "Neither of the initial values should have been dropped"
        );
    }
}