smallring 0.2.2

High-performance ring buffer with automatic stack/heap optimization | 高性能环形缓冲区,支持栈/堆自动优化
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
//! Atomic type ring buffer with specialized trait
//!
//! 为原子类型专门设计的环形缓冲区
//!
//! This module provides ring buffer implementation optimized for atomic types like AtomicU64.
//! Unlike generic ring buffers, atomic ring buffers don't move values but operate through
//! atomic load/store operations.
//!
//! 本模块提供针对原子类型(如 AtomicU64)优化的环形缓冲区实现。
//! 与通用环形缓冲区不同,原子环形缓冲区不移动值,而是通过原子 load/store 操作进行读写。

use super::core::RingBufCore;
use crate::shim::atomic::Ordering;
use alloc::vec::Vec;
use core::fmt;

#[cfg(feature = "loom")]
fn backoff() {
    loom::thread::yield_now();
}

#[cfg(not(feature = "loom"))]
fn backoff() {
    core::hint::spin_loop();
}

/// Trait for types that support atomic operations
///
/// 支持原子操作的类型 trait
///
/// This trait abstracts atomic operations to allow generic implementation
/// over different atomic types (AtomicU8, AtomicU64, AtomicUsize, etc.)
///
/// 此 trait 抽象了原子操作,允许在不同原子类型上实现泛型
/// (AtomicU8, AtomicU64, AtomicUsize 等)
pub trait AtomicElement: Send + Sync {
    /// The underlying primitive type
    ///
    /// 底层原始类型
    type Primitive: Copy;

    /// Load the value with specified ordering
    ///
    /// 使用指定的内存顺序加载值
    fn load(&self, order: Ordering) -> Self::Primitive;

    /// Store a value with specified ordering
    ///
    /// 使用指定的内存顺序存储值
    fn store(&self, val: Self::Primitive, order: Ordering);

    /// Swap the value and return the old value
    ///
    /// 交换值并返回旧值
    fn swap(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive;
}

// Implement for common atomic types
use crate::shim::atomic::{
    AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize, AtomicU8, AtomicU16,
    AtomicU32, AtomicU64, AtomicUsize,
};

macro_rules! impl_atomic_element {
    ($atomic:ty, $primitive:ty) => {
        impl AtomicElement for $atomic {
            type Primitive = $primitive;

            #[inline(always)]
            fn load(&self, order: Ordering) -> Self::Primitive {
                self.load(order)
            }

            #[inline(always)]
            fn store(&self, val: Self::Primitive, order: Ordering) {
                self.store(val, order);
            }

            #[inline(always)]
            fn swap(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive {
                self.swap(val, order)
            }
        }
    };
}

impl_atomic_element!(AtomicU8, u8);
impl_atomic_element!(AtomicU16, u16);
impl_atomic_element!(AtomicU32, u32);
impl_atomic_element!(AtomicU64, u64);
impl_atomic_element!(AtomicUsize, usize);
impl_atomic_element!(AtomicI8, i8);
impl_atomic_element!(AtomicI16, i16);
impl_atomic_element!(AtomicI32, i32);
impl_atomic_element!(AtomicI64, i64);
impl_atomic_element!(AtomicIsize, isize);
impl_atomic_element!(AtomicBool, bool);

/// Internal trait to dispatch push behavior based on OVERWRITE
///
/// 根据 OVERWRITE 分发 push 行为的内部 trait
pub trait PushDispatch<T: AtomicElement, const N: usize, const OVERWRITE: bool> {
    /// The return type of the push operation
    ///
    /// push 操作的返回类型
    type PushOutput;

    /// The actual push implementation
    ///
    /// 实际的 push 实现
    fn push_impl(
        ringbuf: &AtomicRingBuf<T, N, OVERWRITE>,
        value: T::Primitive,
        order: Ordering,
    ) -> Self::PushOutput;
}

/// Marker struct for compile-time dispatch
///
/// 编译期分发的标记结构
pub struct PushMarker<const OVERWRITE: bool>;

impl<T: AtomicElement, const N: usize> PushDispatch<T, N, true> for PushMarker<true> {
    /// Returns `Some(T::Primitive)` if an element was overwritten, `None` otherwise
    ///
    /// 如果覆盖了元素则返回 `Some(T::Primitive)`,否则返回 `None`
    type PushOutput = Option<T::Primitive>;

    #[inline]
    fn push_impl(
        ringbuf: &AtomicRingBuf<T, N, true>,
        value: T::Primitive,
        order: Ordering,
    ) -> Self::PushOutput {
        // Reservation phase
        let write = ringbuf.core.write_idx().fetch_add(1, Ordering::Relaxed);
        let read = ringbuf.core.read_idx().load(Ordering::Acquire);

        // Check if we need to overwrite
        if write.wrapping_sub(read) >= ringbuf.core.capacity() {
            // Buffer was full - attempt to advance read index
            ringbuf
                .core
                .read_idx()
                .compare_exchange(
                    read,
                    read.wrapping_add(1),
                    Ordering::Release,
                    Ordering::Relaxed,
                )
                .ok();

            let index = write & ringbuf.core.mask();
            let old_value = unsafe {
                let slot = ringbuf.core.peek_at(index);
                slot.swap(value, order)
            };

            // Commit phase: wait for our turn
            loop {
                let commit = ringbuf.write_commit.load(Ordering::Acquire);
                if commit == write {
                    ringbuf
                        .write_commit
                        .store(write.wrapping_add(1), Ordering::Release);
                    return Some(old_value);
                }
                backoff();
            }
        } else {
            // Buffer not full - just store
            let index = write & ringbuf.core.mask();
            unsafe {
                let slot = ringbuf.core.peek_at(index);
                slot.store(value, order);
            }

            // Commit phase: wait for our turn
            loop {
                let commit = ringbuf.write_commit.load(Ordering::Acquire);
                if commit == write {
                    ringbuf
                        .write_commit
                        .store(write.wrapping_add(1), Ordering::Release);
                    return None;
                }
                backoff();
            }
        }
    }
}

impl<T: AtomicElement, const N: usize> PushDispatch<T, N, false> for PushMarker<false> {
    /// Returns `Ok(())` on success, or `Err(value)` if full
    ///
    /// 成功时返回 `Ok(())`,如果满则返回 `Err(value)`
    type PushOutput = Result<(), T::Primitive>;

    #[inline]
    fn push_impl(
        ringbuf: &AtomicRingBuf<T, N, false>,
        value: T::Primitive,
        order: Ordering,
    ) -> Self::PushOutput {
        loop {
            // Load read index first to ensure we don't see a "future" read index
            // combined with a "past" write index, which would cause false "full" detection.
            let read = ringbuf.core.read_idx().load(Ordering::Acquire);
            let write = ringbuf.core.write_idx().load(Ordering::Relaxed);

            if write.wrapping_sub(read) >= ringbuf.core.capacity() {
                return Err(value);
            }

            // Attempt to reserve a slot
            if ringbuf
                .core
                .write_idx()
                .compare_exchange(
                    write,
                    write.wrapping_add(1),
                    Ordering::Relaxed,
                    Ordering::Relaxed,
                )
                .is_ok()
            {
                // Reservation successful
                let index = write & ringbuf.core.mask();
                unsafe {
                    let slot = ringbuf.core.peek_at(index);
                    slot.store(value, order);
                }

                // Commit phase: wait for our turn
                loop {
                    let commit = ringbuf.write_commit.load(Ordering::Acquire);
                    if commit == write {
                        ringbuf
                            .write_commit
                            .store(write.wrapping_add(1), Ordering::Release);
                        return Ok(());
                    }
                    backoff();
                }
            }
            backoff();
        }
    }
}

/// Ring buffer specialized for atomic types
///
/// 为原子类型特化的环形缓冲区
///
/// # Type Parameters
/// - `T`: Atomic type implementing AtomicElement
/// - `N`: Stack capacity threshold
/// - `OVERWRITE`: Overwrite mode (true = overwrite oldest, false = reject when full)
///
/// # 类型参数
/// - `T`: 实现 AtomicElement 的原子类型
/// - `N`: 栈容量阈值
/// - `OVERWRITE`: 覆盖模式(true = 覆盖最旧的,false = 满时拒绝)
pub struct AtomicRingBuf<T: AtomicElement, const N: usize, const OVERWRITE: bool = true> {
    core: RingBufCore<T, N>,
    write_commit: AtomicUsize,
}

impl<T: AtomicElement, const N: usize, const OVERWRITE: bool> AtomicRingBuf<T, N, OVERWRITE> {
    /// Create a new atomic ring buffer
    ///
    /// 创建新的原子环形缓冲区
    #[inline]
    pub fn new(capacity: usize) -> Self
    where
        T: Default,
    {
        let uninit = Self::new_uninit(capacity);
        unsafe {
            for i in 0..uninit.core.capacity() {
                uninit.core.write_at(i, T::default());
            }
        }
        uninit
    }

    /// Create a new atomic ring buffer with uninitialized elements
    ///
    /// 创建新的原子环形缓冲区,元素未初始化
    #[inline]
    pub fn new_uninit(capacity: usize) -> Self {
        Self {
            core: RingBufCore::new(capacity),
            write_commit: AtomicUsize::new(0),
        }
    }

    /// Get capacity
    ///
    /// 获取容量
    #[inline]
    pub fn capacity(&self) -> usize {
        self.core.capacity()
    }

    /// Get current length
    ///
    /// 获取当前长度
    #[inline]
    pub fn len(&self) -> usize {
        let commit = self.write_commit.load(Ordering::Acquire);
        let read = self.core.read_idx().load(Ordering::Acquire);
        commit.wrapping_sub(read).min(self.core.capacity())
    }

    /// Check if empty
    ///
    /// 检查是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        let commit = self.write_commit.load(Ordering::Acquire);
        let read = self.core.read_idx().load(Ordering::Acquire);
        commit == read
    }

    /// Check if full
    ///
    /// 检查是否已满
    #[inline]
    pub fn is_full(&self) -> bool {
        self.core.is_full()
    }

    /// Push a value into the buffer
    ///
    /// 向缓冲区推送一个值
    ///
    /// # Behavior
    ///
    /// - **Overwrite mode (OVERWRITE=true)**: Always succeeds. Returns `Some(T::Primitive)` if an element was overwritten, `None` otherwise.
    /// - **Non-overwrite mode (OVERWRITE=false)**: Returns `Err(value)` if buffer is full, `Ok(())` otherwise.
    ///
    /// # 行为
    ///
    /// - **覆盖模式 (OVERWRITE=true)**: 总是成功。如果覆盖了元素则返回 `Some(T::Primitive)`,否则返回 `None`。
    /// - **非覆盖模式 (OVERWRITE=false)**: 如果缓冲区满则返回 `Err(value)`,否则返回 `Ok(())`。
    ///
    /// # Examples
    ///
    /// ```rust
    /// use smallring::atomic::{AtomicRingBuf, AtomicElement};
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// // Overwrite mode
    /// let buf_ow: AtomicRingBuf<AtomicU64, 32, true> = AtomicRingBuf::new(2);
    /// assert_eq!(buf_ow.push(1, Ordering::Relaxed), None);
    /// assert_eq!(buf_ow.push(2, Ordering::Relaxed), None);
    /// assert_eq!(buf_ow.push(3, Ordering::Relaxed), Some(1)); // Overwrote 1
    ///
    /// // Non-overwrite mode
    /// let buf_no: AtomicRingBuf<AtomicU64, 32, false> = AtomicRingBuf::new(2);
    /// assert_eq!(buf_no.push(1, Ordering::Relaxed), Ok(()));
    /// assert_eq!(buf_no.push(2, Ordering::Relaxed), Ok(()));
    /// assert_eq!(buf_no.push(3, Ordering::Relaxed), Err(3)); // Full
    /// ```
    #[inline(always)]
    pub fn push(
        &self,
        value: T::Primitive,
        order: Ordering,
    ) -> <PushMarker<OVERWRITE> as PushDispatch<T, N, OVERWRITE>>::PushOutput
    where
        PushMarker<OVERWRITE>: PushDispatch<T, N, OVERWRITE>,
    {
        PushMarker::<OVERWRITE>::push_impl(self, value, order)
    }

    /// Pop a value from the buffer
    ///
    /// 从缓冲区弹出一个值
    #[inline]
    pub fn pop(&self, order: Ordering) -> Option<T::Primitive> {
        let read = self.core.read_idx().load(Ordering::Relaxed);
        let commit = self.write_commit.load(Ordering::Acquire);

        if read == commit {
            return None;
        }

        let index = read & self.core.mask();
        let value = unsafe {
            let slot = self.core.peek_at(index);
            slot.load(order)
        };

        self.core
            .read_idx()
            .store(read.wrapping_add(1), Ordering::Release);
        Some(value)
    }

    /// Peek at the next value without removing it
    ///
    /// 查看下一个值但不移除
    #[inline]
    pub fn peek(&self, order: Ordering) -> Option<T::Primitive> {
        let read = self.core.read_idx().load(Ordering::Acquire);
        let commit = self.write_commit.load(Ordering::Acquire);

        if read == commit {
            return None;
        }

        let index = read & self.core.mask();
        unsafe {
            let slot = self.core.peek_at(index);
            Some(slot.load(order))
        }
    }

    /// Access a slot directly by offset from read position
    ///
    /// 通过从读位置的偏移直接访问槽位
    ///
    /// # Safety
    /// Caller must ensure offset < len()
    #[inline]
    pub unsafe fn get_unchecked(&self, offset: usize) -> &T {
        let read = self.core.read_idx().load(Ordering::Acquire);
        let index = read.wrapping_add(offset) & self.core.mask();
        // SAFETY: Caller guarantees offset < len(), so index is valid
        unsafe { self.core.peek_at(index) }
    }

    /// Clear all elements from the buffer
    ///
    /// 清空缓冲区中的所有元素
    ///
    /// Resets the buffer to empty state by synchronizing read and write indices.
    ///
    /// 通过同步读写索引将缓冲区重置为空状态。
    ///
    /// # Examples
    ///
    /// ```rust
    /// use smallring::atomic::AtomicRingBuf;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);
    /// buf.push(1, Ordering::Relaxed);
    /// buf.push(2, Ordering::Relaxed);
    /// assert_eq!(buf.len(), 2);
    ///
    /// buf.clear();
    /// assert_eq!(buf.len(), 0);
    /// assert!(buf.is_empty());
    /// ```
    #[inline]
    pub fn clear(&self) {
        let commit = self.write_commit.load(Ordering::Acquire);
        self.core.read_idx().store(commit, Ordering::Release);
    }

    /// Read all valid elements from the buffer
    ///
    /// 读取缓冲区中所有有效元素
    ///
    /// Returns a vector of all elements currently in the buffer, in FIFO order.
    /// This does not remove elements from the buffer.
    ///
    /// 返回缓冲区中当前所有元素的向量,按 FIFO 顺序排列。
    /// 此操作不会从缓冲区中移除元素。
    ///
    /// # Examples
    ///
    /// ```rust
    /// use smallring::atomic::AtomicRingBuf;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);
    /// buf.push(1, Ordering::Relaxed);
    /// buf.push(2, Ordering::Relaxed);
    /// buf.push(3, Ordering::Relaxed);
    ///
    /// let values = buf.read_all(Ordering::Acquire);
    /// assert_eq!(values, vec![1, 2, 3]);
    /// assert_eq!(buf.len(), 3); // Elements still in buffer
    /// ```
    #[inline]
    pub fn read_all(&self, order: Ordering) -> Vec<T::Primitive> {
        let read = self.core.read_idx().load(Ordering::Acquire);
        let commit = self.write_commit.load(Ordering::Acquire);

        let len = commit.wrapping_sub(read).min(self.core.capacity());
        let mut values = Vec::with_capacity(len);

        for i in 0..len {
            let index = read.wrapping_add(i) & self.core.mask();
            let value = unsafe {
                let slot = self.core.peek_at(index);
                slot.load(order)
            };
            values.push(value);
        }

        values
    }

    /// Get an iterator over elements in the buffer
    ///
    /// 获取缓冲区元素的迭代器
    ///
    /// Returns an iterator that yields references to atomic elements in FIFO order.
    /// The iterator provides read-only access to the underlying atomic values.
    ///
    /// 返回一个按 FIFO 顺序产生原子元素引用的迭代器。
    /// 迭代器提供对底层原子值的只读访问。
    ///
    /// # Examples
    ///
    /// ```rust
    /// use smallring::atomic::AtomicRingBuf;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);
    /// buf.push(1, Ordering::Relaxed);
    /// buf.push(2, Ordering::Relaxed);
    /// buf.push(3, Ordering::Relaxed);
    ///
    /// let values: Vec<u64> = buf.iter()
    ///     .map(|atom| atom.load(Ordering::Acquire))
    ///     .collect();
    /// assert_eq!(values, vec![1, 2, 3]);
    /// ```
    #[inline]
    pub fn iter(&self) -> AtomicIter<'_, T, N, OVERWRITE> {
        let read = self.core.read_idx().load(Ordering::Acquire);
        let commit = self.write_commit.load(Ordering::Acquire);
        let len = commit.wrapping_sub(read).min(self.core.capacity());

        AtomicIter {
            ringbuf: self,
            start: read,
            remaining: len,
        }
    }
}

/// Iterator over atomic ring buffer elements
///
/// 原子环形缓冲区元素的迭代器
pub struct AtomicIter<'a, T: AtomicElement, const N: usize, const OVERWRITE: bool> {
    ringbuf: &'a AtomicRingBuf<T, N, OVERWRITE>,
    start: usize,
    remaining: usize,
}

impl<'a, T: AtomicElement, const N: usize, const OVERWRITE: bool> Iterator
    for AtomicIter<'a, T, N, OVERWRITE>
{
    type Item = &'a T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        let index = self.start & self.ringbuf.core.mask();
        let element = unsafe { self.ringbuf.core.peek_at(index) };

        self.start = self.start.wrapping_add(1);
        self.remaining -= 1;
        Some(element)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, T: AtomicElement, const N: usize, const OVERWRITE: bool> ExactSizeIterator
    for AtomicIter<'a, T, N, OVERWRITE>
{
    #[inline]
    fn len(&self) -> usize {
        self.remaining
    }
}

/// Trait for atomic numeric operations on ring buffer elements
///
/// 环形缓冲区元素的原子数值操作 trait
///
/// This trait provides atomic arithmetic operations for numeric atomic types.
///
/// 此 trait 为数值原子类型提供原子算术操作。
pub trait AtomicNumeric: AtomicElement {
    /// Atomically add to the value at the given offset from read position
    ///
    /// 原子地将值加到从读位置开始的给定偏移处
    fn fetch_add(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive;

    /// Atomically subtract from the value at the given offset from read position
    ///
    /// 原子地从给定偏移处的值减去
    fn fetch_sub(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive;
}

macro_rules! impl_atomic_numeric {
    ($atomic:ty, $primitive:ty) => {
        impl AtomicNumeric for $atomic {
            #[inline]
            fn fetch_add(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive {
                self.fetch_add(val, order)
            }

            #[inline]
            fn fetch_sub(&self, val: Self::Primitive, order: Ordering) -> Self::Primitive {
                self.fetch_sub(val, order)
            }
        }
    };
}

impl_atomic_numeric!(AtomicU8, u8);
impl_atomic_numeric!(AtomicU16, u16);
impl_atomic_numeric!(AtomicU32, u32);
impl_atomic_numeric!(AtomicU64, u64);
impl_atomic_numeric!(AtomicUsize, usize);
impl_atomic_numeric!(AtomicI8, i8);
impl_atomic_numeric!(AtomicI16, i16);
impl_atomic_numeric!(AtomicI32, i32);
impl_atomic_numeric!(AtomicI64, i64);
impl_atomic_numeric!(AtomicIsize, isize);

impl<T: AtomicElement + AtomicNumeric, const N: usize, const OVERWRITE: bool>
    AtomicRingBuf<T, N, OVERWRITE>
{
    /// Atomically add to an element at the given offset from read position
    ///
    /// 原子地将值加到从读位置开始的给定偏移处的元素
    ///
    /// # Safety
    /// Caller must ensure offset < len()
    ///
    /// # Examples
    ///
    /// ```rust
    /// use smallring::atomic::AtomicRingBuf;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);
    /// buf.push(10, Ordering::Relaxed);
    /// buf.push(20, Ordering::Relaxed);
    ///
    /// // Add 5 to the first element
    /// let old = unsafe { buf.fetch_add_at(0, 5, Ordering::Relaxed) };
    /// assert_eq!(old, 10);
    /// assert_eq!(buf.peek(Ordering::Acquire).unwrap(), 15);
    /// ```
    #[inline]
    pub unsafe fn fetch_add_at(
        &self,
        offset: usize,
        val: T::Primitive,
        order: Ordering,
    ) -> T::Primitive {
        let element = unsafe { self.get_unchecked(offset) };
        element.fetch_add(val, order)
    }

    /// Atomically subtract from an element at the given offset from read position
    ///
    /// 原子地从读位置开始的给定偏移处的元素减去值
    ///
    /// # Safety
    /// Caller must ensure offset < len()
    #[inline]
    pub unsafe fn fetch_sub_at(
        &self,
        offset: usize,
        val: T::Primitive,
        order: Ordering,
    ) -> T::Primitive {
        let element = unsafe { self.get_unchecked(offset) };
        element.fetch_sub(val, order)
    }
}

impl<T: AtomicElement, const N: usize, const OVERWRITE: bool> fmt::Debug
    for AtomicRingBuf<T, N, OVERWRITE>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AtomicRingBuf")
            .field("capacity", &self.core.capacity())
            .field("len", &self.core.len())
            .field("is_empty", &self.core.is_empty())
            .field("is_full", &self.core.is_full())
            .field("overwrite_mode", &OVERWRITE)
            .finish()
    }
}

unsafe impl<T: AtomicElement, const N: usize, const OVERWRITE: bool> Send
    for AtomicRingBuf<T, N, OVERWRITE>
{
}
unsafe impl<T: AtomicElement, const N: usize, const OVERWRITE: bool> Sync
    for AtomicRingBuf<T, N, OVERWRITE>
{
}

#[cfg(all(test, not(feature = "loom")))]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64};

    #[test]
    fn test_basic_push_pop() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(4);

        buf.push(1, Ordering::Relaxed);
        buf.push(2, Ordering::Relaxed);
        buf.push(3, Ordering::Relaxed);

        assert_eq!(buf.len(), 3);
        assert_eq!(buf.pop(Ordering::Relaxed), Some(1));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(2));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(3));
        assert_eq!(buf.pop(Ordering::Relaxed), None);
    }

    #[test]
    fn test_basic_overwrite_mode() {
        let buf: AtomicRingBuf<AtomicU64, 32, true> = AtomicRingBuf::new(2);

        assert_eq!(buf.push(1, Ordering::Relaxed), None);
        assert_eq!(buf.push(2, Ordering::Relaxed), None);
        assert_eq!(buf.push(3, Ordering::Relaxed), Some(1));

        assert_eq!(buf.len(), 2);
        assert_eq!(buf.pop(Ordering::Relaxed), Some(2));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(3));
    }

    #[test]
    fn test_basic_non_overwrite_mode() {
        let buf: AtomicRingBuf<AtomicU64, 32, false> = AtomicRingBuf::new(2);

        assert_eq!(buf.push(1, Ordering::Relaxed), Ok(()));
        assert_eq!(buf.push(2, Ordering::Relaxed), Ok(()));
        assert_eq!(buf.push(3, Ordering::Relaxed), Err(3));

        assert_eq!(buf.len(), 2);
        assert!(buf.is_full());
    }

    #[test]
    fn test_basic_peek() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(4);

        assert_eq!(buf.peek(Ordering::Relaxed), None);

        buf.push(42, Ordering::Relaxed);
        assert_eq!(buf.peek(Ordering::Relaxed), Some(42));
        assert_eq!(buf.len(), 1);

        buf.push(99, Ordering::Relaxed);
        assert_eq!(buf.peek(Ordering::Relaxed), Some(42));

        buf.pop(Ordering::Relaxed);
        assert_eq!(buf.peek(Ordering::Relaxed), Some(99));
    }

    #[test]
    fn test_basic_clear() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);

        buf.push(1, Ordering::Relaxed);
        buf.push(2, Ordering::Relaxed);
        buf.push(3, Ordering::Relaxed);
        assert_eq!(buf.len(), 3);

        buf.clear();
        assert_eq!(buf.len(), 0);
        assert!(buf.is_empty());

        buf.push(10, Ordering::Relaxed);
        assert_eq!(buf.pop(Ordering::Relaxed), Some(10));
    }

    #[test]
    fn test_basic_capacity() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);
        assert_eq!(buf.capacity(), 8);

        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(5);
        assert_eq!(buf.capacity(), 8);
    }

    #[test]
    fn test_basic_is_empty_full() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(2);

        assert!(buf.is_empty());
        assert!(!buf.is_full());

        buf.push(1, Ordering::Relaxed);
        assert!(!buf.is_empty());
        assert!(!buf.is_full());

        buf.push(2, Ordering::Relaxed);
        assert!(!buf.is_empty());
        assert!(buf.is_full());

        buf.pop(Ordering::Relaxed);
        assert!(!buf.is_empty());
        assert!(!buf.is_full());

        buf.pop(Ordering::Relaxed);
        assert!(buf.is_empty());
        assert!(!buf.is_full());
    }

    #[test]
    fn test_basic_read_all() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);

        buf.push(1, Ordering::Relaxed);
        buf.push(2, Ordering::Relaxed);
        buf.push(3, Ordering::Relaxed);

        let values = buf.read_all(Ordering::Acquire);
        assert_eq!(values, vec![1, 2, 3]);
        assert_eq!(buf.len(), 3);
    }

    #[test]
    fn test_basic_iter() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);

        buf.push(10, Ordering::Relaxed);
        buf.push(20, Ordering::Relaxed);
        buf.push(30, Ordering::Relaxed);

        let values: Vec<u64> = buf
            .iter()
            .map(|atom| atom.load(Ordering::Acquire))
            .collect();
        assert_eq!(values, vec![10, 20, 30]);
    }

    #[test]
    fn test_basic_atomic_u32() {
        let buf: AtomicRingBuf<AtomicU32, 32> = AtomicRingBuf::new(4);

        buf.push(100u32, Ordering::Relaxed);
        buf.push(200u32, Ordering::Relaxed);

        assert_eq!(buf.pop(Ordering::Relaxed), Some(100u32));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(200u32));
    }

    #[test]
    fn test_basic_atomic_bool() {
        let buf: AtomicRingBuf<AtomicBool, 32> = AtomicRingBuf::new(4);

        buf.push(true, Ordering::Relaxed);
        buf.push(false, Ordering::Relaxed);
        buf.push(true, Ordering::Relaxed);

        assert_eq!(buf.pop(Ordering::Relaxed), Some(true));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(false));
        assert_eq!(buf.pop(Ordering::Relaxed), Some(true));
    }

    #[test]
    fn test_basic_fetch_add_at() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);

        buf.push(10, Ordering::Relaxed);
        buf.push(20, Ordering::Relaxed);
        buf.push(30, Ordering::Relaxed);

        let old = unsafe { buf.fetch_add_at(0, 5, Ordering::Relaxed) };
        assert_eq!(old, 10);
        assert_eq!(buf.peek(Ordering::Acquire).unwrap(), 15);

        let old = unsafe { buf.fetch_add_at(1, 100, Ordering::Relaxed) };
        assert_eq!(old, 20);
    }

    #[test]
    fn test_basic_fetch_sub_at() {
        let buf: AtomicRingBuf<AtomicU64, 32> = AtomicRingBuf::new(8);

        buf.push(100, Ordering::Relaxed);
        buf.push(200, Ordering::Relaxed);

        let old = unsafe { buf.fetch_sub_at(0, 10, Ordering::Relaxed) };
        assert_eq!(old, 100);
        assert_eq!(buf.peek(Ordering::Acquire).unwrap(), 90);
    }
}