fast-able 1.20.2

The world's martial arts are fast and unbreakable; 天下武功 唯快不破
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154

use std::fmt;
use std::ops::{Deref, Index, IndexMut};
use std::{default::Default, usize};

use crate::unsafe_cell_type::U;

/// 环形数组,适合高频数据,且数据量不大的场景。线程不安全,使用者请控制好访问时机。
/// 1. 适合高频数据,且数据量不大的场景
/// 2. 线程不安全,使用者请控制好访问时机
/// 3. 设计上,push方法会覆盖掉旧数据,且不删除旧数据。find方法会从最新的数据项开始往前找,直到找到满足条件的项为止。
///     3.1 例如,LEN=10,push了11项,那么第11项会覆盖掉第1项,但第1项仍然存在。find方法会先找第11项,再找第10项...直到找到满足条件的项为止。
///     3.2 例如,LEN=10,push了9项,那么第1项到第9项都存在。find方法会先找第9项,再找第8项...直到找到满足条件的项为止。
///     3.3 例如,LEN=10,push了10项,那么第1项到第10项都存在。find方法会先找第10项,再找第9项...直到找到满足条件的项为止。
/// 4. 适合的场景:例如,某个接口的调用日志,push方法记录每次调用的日志,find方法根据条件找出满足条件的调用日志。
pub struct FastArray<T, const LEN: usize> {
    item: U<UnsafeData<T, LEN>>,
}

impl<T, const LEN: usize> Deref for FastArray<T, LEN> {
    type Target = UnsafeData<T, LEN>;
    fn deref(&self) -> &Self::Target {
        self.item.as_ref()
    }
}

pub struct UnsafeData<T, const LEN: usize> {
    items: [Option<T>; LEN],
    index: usize,
    pub count: usize,
}

impl<T, const LEN: usize> FastArray<T, LEN> {
    pub fn new() -> Self {
        let items: [Option<T>; LEN] = std::array::from_fn(|_| None);
        let item = UnsafeData {
            items,
            index: 0,
            count: 0,
        };
        Self { item: U::new(item) }
    }

    fn item_mut(&self) -> &mut UnsafeData<T, LEN> {
        self.item.as_mut()
    }

    /// 添加1项
    /// 请控制此方法不可并发访问
    pub fn push(&self, item_new: T) {
        let self_item = self.item_mut();

        if self_item.count == 0 {
            // 此时 index = 0, 对index不操作
        } else {
            self_item.index += 1;
            if self_item.index == LEN {
                self_item.index = 0;
            }
        }
        self_item.items[self.index] = Some(item_new);
        self_item.count += 1;
    }

    /// 当前项
    pub fn current(&self) -> Option<&T> {
        if self.count == 0 {
            return None;
        }
        self.items[self.index].as_ref()
    }

    /// 请控制此方法不可并发访问
    pub fn clear(&self) {
        let self_item = self.item_mut();
        self_item.index = 0;
        self_item.count = 0;
    }

    pub fn find<F: FnMut(&T) -> bool>(&self, mut f: F) -> Option<&T> {
        if self.count == 0 {
            return None;
        }

        if let Some(当前项) = &self.items[self.index] {
            if f(当前项) {
                return Some(当前项);
            }
        }

        let index_当前索引 = self.index;
        for idx in (0..index_当前索引).rev() {
            if let Some(item) = &self.items[idx] {
                if f(item) {
                    return Some(item);
                }
            }
        }
        if self.count <= LEN {
            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
            return None;
        }

        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
            if let Some(item) = &self.items[idx] {
                if f(item) {
                    return Some(item);
                }
            }
        }
        None
    }

    pub fn find_vec<F: FnMut(&T) -> bool>(&self, mut f: F) -> Vec<&T> {
        if self.count == 0 {
            return vec![];
        }

        let mut r_items = vec![];
        if let Some(当前项) = &self.items[self.index] {
            if f(当前项) {
                r_items.push(当前项);
            }
        }

        let index_当前索引 = self.index;
        for idx in (0..index_当前索引).rev() {
            if let Some(item) = &self.items[idx] {
                if f(item) {
                    r_items.push(item);
                }
            }
        }
        if self.count <= LEN {
            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
            return r_items;
        }

        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
            if let Some(item) = &self.items[idx] {
                if f(item) {
                    r_items.push(item);
                }
            }
        }
        r_items
    }

    /// 实际存储的元素数量(最大为 LEN)
    pub fn len(&self) -> usize {
        if self.count <= LEN {
            self.count
        } else {
            LEN
        }
    }

    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// 返回迭代器,从最新到最旧的顺序遍历,支持 `.rev()` 反向遍历
    pub fn iter(&self) -> Iter<'_, T, LEN> {
        let len = self.len();
        let back = if len == 0 {
            0
        } else if self.count <= LEN {
            0
        } else {
            (self.index + 1) % LEN
        };
        Iter {
            data: self.item.as_ref(),
            remaining: len,
            front: self.index,
            back,
        }
    }

    /// 将逻辑索引(0=最新)转换为物理环形缓冲区索引
    fn logical_to_physical(&self, logical_idx: usize) -> usize {
        assert!(
            logical_idx < self.len(),
            "index out of bounds: the len is {} but the index is {}",
            self.len(),
            logical_idx
        );
        if self.index >= logical_idx {
            self.index - logical_idx
        } else {
            LEN - (logical_idx - self.index)
        }
    }
}

/// FastVec 迭代器,从最新到最旧的顺序遍历,支持 `rev()` 反向(最旧到最新)遍历
pub struct Iter<'a, T, const LEN: usize> {
    data: &'a UnsafeData<T, LEN>,
    remaining: usize,
    /// 前端游标(最新侧),next() 从此处取值并向旧方向移动
    front: usize,
    /// 后端游标(最旧侧),next_back() 从此处取值并向新方向移动
    back: usize,
}

impl<'a, T, const LEN: usize> Iterator for Iter<'a, T, LEN> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let item = self.data.items[self.front].as_ref();
        self.front = if self.front == 0 { LEN - 1 } else { self.front - 1 };
        self.remaining -= 1;
        item
    }

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

impl<'a, T, const LEN: usize> DoubleEndedIterator for Iter<'a, T, LEN> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let item = self.data.items[self.back].as_ref();
        self.back = if self.back == LEN - 1 { 0 } else { self.back + 1 };
        self.remaining -= 1;
        item
    }
}

impl<'a, T, const LEN: usize> ExactSizeIterator for Iter<'a, T, LEN> {}

impl<'a, T, const LEN: usize> IntoIterator for &'a FastArray<T, LEN> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T, LEN>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// FastVec 所有权迭代器,消费 FastVec 并按从最新到最旧的顺序产出元素
pub struct IntoIter<T, const LEN: usize> {
    items: [Option<T>; LEN],
    remaining: usize,
    front: usize,
    back: usize,
}

impl<T, const LEN: usize> Iterator for IntoIter<T, LEN> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let item = self.items[self.front].take();
        self.front = if self.front == 0 { LEN - 1 } else { self.front - 1 };
        self.remaining -= 1;
        item
    }

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

impl<T, const LEN: usize> DoubleEndedIterator for IntoIter<T, LEN> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let item = self.items[self.back].take();
        self.back = if self.back == LEN - 1 { 0 } else { self.back + 1 };
        self.remaining -= 1;
        item
    }
}

impl<T, const LEN: usize> ExactSizeIterator for IntoIter<T, LEN> {}

impl<T, const LEN: usize> IntoIterator for FastArray<T, LEN> {
    type Item = T;
    type IntoIter = IntoIter<T, LEN>;

    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        let index = self.index;
        let count = self.count;
        let items = self.item.into_inner().items;
        let back = if len == 0 {
            0
        } else if count <= LEN {
            0
        } else {
            (index + 1) % LEN
        };
        IntoIter {
            items,
            remaining: len,
            front: index,
            back,
        }
    }
}

impl<T: fmt::Debug, const LEN: usize> fmt::Debug for FastArray<T, LEN> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<T: fmt::Display, const LEN: usize> fmt::Display for FastArray<T, LEN> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[")?;
        let mut first = true;
        for item in self.iter() {
            if !first {
                write!(f, ", ")?;
            }
            write!(f, "{}", item)?;
            first = false;
        }
        write!(f, "]")
    }
}

impl<T, const LEN: usize> Index<usize> for FastArray<T, LEN> {
    type Output = T;

    fn index(&self, idx: usize) -> &Self::Output {
        let physical = self.logical_to_physical(idx);
        self.items[physical].as_ref().unwrap()
    }
}

impl<T, const LEN: usize> IndexMut<usize> for FastArray<T, LEN> {
    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
        let physical = self.logical_to_physical(idx);
        self.item.as_mut().items[physical].as_mut().unwrap()
    }
}

impl<T, const LEN: usize> Default for FastArray<T, LEN> {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn make_cache(values: &[i32]) -> FastArray<i32, 4> {
        let cache = FastArray::<i32, 4>::new();
        for &v in values {
            cache.push(v);
        }
        cache
    }

    // ==================== push 各种情况 ====================

    #[test]
    fn test_empty_no_push() {
        let cache = FastArray::<i32, 4>::new();
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.count, 0);
        assert!(cache.is_empty());
        assert!(cache.current().is_none());
        assert!(cache.find(|_| true).is_none());
        assert!(cache.find_vec(|_| true).is_empty());
        assert_eq!(cache.iter().count(), 0);
        let collected: Vec<&i32> = cache.iter().collect();
        assert!(collected.is_empty());
    }

    #[test]
    fn test_push_single() {
        let cache = FastArray::<i32, 4>::new();
        cache.push(42);
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.count, 1);
        assert!(!cache.is_empty());
        assert_eq!(cache.current(), Some(&42));
        assert_eq!(cache[0], 42);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&42]);
    }

    #[test]
    fn test_partial_fill() {
        let cache = make_cache(&[10, 20]);
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.count, 2);
        assert!(!cache.is_empty());
        assert_eq!(cache.current(), Some(&20));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&20, &10]);
    }

    #[test]
    fn test_partial_fill_three() {
        let cache = make_cache(&[10, 20, 30]);
        assert_eq!(cache.len(), 3);
        assert_eq!(cache.count, 3);
        assert_eq!(cache.current(), Some(&30));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&30, &20, &10]);
    }

    #[test]
    fn test_exact_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 4);
        assert_eq!(cache.current(), Some(&4));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&4, &3, &2, &1]);
    }

    #[test]
    fn test_overflow_by_one() {
        // push 5 项到 LEN=4,第1项被覆盖
        let cache = make_cache(&[1, 2, 3, 4, 5]);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 5);
        assert_eq!(cache.current(), Some(&5));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&5, &4, &3, &2]);
    }

    #[test]
    fn test_overflow_by_two() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 6);
        assert_eq!(cache.current(), Some(&6));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&6, &5, &4, &3]);
    }

    #[test]
    fn test_many_wraps() {
        // push 20 项到 LEN=4(5 轮满)
        let values: Vec<i32> = (1..=20).collect();
        let cache = make_cache(&values);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 20);
        assert_eq!(cache.current(), Some(&20));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&20, &19, &18, &17]);
    }

    #[test]
    fn test_many_wraps_large() {
        // push 100 项到 LEN=4
        let values: Vec<i32> = (1..=100).collect();
        let cache = make_cache(&values);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 100);
        assert_eq!(cache.current(), Some(&100));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&100, &99, &98, &97]);
    }

    #[test]
    fn test_exact_two_wraps() {
        // push 恰好 8 项到 LEN=4(2 轮满)
        let values: Vec<i32> = (1..=8).collect();
        let cache = make_cache(&values);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 8);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&8, &7, &6, &5]);
    }

    #[test]
    fn test_exact_two_wraps_plus_one() {
        let values: Vec<i32> = (1..=9).collect();
        let cache = make_cache(&values);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 9);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&9, &8, &7, &6]);
    }

    // ==================== LEN=1 边界 ====================

    #[test]
    fn test_len_one_cache() {
        let cache = FastArray::<i32, 1>::new();
        assert!(cache.is_empty());

        cache.push(1);
        assert_eq!(cache.len(), 1);
        assert_eq!(cache[0], 1);

        cache.push(2);
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.count, 2);
        assert_eq!(cache[0], 2);

        cache.push(3);
        assert_eq!(cache[0], 3);
        assert_eq!(cache.count, 3);

        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&3]);
    }

    // ==================== iter ====================

    #[test]
    fn test_iter_empty() {
        let cache = FastArray::<i32, 4>::new();
        let mut iter = cache.iter();
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn test_iter_size_hint() {
        let cache = make_cache(&[1, 2, 3]);
        let iter = cache.iter();
        assert_eq!(iter.size_hint(), (3, Some(3)));
        assert_eq!(iter.len(), 3);
    }

    #[test]
    fn test_iter_exact_size_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5]);
        let iter = cache.iter();
        assert_eq!(iter.len(), 4);
    }

    #[test]
    fn test_iter_step_by_step() {
        let cache = make_cache(&[10, 20, 30]);
        let mut iter = cache.iter();
        assert_eq!(iter.next(), Some(&30));
        assert_eq!(iter.len(), 2);
        assert_eq!(iter.next(), Some(&20));
        assert_eq!(iter.len(), 1);
        assert_eq!(iter.next(), Some(&10));
        assert_eq!(iter.len(), 0);
        assert_eq!(iter.next(), None);
    }

    // ==================== into_iter (&引用) ====================

    #[test]
    fn test_into_iter_borrow() {
        let cache = make_cache(&[10, 20, 30]);
        let items: Vec<&i32> = (&cache).into_iter().collect();
        assert_eq!(items, vec![&30, &20, &10]);
    }

    #[test]
    fn test_for_loop() {
        let cache = make_cache(&[1, 2, 3]);
        let mut items = vec![];
        for item in &cache {
            items.push(*item);
        }
        assert_eq!(items, vec![3, 2, 1]);
    }

    #[test]
    fn test_for_loop_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        let mut items = vec![];
        for item in &cache {
            items.push(*item);
        }
        assert_eq!(items, vec![6, 5, 4, 3]);
    }

    // ==================== len / is_empty / count ====================

    #[test]
    fn test_len_and_count_incremental() {
        let cache = FastArray::<i32, 4>::new();
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.count, 0);
        assert!(cache.is_empty());

        cache.push(1);
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.count, 1);
        assert!(!cache.is_empty());

        cache.push(2);
        cache.push(3);
        cache.push(4);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 4);

        cache.push(5);
        assert_eq!(cache.len(), 4); // 封顶 LEN
        assert_eq!(cache.count, 5); // 总 push 次数

        cache.push(6);
        cache.push(7);
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 7);
    }

    // ==================== Debug ====================

    #[test]
    fn test_debug_empty() {
        let cache = FastArray::<i32, 4>::new();
        assert_eq!(format!("{:?}", cache), "[]");
    }

    #[test]
    fn test_debug_partial() {
        let cache = make_cache(&[1, 2]);
        assert_eq!(format!("{:?}", cache), "[2, 1]");
    }

    #[test]
    fn test_debug_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(format!("{:?}", cache), "[4, 3, 2, 1]");
    }

    #[test]
    fn test_debug_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(format!("{:?}", cache), "[6, 5, 4, 3]");
    }

    // ==================== Display ====================

    #[test]
    fn test_display_empty() {
        let cache = FastArray::<i32, 4>::new();
        assert_eq!(format!("{}", cache), "[]");
    }

    #[test]
    fn test_display_partial() {
        let cache = make_cache(&[1, 2]);
        assert_eq!(format!("{}", cache), "[2, 1]");
    }

    #[test]
    fn test_display_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(format!("{}", cache), "[4, 3, 2, 1]");
    }

    #[test]
    fn test_display_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(format!("{}", cache), "[6, 5, 4, 3]");
    }

    // ==================== Index ====================

    #[test]
    fn test_index_partial() {
        let cache = make_cache(&[10, 20, 30]);
        assert_eq!(cache[0], 30); // 最新
        assert_eq!(cache[1], 20);
        assert_eq!(cache[2], 10); // 最旧
    }

    #[test]
    fn test_index_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(cache[0], 4);
        assert_eq!(cache[1], 3);
        assert_eq!(cache[2], 2);
        assert_eq!(cache[3], 1);
    }

    #[test]
    fn test_index_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(cache[0], 6);
        assert_eq!(cache[1], 5);
        assert_eq!(cache[2], 4);
        assert_eq!(cache[3], 3);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_out_of_bounds_empty() {
        let cache = FastArray::<i32, 4>::new();
        let _ = cache[0];
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_out_of_bounds_partial() {
        let cache = make_cache(&[1, 2]);
        let _ = cache[2];
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_out_of_bounds_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let _ = cache[4];
    }

    // ==================== IndexMut ====================

    #[test]
    fn test_index_mut_partial() {
        let mut cache = make_cache(&[10, 20, 30]);
        cache[0] = 99; // 修改最新
        assert_eq!(cache[0], 99);
        assert_eq!(cache[1], 20);
        assert_eq!(cache[2], 10);

        cache[2] = 88; // 修改最旧
        assert_eq!(cache[2], 88);
    }

    #[test]
    fn test_index_mut_overflow() {
        let mut cache = make_cache(&[1, 2, 3, 4, 5]);
        cache[0] = 99; // 修改最新(原值5)
        assert_eq!(cache[0], 99);
        assert_eq!(cache[1], 4);
        assert_eq!(cache[2], 3);
        assert_eq!(cache[3], 2);
    }

    #[test]
    fn test_index_mut_then_iter() {
        let mut cache = make_cache(&[1, 2, 3, 4]);
        cache[1] = 33; // 修改第2新的项(原值3)
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&4, &33, &2, &1]);
    }

    // ==================== find ====================

    #[test]
    fn test_find_empty() {
        let cache = FastArray::<i32, 4>::new();
        assert!(cache.find(|_| true).is_none());
    }

    #[test]
    fn test_find_partial() {
        let cache = make_cache(&[10, 20, 30]);
        // 从最新开始找
        assert_eq!(cache.find(|&v| v >= 20), Some(&30));
        assert_eq!(cache.find(|&v| v == 10), Some(&10));
        assert!(cache.find(|&v| v > 100).is_none());
    }

    #[test]
    fn test_find_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(cache.find(|&v| v == 1), Some(&1));
        assert_eq!(cache.find(|&v| v == 4), Some(&4));
        assert_eq!(cache.find(|&v| v % 2 == 0), Some(&4)); // 最新的偶数
    }

    #[test]
    fn test_find_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5]);
        // 第1项已被第5项覆盖
        assert!(cache.find(|&v| v == 1).is_none());
        assert_eq!(cache.find(|&v| v == 5), Some(&5));
        assert_eq!(cache.find(|&v| v == 2), Some(&2));
    }

    // ==================== find_vec ====================

    #[test]
    fn test_find_vec_empty() {
        let cache = FastArray::<i32, 4>::new();
        assert!(cache.find_vec(|_| true).is_empty());
    }

    #[test]
    fn test_find_vec_partial() {
        let cache = make_cache(&[10, 20, 30]);
        let found = cache.find_vec(|&v| v >= 20);
        assert_eq!(found, vec![&30, &20]);
    }

    #[test]
    fn test_find_vec_all() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let found = cache.find_vec(|_| true);
        assert_eq!(found, vec![&4, &3, &2, &1]);
    }

    #[test]
    fn test_find_vec_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        let found = cache.find_vec(|_| true);
        assert_eq!(found, vec![&6, &5, &4, &3]);
    }

    #[test]
    fn test_find_vec_none_match() {
        let cache = make_cache(&[1, 2, 3]);
        let found = cache.find_vec(|&v| v > 100);
        assert!(found.is_empty());
    }

    // ==================== current ====================

    #[test]
    fn test_current_empty() {
        let cache = FastArray::<i32, 4>::new();
        assert!(cache.current().is_none());
    }

    #[test]
    fn test_current_after_pushes() {
        let cache = FastArray::<i32, 4>::new();
        cache.push(10);
        assert_eq!(cache.current(), Some(&10));
        cache.push(20);
        assert_eq!(cache.current(), Some(&20));
        cache.push(30);
        cache.push(40);
        cache.push(50); // overflow
        assert_eq!(cache.current(), Some(&50));
    }

    // ==================== clear ====================

    #[test]
    fn test_clear() {
        let cache = make_cache(&[1, 2, 3, 4]);
        assert_eq!(cache.len(), 4);
        cache.clear();
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.count, 0);
        assert!(cache.is_empty());
        assert!(cache.current().is_none());
        assert_eq!(cache.iter().count(), 0);
    }

    #[test]
    fn test_clear_then_push() {
        let cache = make_cache(&[1, 2, 3, 4, 5]);
        cache.clear();
        cache.push(100);
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.count, 1);
        assert_eq!(cache.current(), Some(&100));
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&100]);
    }

    #[test]
    fn test_clear_overflow_then_refill() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        cache.clear();
        cache.push(100);
        cache.push(200);
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.count, 2);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&200, &100]);
    }

    // ==================== Default ====================

    #[test]
    fn test_default() {
        let cache: FastArray<i32, 4> = Default::default();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    // ==================== 一致性验证 ====================

    #[test]
    fn test_iter_index_consistency() {
        // iter 的顺序和 index 的顺序完全一致
        let cache = make_cache(&[10, 20, 30, 40, 50, 60]);
        let iter_items: Vec<&i32> = cache.iter().collect();
        for (i, item) in iter_items.iter().enumerate() {
            assert_eq!(**item, cache[i]);
        }
    }

    #[test]
    fn test_iter_find_vec_consistency() {
        // iter(所有) 和 find_vec(|_| true) 结果一致
        let cache = make_cache(&[10, 20, 30, 40, 50, 60]);
        let iter_items: Vec<&i32> = cache.iter().collect();
        let find_items = cache.find_vec(|_| true);
        assert_eq!(iter_items, find_items);
    }

    #[test]
    fn test_iter_find_vec_consistency_partial() {
        let cache = make_cache(&[10, 20]);
        let iter_items: Vec<&i32> = cache.iter().collect();
        let find_items = cache.find_vec(|_| true);
        assert_eq!(iter_items, find_items);
    }

    #[test]
    fn test_iter_find_vec_consistency_exact_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let iter_items: Vec<&i32> = cache.iter().collect();
        let find_items = cache.find_vec(|_| true);
        assert_eq!(iter_items, find_items);
    }

    #[test]
    fn test_iter_find_vec_consistency_many_wraps() {
        let values: Vec<i32> = (1..=100).collect();
        let cache = make_cache(&values);
        let iter_items: Vec<&i32> = cache.iter().collect();
        let find_items = cache.find_vec(|_| true);
        assert_eq!(iter_items, find_items);
    }

    // ==================== 综合场景 ====================

    #[test]
    fn test_push_clear_push_cycle() {
        let cache = FastArray::<i32, 4>::new();

        // 第一轮
        for i in 1..=6 {
            cache.push(i);
        }
        assert_eq!(cache.len(), 4);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&6, &5, &4, &3]);

        // 清空
        cache.clear();
        assert!(cache.is_empty());

        // 第二轮
        for i in 100..=102 {
            cache.push(i);
        }
        assert_eq!(cache.len(), 3);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&102, &101, &100]);

        // 再满
        cache.push(103);
        cache.push(104);
        assert_eq!(cache.len(), 4);
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&104, &103, &102, &101]);
    }

    #[test]
    fn test_display_debug_consistency() {
        let cache = make_cache(&[5, 10, 15]);
        let display = format!("{}", cache);
        // Display: [15, 10, 5]
        assert_eq!(display, "[15, 10, 5]");
        let debug = format!("{:?}", cache);
        // Debug: [15, 10, 5]
        assert_eq!(debug, "[15, 10, 5]");
    }

    #[test]
    fn test_all_apis_on_overflow_scenario() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6, 7]);
        // LEN=4, push了7项,保留 7,6,5,4

        // len / count / is_empty
        assert_eq!(cache.len(), 4);
        assert_eq!(cache.count, 7);
        assert!(!cache.is_empty());

        // current
        assert_eq!(cache.current(), Some(&7));

        // iter
        let items: Vec<&i32> = cache.iter().collect();
        assert_eq!(items, vec![&7, &6, &5, &4]);

        // into_iter
        let items2: Vec<&i32> = (&cache).into_iter().collect();
        assert_eq!(items2, vec![&7, &6, &5, &4]);

        // index
        assert_eq!(cache[0], 7);
        assert_eq!(cache[1], 6);
        assert_eq!(cache[2], 5);
        assert_eq!(cache[3], 4);

        // find
        assert_eq!(cache.find(|&v| v == 5), Some(&5));
        assert!(cache.find(|&v| v == 1).is_none());

        // find_vec
        let found = cache.find_vec(|&v| v >= 6);
        assert_eq!(found, vec![&7, &6]);

        // debug / display
        assert_eq!(format!("{:?}", cache), "[7, 6, 5, 4]");
        assert_eq!(format!("{}", cache), "[7, 6, 5, 4]");
    }

    // ==================== rev ====================

    #[test]
    fn test_rev_empty() {
        let cache = FastArray::<i32, 4>::new();
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert!(items.is_empty());
    }

    #[test]
    fn test_rev_single() {
        let cache = make_cache(&[42]);
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&42]);
    }

    #[test]
    fn test_rev_partial() {
        let cache = make_cache(&[10, 20, 30]);
        // iter: 30, 20, 10 → rev: 10, 20, 30
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&10, &20, &30]);
    }

    #[test]
    fn test_rev_exact_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&1, &2, &3, &4]);
    }

    #[test]
    fn test_rev_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        // 保留 6,5,4,3 → rev: 3, 4, 5, 6
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&3, &4, &5, &6]);
    }

    #[test]
    fn test_rev_many_wraps() {
        let values: Vec<i32> = (1..=20).collect();
        let cache = make_cache(&values);
        // 保留 20,19,18,17 → rev: 17, 18, 19, 20
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&17, &18, &19, &20]);
    }

    #[test]
    fn test_rev_len_one_cache() {
        let cache = FastArray::<i32, 1>::new();
        cache.push(1);
        cache.push(2);
        cache.push(3);
        let items: Vec<&i32> = cache.iter().rev().collect();
        assert_eq!(items, vec![&3]);
    }

    #[test]
    fn test_rev_is_inverse_of_iter() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6, 7]);
        let forward: Vec<&i32> = cache.iter().collect();
        let mut backward: Vec<&i32> = cache.iter().rev().collect();
        backward.reverse();
        assert_eq!(forward, backward);
    }

    #[test]
    fn test_mixed_next_and_next_back() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let mut iter = cache.iter();
        // front: 4, back: 1
        assert_eq!(iter.next(), Some(&4));
        assert_eq!(iter.next_back(), Some(&1));
        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next_back(), Some(&2));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next_back(), None);
    }

    // ==================== into_iter (所有权) ====================

    #[test]
    fn test_into_iter_owned_empty() {
        let cache = FastArray::<i32, 4>::new();
        let items: Vec<i32> = cache.into_iter().collect();
        assert!(items.is_empty());
    }

    #[test]
    fn test_into_iter_owned_partial() {
        let cache = make_cache(&[10, 20, 30]);
        let items: Vec<i32> = cache.into_iter().collect();
        assert_eq!(items, vec![30, 20, 10]);
    }

    #[test]
    fn test_into_iter_owned_full() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let items: Vec<i32> = cache.into_iter().collect();
        assert_eq!(items, vec![4, 3, 2, 1]);
    }

    #[test]
    fn test_into_iter_owned_overflow() {
        let cache = make_cache(&[1, 2, 3, 4, 5, 6]);
        let items: Vec<i32> = cache.into_iter().collect();
        assert_eq!(items, vec![6, 5, 4, 3]);
    }

    #[test]
    fn test_into_iter_owned_rev() {
        let cache = make_cache(&[1, 2, 3, 4, 5]);
        // 保留 5,4,3,2 → rev: 2,3,4,5
        let items: Vec<i32> = cache.into_iter().rev().collect();
        assert_eq!(items, vec![2, 3, 4, 5]);
    }

    #[test]
    fn test_into_iter_owned_for_loop() {
        let cache = make_cache(&[10, 20, 30]);
        let mut items = vec![];
        for item in cache {
            items.push(item);
        }
        assert_eq!(items, vec![30, 20, 10]);
    }

    #[test]
    fn test_into_iter_owned_mixed() {
        let cache = make_cache(&[1, 2, 3, 4]);
        let mut iter = cache.into_iter();
        assert_eq!(iter.next(), Some(4));
        assert_eq!(iter.next_back(), Some(1));
        assert_eq!(iter.len(), 2);
        assert_eq!(iter.next(), Some(3));
        assert_eq!(iter.next_back(), Some(2));
        assert_eq!(iter.next(), None);
    }
}