atomic-tagged-ptr 0.3.1

A platform-adaptive atomic tagged pointer implementation supporting 32-bit, 48-bit, and 52/57-bit high virtual address layouts with ABA protection.
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
//! A platform-adaptive atomic tagged pointer implementation with robust ABA protection.
//!
//! # Background & Hardware Realities
//!
//! In lock-free concurrent programming, particularly when constructing intrusive data structures
//! such as a Treiber Stack, the **ABA problem** frequently arises. The traditional mitigation involves
//! pairing the physical pointer with a generation tag, updating both atomically.
//!
//! However, this incurs CPU architecture constraints:
//! 1. **64-bit Systems with High Virtual Addresses (52/57-bit)**:
//!    Modern operating systems on x86_64 (using Intel 5-level paging for 57-bit address space) or AArch64
//!    (using 52-bit virtual addresses) utilize pointer spaces beyond the typical 48-bit region. Assumed
//!    48-bit address layout limits lead to pointer truncation and severe wild-pointer crashes.
//!    This module splits the 64-bit word dynamically: reserving the **lower 56 bits** for the physical pointer
//!    (covering the entire `007f_ffff_ffff_ffff` user-space boundary) and the **upper 8 bits** for the tag.
//!    This provides absolute pointer integrity across all current server environments.
//! 2. **32-bit Systems**:
//!    Pointer width is 32 bits. We pair it with a 32-bit generation tag to form a double-word 64-bit composite.
//!    This leverages hardware-level 64-bit atomic operations (such as `cmpxchg8b` on x86 or `ldrd/strd` on ARMv7)
//!    to complete CAS transitions natively, without making raw address size assumptions.
//! 3. **Non-AtomicFallback Systems**:
//!    Under highly customized secure hypervisors (using full MTE tagging) or extremely constrained microcontrollers
//!    without native 64-bit atomics, the implementation seamlessly falls back to standard Mutex synchronization.
//!    This guarantees 100% compilation safety without sacrificing API consistency or memory efficiency.
use core::fmt;
use core::ptr::NonNull;
use core::sync::atomic::Ordering;

use crate::{Tag, ptr::{Ptr, TaggedPtr}};

// --- Platform Routing Conditional Compile Sections ---

#[cfg(all(target_pointer_width = "64", not(atomic_fallback)))]
mod ptr64;

#[cfg(all(target_pointer_width = "64", not(atomic_fallback)))]
use ptr64::AtomicTaggedPtrImpl;

#[cfg(all(target_pointer_width = "64", not(atomic_fallback)))]
pub use ptr64::TAG_MASK;

#[cfg(all(target_pointer_width = "32", not(atomic_fallback)))]
mod ptr32;

#[cfg(all(target_pointer_width = "32", not(atomic_fallback)))]
use ptr32::AtomicTaggedPtrImpl;

#[cfg(all(target_pointer_width = "32", not(atomic_fallback)))]
pub use ptr32::TAG_MASK;

#[cfg(atomic_fallback)]
mod fallback;

#[cfg(atomic_fallback)]
pub use fallback::TAG_MASK;

#[cfg(atomic_fallback)]
use fallback::AtomicTaggedPtrImpl;


/// Type alias representing the result of atomic compare and exchange operations.
pub type TaggedPtrResult<T> = Result<TaggedPtr<T>, TaggedPtr<T>>;

/// Type alias for raw results returned by internal platform implementations.
pub(crate) type RawTaggedPtrResult<T> =
    Result<(Option<NonNull<T>>, Tag), (Option<NonNull<T>>, Tag)>;

/// A platform-adaptive atomic tagged pointer supporting thread-safe ABA protection.
pub struct AtomicTaggedPtr<T> {
    inner: AtomicTaggedPtrImpl<T>,
}

// Safety: AtomicTaggedPtr is an atomic synchronizer wrapping pointer locations, safe to send/share across threads.
unsafe impl<T> Send for AtomicTaggedPtr<T> {}
unsafe impl<T> Sync for AtomicTaggedPtr<T> {}

impl<T> AtomicTaggedPtr<T> {
    /// Creates a new `AtomicTaggedPtr` initialized with the given tagged pointer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::ptr::NonNull;
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    ///
    /// let value = 42;
    /// let ptr = NonNull::new(&value as *const i32 as *mut i32);
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr, Tag::new(0)));
    /// ```
    #[inline]
    pub fn new(val: impl Into<TaggedPtr<T>>) -> Self {
        let val = val.into();
        Self {
            inner: AtomicTaggedPtrImpl::new(val.ptr.option(), val.tag),
        }
    }

    /// Loads the current values of the pointer and tag atomically.
    ///
    /// # Panics
    ///
    /// Panics if `order` is `Release` or `AcqRel`.
    #[inline]
    pub fn load(&self, order: Ordering) -> TaggedPtr<T> {
        let (raw_ptr, tag) = self.inner.load(order);
        TaggedPtr {
            ptr: Ptr::new(raw_ptr),
            tag,
        }
    }

    /// Stores a new pointer and tag atomically.
    ///
    /// # Panics
    ///
    /// Panics if `order` is `Acquire` or `AcqRel`.
    #[inline]
    pub fn store(&self, val: impl Into<TaggedPtr<T>>, order: Ordering) {
        let val = val.into();
        self.inner.store(val.ptr.option(), val.tag, order);
    }

    /// Stores a value into the pointer if the current value is the same as the `current` value.
    ///
    /// The return value is a result that indicates whether the new value was written and contains
    /// the previous value. On success, this value is guaranteed to be equal to `current`.
    ///
    /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory model of this operation.
    /// The `success` ordering describes the memory ordering of the read-modify-write operation if the comparison
    /// succeeds. The `failure` ordering describes the memory ordering of the read operation if the comparison fails.
    ///
    /// # Panics
    ///
    /// Panics if `failure` is `Release` or `AcqRel`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    /// use std::ptr::NonNull;
    ///
    /// let val1 = 10;
    /// let val2 = 20;
    /// let ptr1 = NonNull::new(&val1 as *const i32 as *mut i32);
    /// let ptr2 = NonNull::new(&val2 as *const i32 as *mut i32);
    ///
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr1, Tag::new(1)));
    ///
    /// // Successful compare_exchange
    /// let res = atom.compare_exchange(
    ///     TaggedPtr::new(ptr1, Tag::new(1)),
    ///     TaggedPtr::new(ptr2, Tag::new(2)),
    ///     Ordering::SeqCst,
    ///     Ordering::SeqCst,
    /// );
    /// assert_eq!(res, Ok(TaggedPtr::new(ptr1, Tag::new(1))));
    /// assert_eq!(atom.load(Ordering::SeqCst), TaggedPtr::new(ptr2, Tag::new(2)));
    ///
    /// // Failed compare_exchange
    /// let res = atom.compare_exchange(
    ///     TaggedPtr::new(ptr1, Tag::new(1)),
    ///     TaggedPtr::new(ptr1, Tag::new(3)),
    ///     Ordering::SeqCst,
    ///     Ordering::SeqCst,
    /// );
    /// assert_eq!(res, Err(TaggedPtr::new(ptr2, Tag::new(2))));
    /// ```
    #[inline]
    pub fn compare_exchange(
        &self,
        current: impl Into<TaggedPtr<T>>,
        new: impl Into<TaggedPtr<T>>,
        success: Ordering,
        failure: Ordering,
    ) -> TaggedPtrResult<T> {
        let current = current.into();
        let new = new.into();
        match self.inner.compare_exchange(
            (current.ptr.option(), current.tag),
            (new.ptr.option(), new.tag),
            success,
            failure,
        ) {
            Ok((raw_ptr, tag)) => Ok(TaggedPtr {
                ptr: Ptr::new(raw_ptr),
                tag,
            }),
            Err((raw_ptr, tag)) => Err(TaggedPtr {
                ptr: Ptr::new(raw_ptr),
                tag,
            }),
        }
    }

    /// Stores a value into the pointer if the current value is the same as the `current` value.
    ///
    /// Unlike [`compare_exchange`], this function is allowed to spuriously fail even when the comparison
    /// succeeds, which can result in more efficient code generation on architectures that use load-link/store-conditional
    /// instructions (like ARM).
    ///
    /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory model of this operation.
    /// The `success` ordering describes the memory ordering of the read-modify-write operation if the comparison
    /// succeeds. The `failure` ordering describes the memory ordering of the read operation if the comparison fails.
    ///
    /// # Panics
    ///
    /// Panics if `failure` is `Release` or `AcqRel`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    /// use std::ptr::NonNull;
    ///
    /// let val1 = 10;
    /// let val2 = 20;
    /// let ptr1 = NonNull::new(&val1 as *const i32 as *mut i32);
    /// let ptr2 = NonNull::new(&val2 as *const i32 as *mut i32);
    ///
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr1, Tag::new(1)));
    ///
    /// let mut old = atom.load(Ordering::Relaxed);
    /// loop {
    ///     let new = TaggedPtr::new(ptr2, Tag::new(2));
    ///     match atom.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::SeqCst) {
    ///         Ok(_) => break,
    ///         Err(actual) => old = actual,
    ///     }
    /// }
    /// assert_eq!(atom.load(Ordering::SeqCst), TaggedPtr::new(ptr2, Tag::new(2)));
    /// ```
    #[inline]
    pub fn compare_exchange_weak(
        &self,
        current: impl Into<TaggedPtr<T>>,
        new: impl Into<TaggedPtr<T>>,
        success: Ordering,
        failure: Ordering,
    ) -> TaggedPtrResult<T> {
        let current = current.into();
        let new = new.into();
        match self.inner.compare_exchange_weak(
            (current.ptr.option(), current.tag),
            (new.ptr.option(), new.tag),
            success,
            failure,
        ) {
            Ok((raw_ptr, tag)) => Ok(TaggedPtr {
                ptr: Ptr::new(raw_ptr),
                tag,
            }),
            Err((raw_ptr, tag)) => Err(TaggedPtr {
                ptr: Ptr::new(raw_ptr),
                tag,
            }),
        }
    }

    /// Atomically exchanges the value and returns the old value.
    ///
    /// This method replaces the stored pointer and tag with `val` and returns the previously
    /// stored `TaggedPtr`.
    ///
    /// # Panics
    ///
    /// Panics if `order` is `AcqRel`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    /// use std::ptr::NonNull;
    ///
    /// let val1 = 10;
    /// let val2 = 20;
    /// let ptr1 = NonNull::new(&val1 as *const i32 as *mut i32);
    /// let ptr2 = NonNull::new(&val2 as *const i32 as *mut i32);
    ///
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr1, Tag::new(1)));
    /// let old = atom.swap(TaggedPtr::new(ptr2, Tag::new(2)), Ordering::SeqCst);
    ///
    /// assert_eq!(old, TaggedPtr::new(ptr1, Tag::new(1)));
    /// assert_eq!(atom.load(Ordering::SeqCst), TaggedPtr::new(ptr2, Tag::new(2)));
    /// ```
    #[inline]
    pub fn swap(&self, val: impl Into<TaggedPtr<T>>, order: Ordering) -> TaggedPtr<T> {
        let val = val.into();
        let (raw_ptr, tag) = self.inner.swap(val.ptr.option(), val.tag, order);
        TaggedPtr {
            ptr: Ptr::new(raw_ptr),
            tag,
        }
    }

    /// Consumes the atomic and returns the inner value.
    ///
    /// This is safe because consuming `self` guarantees no other threads can concurrently
    /// access it, and therefore no synchronization is required.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::ptr::NonNull;
    ///
    /// let val = 42;
    /// let ptr = NonNull::new(&val as *const i32 as *mut i32);
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr, Tag::new(100)));
    ///
    /// let inner = atom.into_inner();
    /// assert_eq!(inner.ptr.option(), ptr);
    /// assert_eq!(inner.tag.value(), 100);
    /// ```
    #[inline]
    pub fn into_inner(self) -> TaggedPtr<T> {
        let (raw_ptr, tag) = self.inner.into_inner();
        TaggedPtr {
            ptr: Ptr::new(raw_ptr),
            tag,
        }
    }

    /// Fetches the value, applies a function to it, and attempts to store the result.
    ///
    /// This is a convenience method for compare-and-swap loops. The function `f` is called with
    /// the current value, and can return `Some(new_value)` to attempt a CAS, or `None` to abort the update.
    ///
    /// On success, it returns `Ok(old_value)`. On failure (when `f` returns `None`), it returns `Err(old_value)`.
    ///
    /// `fetch_update` takes two [`Ordering`] arguments: `set_order` for the write ordering, and `fetch_order` for
    /// the read/load ordering.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::default();
    ///
    /// // Increment the tag only if the tag is less than 5
    /// let res = atom.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |curr| {
    ///     if curr.tag.value() < 5 {
    ///         Some(curr.with_tag(curr.tag.wrapping_add(1)))
    ///     } else {
    ///         None
    ///     }
    /// });
    ///
    /// assert!(res.is_ok());
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 1);
    /// ```
    #[inline]
    pub fn fetch_update<F>(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        mut f: F,
    ) -> Result<TaggedPtr<T>, TaggedPtr<T>>
    where
        F: FnMut(TaggedPtr<T>) -> Option<TaggedPtr<T>>,
    {
        let mut prev = self.load(fetch_order);
        while let Some(next) = f(prev) {
            match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
                Ok(x) => return Ok(x),
                Err(next_prev) => prev = next_prev,
            }
        }
        Err(prev)
    }

    /// Atomically adds `val` to the tag of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::default();
    /// let old = atom.fetch_add_tag(5, Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 0);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 5);
    /// ```
    #[inline]
    pub fn fetch_add_tag(&self, val: usize, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(prev.tag.wrapping_add(val)))
        }).unwrap()
    }

    /// Atomically subtracts `val` from the tag of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::new(TaggedPtr::new(None, Tag::new(10)));
    /// let old = atom.fetch_sub_tag(3, Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 10);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 7);
    /// ```
    #[inline]
    pub fn fetch_sub_tag(&self, val: usize, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(prev.tag.wrapping_sub(val)))
        }).unwrap()
    }

    /// Atomically performs a bitwise AND on the tag of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::new(TaggedPtr::new(None, Tag::new(0b1111)));
    /// let old = atom.fetch_and_tag(0b1010, Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 0b1111);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 0b1010);
    /// ```
    #[inline]
    pub fn fetch_and_tag(&self, val: usize, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(prev.tag & val))
        }).unwrap()
    }

    /// Atomically performs a bitwise OR on the tag of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::new(TaggedPtr::new(None, Tag::new(0b0101)));
    /// let old = atom.fetch_or_tag(0b1010, Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 0b0101);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 0b1111);
    /// ```
    #[inline]
    pub fn fetch_or_tag(&self, val: usize, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(prev.tag | val))
        }).unwrap()
    }

    /// Atomically performs a bitwise XOR on the tag of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::new(TaggedPtr::new(None, Tag::new(0b0101)));
    /// let old = atom.fetch_xor_tag(0b1100, Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 0b0101);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 0b1001);
    /// ```
    #[inline]
    pub fn fetch_xor_tag(&self, val: usize, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(prev.tag ^ val))
        }).unwrap()
    }

    /// Atomically updates the pointer part of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag, Ptr};
    /// use std::sync::atomic::Ordering;
    /// use std::ptr::NonNull;
    ///
    /// let val1 = 42;
    /// let val2 = 84;
    /// let ptr1 = NonNull::new(&val1 as *const i32 as *mut i32);
    /// let ptr2 = NonNull::new(&val2 as *const i32 as *mut i32);
    ///
    /// let atom = AtomicTaggedPtr::new(TaggedPtr::new(ptr1, Tag::new(10)));
    /// let old = atom.fetch_set_ptr(ptr2, Ordering::SeqCst);
    /// assert_eq!(old.ptr.option(), ptr1);
    /// assert_eq!(old.tag.value(), 10);
    /// assert_eq!(atom.load(Ordering::SeqCst).ptr.option(), ptr2);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 10);
    /// ```
    #[inline]
    pub fn fetch_set_ptr(&self, ptr: impl Into<Ptr<T>>, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        let ptr = ptr.into();
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_ptr(ptr))
        }).unwrap()
    }

    /// Atomically updates the tag part of the current tagged pointer, returning the previous tagged pointer.
    ///
    /// This operation uses a CAS loop to perform the update.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use atomic_tagged_ptr::{AtomicTaggedPtr, TaggedPtr, Tag, Ptr};
    /// use std::sync::atomic::Ordering;
    ///
    /// let atom = AtomicTaggedPtr::<i32>::default();
    /// let old = atom.fetch_set_tag(Tag::new(99), Ordering::SeqCst);
    /// assert_eq!(old.tag.value(), 0);
    /// assert_eq!(atom.load(Ordering::SeqCst).tag.value(), 99);
    /// ```
    #[inline]
    pub fn fetch_set_tag(&self, tag: Tag, order: Ordering) -> TaggedPtr<T> {
        let (success, failure) = split_ordering(order);
        self.fetch_update(success, failure, |prev| {
            Some(prev.with_tag(tag))
        }).unwrap()
    }
}

/// Splits a single `Ordering` into success and failure orderings for CAS loops.
#[inline]
const fn split_ordering(order: Ordering) -> (Ordering, Ordering) {
    match order {
        Ordering::SeqCst => (Ordering::SeqCst, Ordering::SeqCst),
        Ordering::AcqRel => (Ordering::AcqRel, Ordering::Acquire),
        Ordering::Acquire => (Ordering::Acquire, Ordering::Acquire),
        Ordering::Release => (Ordering::Release, Ordering::Relaxed),
        Ordering::Relaxed => (Ordering::Relaxed, Ordering::Relaxed),
        _ => (order, Ordering::Relaxed),
    }
}

// --- Common Trait Implementations ---

impl<T> Default for AtomicTaggedPtr<T> {
    #[inline]
    fn default() -> Self {
        Self::new(TaggedPtr::default())
    }
}

impl<T> fmt::Debug for AtomicTaggedPtr<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Safe load under Relaxed ordering to capture debug state snapshot
        let val = self.load(Ordering::Relaxed);
        f.debug_struct("AtomicTaggedPtr")
            .field("pointer", &val.ptr)
            .field("tag", &val.tag)
            .finish()
    }
}

impl<T> From<TaggedPtr<T>> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(val: TaggedPtr<T>) -> Self {
        Self::new(val)
    }
}

impl<T> From<(Ptr<T>, Tag)> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(val: (Ptr<T>, Tag)) -> Self {
        Self::new(val)
    }
}

impl<T> From<Ptr<T>> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(ptr: Ptr<T>) -> Self {
        Self::new(TaggedPtr::new(ptr, Tag::default()))
    }
}

impl<T> From<Option<NonNull<T>>> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(ptr: Option<NonNull<T>>) -> Self {
        Self::new(TaggedPtr::new(ptr, Tag::default()))
    }
}

impl<T> From<NonNull<T>> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(ptr: NonNull<T>) -> Self {
        Self::new(TaggedPtr::new(ptr, Tag::default()))
    }
}

impl<T> From<*const T> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(ptr: *const T) -> Self {
        Self::new(TaggedPtr::new(ptr, Tag::default()))
    }
}

impl<T> From<*mut T> for AtomicTaggedPtr<T> {
    #[inline]
    fn from(ptr: *mut T) -> Self {
        Self::new(TaggedPtr::new(ptr, Tag::default()))
    }
}

#[cfg(all(test, feature = "std"))]
mod tests;