sliding-ring 0.1.1

Cache-friendly sliding ring buffer keyed to an anchor coordinate for ultra-low-latency workloads.
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
//! Fixed-size sliding ring buffer with anchor-preserving index math.
//!
//! `SlidingRing` keeps a circular array of 256 slots whose live window begins at an
//! anchor index. Moves are expressed as signed deltas; the ring rewires indices in
//! constant time and zeroes only the slots that newly enter the window (or the entire
//! ring when the delta exceeds the configured depth). Any domain-specific “anchor
//! coordinate” should be stored outside the ring and combined with offsets as needed.
//!
//! ## Model overview
//! - The ring tracks an anchor **index** (0-255). Store your absolute coordinate outside the ring.
//! - Moving by `k` adjusts the anchor index by `k mod 256` and clears exactly `|k|`
//!   freshly entered offsets (full reset when `|k| >= DEPTH`).
//! - [`SlidingRing::slot`] / [`SlidingRing::slot_mut`] accept offsets relative to the anchor, keeping lookups branch-free.
//! - [`SlidingRing::shift_by_keep_anchor`] preserves the newly entered anchor slot on backward moves
//!   so consumers can promote “next best” levels without losing their quantity.
//!
//! ## When to use it
//! Use this crate any time you need a cache-friendly sliding window tied to a
//! monotonically moving reference point and you can tolerate a fixed resolution
//! of 256 discrete offsets. Typical use-cases include:
//! - Aggregated orderbooks keyed by price ticks.
//! - Sliding time buckets for telemetry or rate-limiters.
//! - Game state timelines (e.g., ringed entity positions) where only a bounded
//!   horizon surrounding the current tick matters.
//!
//! ## When *not* to use it
//! - You need more than 256 distinct offsets at a time.
//! - The anchor jumps arbitrarily with sparse occupancy (use a hashmap instead).
//! - Slots require heap allocations on clear (prefer a structure that owns the
//!   heap nodes elsewhere and references them by ID).
//!
//! ## Slot requirements
//! The buffer stores `[T; 256]` where `T: Copy`. Pass the value that represents
//! your cleared state (often zero) to [`SlidingRing::new`]; the ring seeds every
//! slot with that value and reuses it whenever newly entered slots need to be
//! cleared. This keeps the API simple and removes the need for a custom trait.
//! For ultra-low latency users, the main primitive is
//! [`SlidingRing::slices_from_anchor`], which returns the two contiguous spans
//! that cover the ring starting at the anchor. Operate on those slices directly
//! with SIMD or unrolled loops when you need raw throughput. The iterator
//! variants (`iter*`) simply layer offset reporting on top of the
//! same index arithmetic and remain zero-cost.
//! Pair those slices with a stable SIMD helper (e.g., the [`wide`](https://crates.io/crates/wide)
//! crate demonstrated in `examples/simd_scan.rs`) to keep portable performance on stable Rust.
//!
//! ## Example
//!
//! ```rust
//! use sliding_ring::SlidingRing;
//!
//! #[derive(Debug, Copy, Clone)]
//! struct Level { qty: u64 }
//!
//! const DEPTH: u8 = 64;
//! let mut ring = SlidingRing::<Level, DEPTH>::new(Level { qty: 0 });
//! let mut best = 1_000i128;
//! let offset = 5u8;
//! ring.slot_mut(offset).qty = 10;
//! ring.shift_by(offset as i128);
//! best += offset as i128;
//! assert_eq!(ring.borrow_anchor().qty, 10);
//! ```
//!
//! ### Telemetry counter example
//!
//! ```rust
//! # use sliding_ring::{SlidingRing, Direction};
//! #[derive(Clone, Copy)]
//! struct Bucket { hits: u64 }
//! const DEPTH: u8 = 32;
//! let mut ring = SlidingRing::<Bucket, DEPTH>::new(Bucket { hits: 0 });
//! ring.slot_mut(5).hits += 1;
//! ring.slot_mut(6).hits += 3;
//! let sum: u64 = ring
//!     .iter_from_anchor(Direction::Forward)
//!     .map(|(_, bucket)| bucket.hits)
//!     .sum();
//! assert_eq!(sum, 4);
//! ```

use core::{fmt, marker::PhantomData};

/// Number of slots in the ring.
pub const RING_SIZE: usize = 256;
pub type RingIndex = u8;

/// Ring that slides over signed coordinates while keeping slot access O(1).
pub struct SlidingRing<T: Copy, const DEPTH: u8> {
    slots: [T; RING_SIZE],
    zero: T,
    anchor: RingIndex,
}

impl<T: Copy, const DEPTH: u8> SlidingRing<T, DEPTH> {
    /// Create a new ring seeded with `zero`. The anchor index starts at 0.
    pub fn new(zero: T) -> Self {
        assert!(DEPTH > 0, "SlidingRing DEPTH must be at least 1");
        assert!(
            DEPTH as usize <= RING_SIZE,
            "SlidingRing DEPTH cannot exceed {}",
            RING_SIZE
        );
        Self {
            slots: [zero; RING_SIZE],
            zero,
            anchor: 0,
        }
    }

    /// Compile-time depth parameter exposed for downstream consumers.
    pub const DEPTH: u8 = DEPTH;

    #[inline(always)]
    const fn depth_usize() -> usize {
        DEPTH as usize
    }

    #[inline(always)]
    fn shift_internal(&mut self, delta: i128, keep_new_anchor: bool) {
        if delta == 0 {
            return;
        }
        let step = diff_mod_256(delta);
        self.anchor = self.anchor.wrapping_add(step);
        let depth = Self::depth_usize();
        let depth_limit = DEPTH as i128;
        if delta >= depth_limit || delta <= -depth_limit {
            self.slots.fill(self.zero);
            return;
        }
        let count = if delta > 0 {
            delta as usize
        } else {
            (-delta) as usize
        };
        debug_assert!(count < depth, "delta {} exceeds window {}", delta, DEPTH);
        if delta > 0 {
            let keep = depth - count;
            let mut idx = self.anchor.wrapping_add(keep as u8);
            for _ in 0..count {
                self.slots[idx as usize] = self.zero;
                idx = idx.wrapping_add(1);
            }
        } else {
            let mut idx = self.anchor;
            for i in 0..count {
                if keep_new_anchor && i == 0 {
                    idx = idx.wrapping_add(1);
                    continue;
                }
                self.slots[idx as usize] = self.zero;
                idx = idx.wrapping_add(1);
            }
        }
    }

    /// Borrow the slot at the anchor.
    #[inline(always)]
    pub fn borrow_anchor(&self) -> &T {
        &self.slots[self.anchor as usize]
    }

    /// Borrow the slot at the anchor mutably.
    #[inline(always)]
    pub fn borrow_anchor_mut(&mut self) -> &mut T {
        &mut self.slots[self.anchor as usize]
    }

    /// Immutable access to the slot for `offset` (measured from the anchor).
    #[inline(always)]
    pub fn slot(&self, offset: RingIndex) -> &T {
        debug_assert!(
            (offset as usize) < Self::depth_usize(),
            "offset {} is outside the configured depth ({})",
            offset,
            DEPTH
        );
        let idx = self.anchor.wrapping_add(offset);
        &self.slots[idx as usize]
    }

    /// Mutable access to the slot for `offset` (measured from the anchor).
    #[inline(always)]
    pub fn slot_mut(&mut self, offset: RingIndex) -> &mut T {
        debug_assert!(
            (offset as usize) < Self::depth_usize(),
            "offset {} is outside the configured depth ({})",
            offset,
            DEPTH
        );
        let idx = self.anchor.wrapping_add(offset);
        &mut self.slots[idx as usize]
    }

    /// Shift the anchor by `delta`, clearing only the slots that newly enter the window.
    #[inline(always)]
    pub fn shift_by(&mut self, delta: i128) {
        self.shift_internal(delta, false);
    }

    /// Shift by `delta` while preserving the new anchor slot on backward moves.
    #[inline(always)]
    pub fn shift_by_keep_anchor(&mut self, delta: i128) {
        self.shift_internal(delta, true);
    }

    /// Immutable access by raw ring index (0-255).
    #[inline(always)]
    pub fn slot_by_index(&self, index: RingIndex) -> &T {
        &self.slots[index as usize]
    }

    /// Mutable access by raw ring index (0-255).
    #[inline(always)]
    pub fn slot_by_index_mut(&mut self, index: RingIndex) -> &mut T {
        &mut self.slots[index as usize]
    }

    /// Clear every slot and reset the anchor index to zero.
    #[inline(always)]
    pub fn clear_all(&mut self) {
        self.slots.fill(self.zero);
        self.anchor = 0;
    }

    /// Expose immutable slice reference for advanced use-cases.
    #[inline(always)]
    pub fn as_slice(&self) -> &[T; RING_SIZE] {
        &self.slots
    }

    /// Expose mutable slice reference for advanced use-cases.
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [T; RING_SIZE] {
        &mut self.slots
    }

    /// Returns the contiguous slices that cover the ring starting at the anchor.
    ///
    /// The first slice begins at the anchor slot; the second slice wraps around
    /// to index 0 (and may be empty). This is ideal for SIMD scans.
    ///
    /// ```
    /// # use sliding_ring::SlidingRing;
    /// const DEPTH: u8 = 16;
    /// let mut ring = SlidingRing::<u64, DEPTH>::new(0);
    /// *ring.slot_mut(0) = 42;
    /// let (tail, head) = ring.slices_from_anchor();
    /// assert_eq!(tail.first(), Some(&42));
    /// assert!(head.is_empty());
    /// ```
    #[inline(always)]
    pub fn slices_from_anchor(&self) -> (&[T], &[T]) {
        let start = self.anchor as usize;
        let depth = Self::depth_usize();
        if depth >= RING_SIZE {
            let (head, tail) = self.slots.split_at(start);
            return (tail, head);
        }
        let tail_len = depth.min(RING_SIZE - start);
        let head_len = depth - tail_len;
        let tail = &self.slots[start..start + tail_len];
        let head = &self.slots[..head_len];
        (tail, head)
    }

    /// Mutable variant of [`SlidingRing::slices_from_anchor`].
    ///
    /// ```
    /// # use sliding_ring::SlidingRing;
    /// const DEPTH: u8 = 16;
    /// let mut ring = SlidingRing::<u64, DEPTH>::new(0);
    /// {
    ///     let (tail, head) = ring.slices_from_anchor_mut();
    ///     tail[0] = 7;
    ///     assert!(head.is_empty());
    /// }
    /// assert_eq!(*ring.slot(0), 7);
    /// ```
    #[inline(always)]
    pub fn slices_from_anchor_mut(&mut self) -> (&mut [T], &mut [T]) {
        let start = self.anchor as usize;
        let depth = Self::depth_usize();
        if depth >= RING_SIZE {
            let (head, tail) = self.slots.split_at_mut(start);
            return (tail, head);
        }
        let tail_len = depth.min(RING_SIZE - start);
        let head_len = depth - tail_len;
        let (head, tail) = self.slots.split_at_mut(start);
        let (tail_window, _) = tail.split_at_mut(tail_len);
        let head_window = &mut head[..head_len];
        (tail_window, head_window)
    }

    /// Iterate over slots in storage order using raw pointers.
    #[inline(always)]
    pub fn iter(&self) -> Slots<'_, T> {
        Slots::new(&self.slots)
    }

    /// Mutable iterator over slots in storage order using raw pointers.
    #[inline(always)]
    pub fn iter_mut(&mut self) -> SlotsMut<'_, T> {
        SlotsMut::new(&mut self.slots)
    }

    /// Iterate starting at the anchor in the desired direction (wrapping once).
    ///
    /// ```
    /// # use sliding_ring::{Direction, SlidingRing};
    /// const DEPTH: u8 = 16;
    /// let mut ring = SlidingRing::<u64, DEPTH>::new(0);
    /// *ring.slot_mut(0) = 1;
    /// *ring.slot_mut(1) = 2;
    /// let mut iter = ring.iter_from_anchor(Direction::Forward);
    /// assert_eq!(iter.next().unwrap().1, &1);
    /// assert_eq!(iter.next().unwrap().0, 1);
    /// ```
    #[inline(always)]
    pub fn iter_from_anchor(&self, direction: Direction) -> AnchorIter<'_, T, DEPTH> {
        AnchorIter::new(self, direction)
    }

    /// Mutable iteration starting at the anchor in the desired direction.
    ///
    /// ```
    /// # use sliding_ring::{Direction, SlidingRing};
    /// const DEPTH: u8 = 16;
    /// let mut ring = SlidingRing::<u64, DEPTH>::new(0);
    /// for (_, slot) in ring.iter_from_anchor_mut(Direction::Forward).take(2) {
    ///     *slot = 5;
    /// }
    /// assert_eq!(*ring.slot(0), 5);
    /// assert_eq!(*ring.slot(1), 5);
    /// ```
    #[inline(always)]
    pub fn iter_from_anchor_mut(&mut self, direction: Direction) -> AnchorIterMut<'_, T, DEPTH> {
        AnchorIterMut::new(self, direction)
    }
}

impl<T: Copy, const DEPTH: u8> fmt::Debug for SlidingRing<T, DEPTH> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SlidingRing")
            .field("anchor_index", &self.anchor)
            .finish()
    }
}

/// Iteration order relative to the anchor.
#[derive(Copy, Clone, Debug)]
pub enum Direction {
    /// Increasing offsets from the anchor (useful for asks / forward scans).
    Forward,
    /// Decreasing offsets from the anchor (useful for bids / backward scans).
    Backward,
}

/// Raw-pointer iterator over an immutable ring slice.
pub struct Slots<'a, T> {
    ptr: *const T,
    end: *const T,
    _marker: PhantomData<&'a T>,
}

impl<'a, T> Slots<'a, T> {
    #[inline(always)]
    fn new(slice: &'a [T; RING_SIZE]) -> Self {
        let ptr = slice.as_ptr();
        unsafe {
            Self {
                ptr,
                end: ptr.add(RING_SIZE),
                _marker: PhantomData,
            }
        }
    }
}

impl<'a, T> Iterator for Slots<'a, T> {
    type Item = &'a T;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.ptr == self.end {
            return None;
        }
        unsafe {
            let item = &*self.ptr;
            self.ptr = self.ptr.add(1);
            Some(item)
        }
    }

    #[inline(always)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = unsafe { self.end.offset_from(self.ptr) as usize };
        (len, Some(len))
    }
}

impl<'a, T> ExactSizeIterator for Slots<'a, T> {
    #[inline(always)]
    fn len(&self) -> usize {
        unsafe { self.end.offset_from(self.ptr) as usize }
    }
}

impl<'a, T> core::iter::FusedIterator for Slots<'a, T> {}

/// Raw-pointer iterator over a mutable ring slice.
pub struct SlotsMut<'a, T> {
    ptr: *mut T,
    end: *mut T,
    _marker: PhantomData<&'a mut T>,
}

impl<'a, T> SlotsMut<'a, T> {
    #[inline(always)]
    fn new(slice: &'a mut [T; RING_SIZE]) -> Self {
        let ptr = slice.as_mut_ptr();
        unsafe {
            Self {
                ptr,
                end: ptr.add(RING_SIZE),
                _marker: PhantomData,
            }
        }
    }
}

impl<'a, T> Iterator for SlotsMut<'a, T> {
    type Item = &'a mut T;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.ptr == self.end {
            return None;
        }
        unsafe {
            let item = &mut *self.ptr;
            self.ptr = self.ptr.add(1);
            Some(item)
        }
    }

    #[inline(always)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = unsafe { self.end.offset_from(self.ptr) as usize };
        (len, Some(len))
    }
}

impl<'a, T> ExactSizeIterator for SlotsMut<'a, T> {
    #[inline(always)]
    fn len(&self) -> usize {
        unsafe { self.end.offset_from(self.ptr) as usize }
    }
}

impl<'a, T> core::iter::FusedIterator for SlotsMut<'a, T> {}

/// Anchor-ordered iterator (immutable).
pub struct AnchorIter<'a, T: Copy, const DEPTH: u8> {
    ptr: *const T,
    base: *const T,
    end: *const T,
    remaining: usize,
    offset: i16,
    direction: Direction,
    _marker: PhantomData<&'a T>,
}

impl<'a, T: Copy, const DEPTH: u8> AnchorIter<'a, T, DEPTH> {
    #[inline(always)]
    fn new(ring: &'a SlidingRing<T, DEPTH>, direction: Direction) -> Self {
        let base = ring.slots.as_ptr();
        let ptr = unsafe { base.add(ring.anchor as usize) };
        let end = unsafe { base.add(RING_SIZE) };
        Self {
            ptr,
            base,
            end,
            remaining: SlidingRing::<T, DEPTH>::depth_usize(),
            offset: 0,
            direction,
            _marker: PhantomData,
        }
    }
}

impl<'a, T: Copy, const DEPTH: u8> Iterator for AnchorIter<'a, T, DEPTH> {
    type Item = (i16, &'a T);

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;
        unsafe {
            let item = &*self.ptr;
            self.ptr = match self.direction {
                Direction::Forward => {
                    let next = self.ptr.add(1);
                    if next == self.end { self.base } else { next }
                }
                Direction::Backward => {
                    if self.ptr == self.base {
                        self.end.sub(1)
                    } else {
                        self.ptr.sub(1)
                    }
                }
            };
            let coord = self.offset;
            match self.direction {
                Direction::Forward => self.offset = self.offset.wrapping_add(1),
                Direction::Backward => self.offset = self.offset.wrapping_sub(1),
            }
            Some((coord, item))
        }
    }

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

impl<'a, T: Copy, const DEPTH: u8> ExactSizeIterator for AnchorIter<'a, T, DEPTH> {
    #[inline(always)]
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<'a, T: Copy, const DEPTH: u8> core::iter::FusedIterator for AnchorIter<'a, T, DEPTH> {}

/// Anchor-ordered iterator (mutable).
pub struct AnchorIterMut<'a, T: Copy, const DEPTH: u8> {
    ptr: *mut T,
    base: *mut T,
    end: *mut T,
    remaining: usize,
    offset: i16,
    direction: Direction,
    _marker: PhantomData<&'a mut T>,
}

impl<'a, T: Copy, const DEPTH: u8> AnchorIterMut<'a, T, DEPTH> {
    #[inline(always)]
    fn new(ring: &'a mut SlidingRing<T, DEPTH>, direction: Direction) -> Self {
        let base = ring.slots.as_mut_ptr();
        let ptr = unsafe { base.add(ring.anchor as usize) };
        let end = unsafe { base.add(RING_SIZE) };
        Self {
            ptr,
            base,
            end,
            remaining: SlidingRing::<T, DEPTH>::depth_usize(),
            offset: 0,
            direction,
            _marker: PhantomData,
        }
    }
}

impl<'a, T: Copy, const DEPTH: u8> Iterator for AnchorIterMut<'a, T, DEPTH> {
    type Item = (i16, &'a mut T);

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;
        unsafe {
            let item = &mut *self.ptr;
            self.ptr = match self.direction {
                Direction::Forward => {
                    let next = self.ptr.add(1);
                    if next == self.end { self.base } else { next }
                }
                Direction::Backward => {
                    if self.ptr == self.base {
                        self.end.sub(1)
                    } else {
                        self.ptr.sub(1)
                    }
                }
            };
            let coord = self.offset;
            match self.direction {
                Direction::Forward => self.offset = self.offset.wrapping_add(1),
                Direction::Backward => self.offset = self.offset.wrapping_sub(1),
            }
            Some((coord, item))
        }
    }

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

impl<'a, T: Copy, const DEPTH: u8> ExactSizeIterator for AnchorIterMut<'a, T, DEPTH> {
    #[inline(always)]
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<'a, T: Copy, const DEPTH: u8> core::iter::FusedIterator for AnchorIterMut<'a, T, DEPTH> {}

/// Reduce a signed difference mod 256 (ring size).
#[inline]
pub fn diff_mod_256(diff: i128) -> RingIndex {
    (diff & 255) as RingIndex
}

#[cfg(test)]
mod tests {
    use super::*;
    const TEST_DEPTH: u8 = 64;

    #[test]
    fn diff_mod_matches_reference() {
        let xs = [
            i128::MIN,
            i128::MIN / 2,
            -65_536,
            -10_000,
            -1024,
            -256,
            -255,
            -1,
            0,
            1,
            127,
            254,
            255,
            256,
            1024,
            10_000,
            65_536,
            i128::MAX / 2,
            i128::MAX,
        ];
        for &d in &xs {
            let m = diff_mod_256(d);
            let expected = (d.rem_euclid(256)) as u8;
            assert_eq!(m, expected);
        }
    }

    #[test]
    fn slot_reads_and_writes_by_offset() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        *ring.borrow_anchor_mut() = 5;
        *ring.slot_mut(1) = 7;
        assert_eq!(*ring.borrow_anchor(), 5);
        assert_eq!(*ring.slot(1), 7);
    }

    #[test]
    fn shift_by_forward_clears_tail() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        for off in 0..TEST_DEPTH {
            *ring.slot_mut(off) = 1;
        }
        ring.shift_by(5);
        let depth = TEST_DEPTH as usize;
        for off in 0..(depth - 5) {
            assert_eq!(*ring.slot(off as RingIndex), 1);
        }
        for off in depth - 5..depth {
            assert_eq!(*ring.slot(off as RingIndex), 0);
        }
    }

    #[test]
    fn shift_by_backward_clears_head() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        for off in 0..TEST_DEPTH {
            *ring.slot_mut(off) = 1;
        }
        ring.shift_by(-4);
        for off in 0..4 {
            assert_eq!(*ring.slot(off as RingIndex), 0);
        }
        for off in 4..TEST_DEPTH as usize {
            assert_eq!(*ring.slot(off as RingIndex), 1);
        }
    }

    #[test]
    fn shift_by_large_distance_resets_all() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        for off in 0..TEST_DEPTH {
            *ring.slot_mut(off) = 9;
        }
        ring.shift_by(TEST_DEPTH as i128);
        for off in 0..TEST_DEPTH {
            assert_eq!(*ring.slot(off), 0);
        }
    }

    #[test]
    fn shift_by_keep_anchor_preserves_anchor_slot() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        let head0 = diff_mod_256(-1);
        let head1 = diff_mod_256(-2);
        let head2 = diff_mod_256(-3);
        *ring.slot_by_index_mut(head0) = 11;
        *ring.slot_by_index_mut(head1) = 22;
        *ring.slot_by_index_mut(head2) = 33;
        ring.shift_by_keep_anchor(-3);
        assert_eq!(*ring.borrow_anchor(), 33);
        assert_eq!(*ring.slot(1), 0);
        assert_eq!(*ring.slot(2), 0);
    }

    #[test]
    fn iterators_cover_all_slots_in_storage_order() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        for (i, slot) in ring.iter_mut().enumerate() {
            *slot = i as u64;
        }
        for (i, slot) in ring.iter().enumerate() {
            assert_eq!(*slot, i as u64);
        }
    }

    #[test]
    fn slices_from_anchor_split_correctly() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        for (i, slot) in ring.iter_mut().enumerate() {
            *slot = i as u64;
        }
        ring.shift_by(100);
        *ring.borrow_anchor_mut() = u64::MAX;
        let (tail, head) = ring.slices_from_anchor();
        let window = TEST_DEPTH as usize;
        let anchor_idx = ring
            .as_slice()
            .iter()
            .position(|&v| v == u64::MAX)
            .expect("sentinel present");
        let expected_tail = window.min(RING_SIZE - anchor_idx);
        assert_eq!(head.len() + tail.len(), window);
        assert_eq!(tail.len(), expected_tail);
        assert_eq!(head.len(), window - expected_tail);
    }

    #[test]
    fn anchor_iter_traverses_forward() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        ring.shift_by(50);
        for (i, slot) in ring.iter_mut().enumerate() {
            *slot = i as u64;
        }
        let mut offsets = Vec::new();
        for (offset, _) in ring.iter_from_anchor(Direction::Forward).take(3) {
            offsets.push(offset);
        }
        assert_eq!(offsets, vec![0, 1, 2]);
    }

    #[test]
    fn anchor_iter_traverses_backward() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        ring.shift_by(50);
        let mut offsets = Vec::new();
        for (offset, _) in ring.iter_from_anchor(Direction::Backward).take(3) {
            offsets.push(offset);
        }
        assert_eq!(offsets, vec![0, -1, -2]);
    }

    #[test]
    fn option_slots_clear_back_to_none() {
        let mut ring = SlidingRing::<Option<u32>, TEST_DEPTH>::new(None);
        *ring.slot_mut(5) = Some(42);
        ring.shift_by(TEST_DEPTH as i128);
        for off in 0..TEST_DEPTH {
            assert!(ring.slot(off).is_none());
        }
    }

    #[test]
    fn custom_copy_slots_reset_to_zero() {
        #[derive(Clone, Copy)]
        struct Level {
            qty: u32,
        }

        let mut ring = SlidingRing::<Level, TEST_DEPTH>::new(Level { qty: 0 });
        ring.slot_mut(3).qty = 7;
        ring.shift_by(TEST_DEPTH as i128);
        assert_eq!(ring.slot(3).qty, 0);
    }

    #[test]
    fn anchor_index_wraps_modulo() {
        let mut ring = SlidingRing::<u64, TEST_DEPTH>::new(0);
        let diff = i128::MAX - 100;
        ring.shift_by(diff);
        *ring.borrow_anchor_mut() = 7;
        let idx = ring
            .as_slice()
            .iter()
            .position(|&v| v == 7)
            .expect("sentinel should be present");
        assert_eq!(idx as u8, diff_mod_256(diff));
    }
}