fast-able 1.18.6

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
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
// 高频数据

use crossbeam::atomic::AtomicCell;
use crate::unsafe_cell_type::U;
use std::ops::Deref;
use std::{default::Default, usize};
use chrono::NaiveTime;
use crate::fasttime::b2_time::TimeExt;
use crate::fasttime::a8_micros;
use std::iter::{IntoIterator, Iterator, ExactSizeIterator};
use std::ops::{Index, IndexMut};

pub trait CacheData: Default + Clone {
    fn time(&self) -> NaiveTime;
}

pub struct HighSpeedCache<T, const LEN: usize> {
    item: U<UnsafeData<T, LEN>>,
}

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

pub struct UnsafeData<T, const LEN: usize> {
    items: [T; LEN],
    index: usize,
    defalut_val: T,
    pub count: usize,
    待补数据: AtomicCell<Option<(usize, T)>>,
}

// HighSpeedCache 引用迭代器
pub struct HighSpeedCacheIter<'a, T, const LEN: usize> {
    cache: &'a HighSpeedCache<T, LEN>,
    current_index: usize,
    items_seen: usize,
    total_items: usize,
}

// HighSpeedCache 可变引用迭代器
pub struct HighSpeedCacheIterMut<'a, T, const LEN: usize> {
    cache: &'a mut HighSpeedCache<T, LEN>,
    current_index: usize,
    items_seen: usize,
    total_items: usize,
}

// 定义一个通用的缓存迭代器特征
trait CacheIteratorCore {
    fn get_cache_count(&self) -> usize;
    fn get_cache_index(&self) -> usize;
    fn get_current_index(&self) -> usize;
    fn get_items_seen(&self) -> usize;
    fn get_total_items(&self) -> usize;
    fn increment_counters(&mut self);
    
    // 计算当前元素的实际索引
    fn calculate_actual_index<const LEN: usize>(&self) -> Option<usize> {
        if self.get_items_seen() >= self.get_total_items() {
            return None;
        }
        
        // 循环方向从最新的元素开始遍历
        let idx = if self.get_cache_count() <= LEN {
            // 未满或刚好满,从最新的元素开始
            if self.get_current_index() >= self.get_cache_count() {
                return None;
            }
            // 最新的元素索引是 index,然后依次往前
            let newest_idx = self.get_cache_index();
            if self.get_current_index() <= newest_idx {
                newest_idx - self.get_current_index()
            } else {
                // 环绕到数组的尾部
                LEN - (self.get_current_index() - newest_idx)
            }
        } else {
            // 已满且溢出,从最新的元素(当前 index)开始
            let newest_idx = self.get_cache_index();
            (newest_idx + LEN - self.get_current_index()) % LEN
        };
        
        Some(idx)
    }
    
    // 为反向迭代计算实际的索引
    fn calculate_actual_index_for_back<const LEN: usize>(&self, back_index: usize) -> Option<usize> {
        let cache_index = self.get_cache_index();
        let cache_count = self.get_cache_count();
        
        // 计算实际索引,考虑环形缓冲区
        if back_index >= self.get_total_items() {
            return None;
        }
        
        let actual_index = if cache_count <= LEN {
            // 未满或刚好满,从最旧的元素开始
            if back_index >= cache_count {
                return None; // 超过范围
            }
            
            // 最旧的元素在缓存中的位置
            let oldest_index = if cache_index + 1 >= cache_count {
                // 还没有环绕,最旧的元素在索引 0
                0
            } else {
                // 已经环绕,最旧的元素在 (cache_index + 1) % LEN
                (cache_index + 1) % LEN
            };
            
            // 从最旧的元素开始计算
            (oldest_index + back_index) % LEN
        } else {
            // 已满且溢出,从最旧的元素开始
            // 最旧的元素在 (cache_index + 1) % LEN
            (cache_index + 1 + back_index) % LEN
        };
        
        Some(actual_index)
    }
}

impl<'a, T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIter<'a, T, LEN> {
    fn get_cache_count(&self) -> usize {
        self.cache.count
    }
    
    fn get_cache_index(&self) -> usize {
        self.cache.index
    }
    
    fn get_current_index(&self) -> usize {
        self.current_index
    }
    
    fn get_items_seen(&self) -> usize {
        self.items_seen
    }
    
    fn get_total_items(&self) -> usize {
        self.total_items
    }
    
    fn increment_counters(&mut self) {
        self.current_index += 1;
        self.items_seen += 1;
    }
}

// 为可变迭代器实现核心特征
impl<'a, T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIterMut<'a, T, LEN> {
    fn get_cache_count(&self) -> usize {
        self.cache.count
    }
    
    fn get_cache_index(&self) -> usize {
        self.cache.index
    }
    
    fn get_current_index(&self) -> usize {
        self.current_index
    }
    
    fn get_items_seen(&self) -> usize {
        self.items_seen
    }
    
    fn get_total_items(&self) -> usize {
        self.total_items
    }
    
    fn increment_counters(&mut self) {
        self.current_index += 1;
        self.items_seen += 1;
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(idx) = self.calculate_actual_index::<LEN>() {
            let item = &self.cache.items[idx];
            self.increment_counters();
            Some(item)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.get_total_items() - self.get_items_seen();
        (remaining, Some(remaining))
    }
}

impl<'a, T, const LEN: usize> DoubleEndedIterator for HighSpeedCacheIter<'a, T, LEN>
where
    T: CacheData,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.items_seen >= self.total_items {
            return None;
        }
        
        // 计算最后一个元素的索引
        let back_index = self.total_items - self.items_seen - 1;
        self.items_seen += 1;
        self.cache.get(back_index)
    }
}

// 实现可变迭代器
impl<'a, T, const LEN: usize> Iterator for HighSpeedCacheIterMut<'a, T, LEN> 
where
    T: CacheData,
{
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(idx) = self.calculate_actual_index::<LEN>() {
            // 使用 unsafe 来获取可变引用
            // 这是安全的,因为我们保证每次返回不同的索引
            let item = unsafe {
                let items_ptr = self.cache.item_mut().items.as_mut_ptr();
                &mut *items_ptr.add(idx)
            };
            self.increment_counters();
            Some(item)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.get_total_items() - self.get_items_seen();
        (remaining, Some(remaining))
    }
}

// 实现 ExactSizeIterator
impl<'a, T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIter<'a, T, LEN>
where
    T: CacheData,
{
    fn len(&self) -> usize {
        self.get_total_items() - self.get_items_seen()
    }
}

// 实现可变迭代器的 ExactSizeIterator
impl<'a, T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIterMut<'a, T, LEN>
where
    T: CacheData,
{
    fn len(&self) -> usize {
        self.get_total_items() - self.get_items_seen()
    }
}

// 实现 DoubleEndedIterator trait,支持从两端迭代
impl<'a, T, const LEN: usize> DoubleEndedIterator for HighSpeedCacheIterMut<'a, T, LEN>
where
    T: CacheData,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.items_seen >= self.total_items {
            return None;
        }
        
        // 计算最后一个元素的索引
        let back_index = self.total_items - self.items_seen - 1;
        
        // 使用 unsafe 来获取可变引用
        // 这是安全的,因为我们保证每次返回不同的索引
        if let Some(actual_index) = self.calculate_actual_index_for_back::<LEN>(back_index) {
            let item = unsafe {
                let items_ptr = self.cache.item_mut().items.as_mut_ptr();
                &mut *items_ptr.add(actual_index)
            };
            self.items_seen += 1;
            Some(item)
        } else {
            None
        }
    }
}

// 消费型迭代器
pub struct HighSpeedCacheIntoIter<T, const LEN: usize> {
    cache: HighSpeedCache<T, LEN>,
    current_index: usize,
    items_seen: usize,
    total_items: usize,
}

// 实现迭代器核心特征
impl<T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIntoIter<T, LEN> {
    fn get_cache_count(&self) -> usize {
        self.cache.count
    }
    
    fn get_cache_index(&self) -> usize {
        self.cache.index
    }
    
    fn get_current_index(&self) -> usize {
        self.current_index
    }
    
    fn get_items_seen(&self) -> usize {
        self.items_seen
    }
    
    fn get_total_items(&self) -> usize {
        self.total_items
    }
    
    fn increment_counters(&mut self) {
        self.current_index += 1;
        self.items_seen += 1;
    }
}

impl<T, const LEN: usize> Iterator for HighSpeedCacheIntoIter<T, LEN> 
where
    T: CacheData + Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(idx) = self.calculate_actual_index::<LEN>() {
            let item = self.cache.items[idx].clone();
            self.increment_counters();
            Some(item)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.get_total_items() - self.get_items_seen();
        (remaining, Some(remaining))
    }
}

// 实现 ExactSizeIterator
impl<T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIntoIter<T, LEN>
where
    T: CacheData + Clone,
{
    fn len(&self) -> usize {
        self.get_total_items() - self.get_items_seen()
    }
}

impl<T, const LEN: usize> HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    /// 创建一个新的高速缓存,与 Vec 的 with_capacity 方法类似
    /// 注意:因为内部已经使用固定大小的数组,参数 capacity 仅用于保持 API 风格一致性
    pub fn with_capacity(_capacity: usize) -> Self {
        Self::new()
    }
    
    pub fn new() -> Self {
        // TODO: 生成 [T; LEN]
        // 当前报错: error[E0277]: the trait bound `T: std::marker::Copy` is not satisfied
        // 请在不实现 copy 的情况下, 帮我修改这里的代码, 让它编译通过
        let items: [T; LEN] = std::array::from_fn(|_i| T::default());
        let item = UnsafeData {
            items,
            index: 0,
            count: 0,
            defalut_val: T::default(),
            待补数据: AtomicCell::new(None),
        };
        Self { item: item.into() }
    }

    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 let Some((i, d)) = self.待补数据.swap(None) {
            self_item.items[i] = d;
        }

        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] = item_new;
        self_item.count += 1;
    }

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

    /// 请控制此方法不可并发访问
    pub fn clear(&self) {
        let self_item = self.item_mut();
        self_item.index = 0;
        self_item.count = 0;
        // 第1条数据要清空,并无实质数据。
        self_item.items[0] = T::default();
    }

    /// 传参:毫秒
    /// 如果找不到精确定位的数据, 则返回最新的那条数据
    pub fn find_找之前的项(&self, 毫秒数: i64, is_找不到即取最新数据: bool) -> Option<&T> {
        if self.count == 0 {
            return None;
        }
        let capacity = self.items.len();
        // 将微秒数转为 u64,但只在非负当前情况才如此
        let 微秒数 = if 毫秒数 >= 0 {
            毫秒数 as u64 * a8_micros::MICROS_PER_MILLIS
        } else {
            0
        };

        let ticks_当前项 = self.items[self.index].time().micros_of_day();
        let index_当前索引 = self.index;

        let mut find_最新 = Option::<&T>::None;
        for idx in (0..index_当前索引).rev() {
            let ticks_往前项 = self.items[idx].time().micros_of_day();
            if ticks_往前项 == 0 {
                continue;
            }
            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
            if delta_往前微秒数 > 微秒数 {
                return Some(&self.items[idx]);
            }

            // 修复: 如果找不到精确定位的数据, 则返回最新的那条数据; 从vec后面开始循环, 第一条数据就是最新的
            if is_找不到即取最新数据 {
                match &find_最新 {
                    None => {
                        find_最新 = Some(&self.items[idx]);
                    }
                    _ => (),
                }
            }
        }

        if self.count <= LEN {
            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
            return Some(find_最新.unwrap_or_else(|| &self.item.as_ref().defalut_val));
        }

        // 从数组后面开始找
        for idx in ((index_当前索引 + 1)..capacity).rev() {
            let item = &self.items[idx];
            let ticks_往前项 = item.time().micros_of_day();
            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
            if ticks_往前项 > 0 && delta_往前微秒数 > 微秒数 {
                return Some(item);

                // 修复: 找前封单时刚好在前一段找不到数据, 再从后面开始找, 匹配到最后一个数据, 但却拿到第一个下标的初始值
                // if idx + 1 == capacity {
                //     return &self.items[0];
                // } else {
                //     return item;
                // }
            }
        }

        return find_最新;
    }

    /// 如果十档或者前封单数据如果出现断档的情况,那么把前一个数据的时间戳改成现在数据并且减10毫秒
    /// 下次找数据时可以直接找到这一条
    // fn 向前补一个数据(&self) -> Option<T> {
    //     let idx = if self.index == 0 && self.count >= LEN {
    //         LEN - 1
    //     } else if self.index > 0 {
    //         self.index - 1
    //     } else {
    //         // index 等于零, 没有数据的情况
    //         return None;
    //     };

    //     let mut item = self.items[idx].clone();
    //     let millis = self.current().time().micros_of_day() - 10 * 1000;
    //     let time = NaiveTime::from_micros_day_unsafe(millis);
    //     item.set_time_发生时间(time);
    //     self.待补数据.store(Some((idx, item.clone())));
    //     return Some(item);
    // }

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

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

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

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

    /// 找到范围内最大的值
    /// n: 毫秒数
    /// is_return_last: true; 两秒内最大值找不到, 即找一个最新的数据
    /// compare: 比较两个值, 返回true则使用新的值
    /// 
    /// TODO: 不要使用补数据的逻辑, 找不到数据即取一个最新的数据
    pub fn find_limit<F: Fn(&T, &T) -> bool>(
        &self,
        n: i64,
        is_return_last: bool,
        compare: F,
    ) -> T {
        let items = self.list_items(n);
        let 补一个数据 = None;

        if (items.is_empty() || items.len() == 1) && is_return_last {
            // TODO: 注释掉不存在的方法调用
            // 补一个数据 = self.向前补一个数据();
        }

        if items.is_empty() {
            return 补一个数据.unwrap_or_else(|| self.defalut_val.clone());
        }

        let mut find_v = items[0];
        for item in items.iter().skip(1) {
            if compare(&find_v, item) {
                find_v = item;
            }
        }

        if let Some(v) = &补一个数据 {
            if compare(&find_v, v) {
                find_v = v;
            }
        }

        return find_v.clone();
    }

    /// 传参:找多少个
    pub fn list_items_len(&self, mut count: usize) -> Vec<&T> {
        if self.count == 0 {
            return vec![];
        }
        let mut items = vec![];

        let 当前项 = &self.items[self.index];
        items.push(当前项);

        let index_当前索引 = self.index;
        for idx in (0..index_当前索引).rev() {
            if count == 0 {
                return items;
            }
            items.push(&self.items[idx]);
            count -= 1;
        }

        if self.count <= LEN {
            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
            return items;
        }

        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
            if count == 0 {
                return items;
            }
            items.push(&self.items[idx]);
            count -= 1;
        }
        items
    }

    /// 传参:毫秒
    pub fn list_items(&self, 毫秒数: i64) -> Vec<&T> {
        if self.count == 0 {
            return vec![];
        }
        let mut items = vec![];

        // 将微秒数转为 u64,但只在非负当前情况才如此
        let 微秒数 = if 毫秒数 as i64 >= 0 {
            毫秒数 as u64 * a8_micros::MICROS_PER_MILLIS
        } else {
            0
        };

        let 当前项 = &self.items[self.index];
        items.push(当前项);

        let ticks_当前项 = 当前项.time().micros_of_day();
        let index_当前索引 = self.index;
        for idx in (0..index_当前索引).rev() {
            let ticks_往前项 = self.items[idx].time().micros_of_day();
            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
            if delta_往前微秒数 > 微秒数 {
                // return items;
                break;
            }
            items.push(&self.items[idx]);
        }
        if self.count <= LEN {
            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
            return items;
        }

        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
            let ticks_往前项 = self.items[idx].time().micros_of_day();
            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
            if delta_往前微秒数 > 微秒数 {
                return items;
            }
            // 是不是少了这句代码? todo 志松
            items.push(&self.items[idx]);
        }
        items
    }

    // 补数据, 十档数据有可能在N秒后才有新数据, 逐笔同理, 把之前缺失的数据补上(10毫秒一个)
    /* pub fn update_补数据(&mut self, last: TimeFT) {
        let last_ticks = last.micros_of_day();

        if self.current().time().micros_of_day() + 10 >= last_ticks {
            return;
        }

        let mut 最新时间的数据 = Option::<T>::None;
        for ele in &self.items {
            match 最新时间的数据{
                Some(v) => {
                    if v.time().micros_of_day() <= ele.time().micros_of_day() {
                        最新时间的数据 = Some(ele.clone());
                    }
                },
                None => {
                    最新时间的数据 = Some(ele.clone());
                }
            }
        }

        let mut 内存_最新数据 = match 最新时间的数据 {
            Some(v) => v,
            None => return,
        };

        let mut 内存_最新数据时间 = 内存_最新数据.time().micros_of_day();

        while last_ticks > 内存_最新数据时间 + 10{
            内存_最新数据时间 += 10;
            内存_最新数据.set_接收时间(TimeFT::from_micros_day_unsafe(内存_最新数据时间));
            self.push(&内存_最新数据);
        }

    } */
}

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

impl<T, const LEN: usize> HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    /// 返回缓存中的元素数量
    pub fn len(&self) -> usize {
        // 返回实际可迭代的元素数量,不能超过缓存容量
        self.count.min(LEN)
    }
    
    /// 检查缓存是否为空
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }
    
    /// 返回缓存的容量(最大可存储元素数)
    pub fn capacity(&self) -> usize {
        LEN
    }
    
    /// 根据索引获取元素的引用
    pub fn get(&self, index: usize) -> Option<&T> {
        if index >= self.count {
            return None;
        }
        
        // 计算实际索引,考虑环形缓冲区
        let actual_index = if self.count <= LEN {
            // 未满或刚好满,从最新的元素开始
            // 最新的元素索引是 index,然后依次往前
            if index <= self.index {
                self.index - index
            } else {
                // 环绕到数组的尾部
                LEN - (index - self.index)
            }
        } else {
            // 已满且溢出,从最新的元素开始
            (self.index + LEN - index) % LEN
        };
        
        Some(&self.item.as_ref().items[actual_index])
    }
    
    /// 获取元素的可变引用
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if index >= self.count {
            return None;
        }
        
        // 计算实际索引,考虑环形缓冲区
        let actual_index = if self.count <= LEN {
            // 未满或刚好满,从最新的元素开始
            if index >= self.count {
                return None; // 超过范围
            }
            // 最新的元素索引是 index,然后依次往前
            if index <= self.index {
                self.index - index
            } else {
                // 环绕到数组的尾部
                LEN - (index - self.index)
            }
        } else {
            // 已满且溢出,从最新的元素开始
            (self.index + LEN - index) % LEN
        };
        
        Some(&mut self.item_mut().items[actual_index])
    }
    
    /// 返回一个引用迭代器,按从最新到最旧的顺序
    pub fn iter(&self) -> HighSpeedCacheIter<T, LEN> {
        HighSpeedCacheIter {
            cache: self,
            current_index: 0,
            items_seen: 0,
            total_items: self.len(),
        }
    }
    
    /// 返回一个可变引用迭代器,按从最新到最旧的顺序
    pub fn iter_mut(&mut self) -> HighSpeedCacheIterMut<T, LEN> {
        // 先获取长度,避免后续的借用冲突
        let total = self.len();
        HighSpeedCacheIterMut {
            cache: self,
            current_index: 0,
            items_seen: 0,
            total_items: total,
        }
    }
    
    /// 转换为 Vec
    pub fn to_vec(&self) -> Vec<T> 
    where
        T: Clone,
    {
        self.iter().cloned().collect()
    }
}

// 实现 IntoIterator trait,允许在 for 循环中使用(引用)
impl<'a, T, const LEN: usize> IntoIterator for &'a HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    type Item = &'a T;
    type IntoIter = HighSpeedCacheIter<'a, T, LEN>;
    
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

// 实现 IntoIterator trait,允许在 for 循环中使用(可变引用)
impl<'a, T, const LEN: usize> IntoIterator for &'a mut HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    type Item = &'a mut T;
    type IntoIter = HighSpeedCacheIterMut<'a, T, LEN>;
    
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

// 注意:我们不需要为 HighSpeedCacheIter 和 HighSpeedCacheIterMut 实现 IntoIterator
// 因为标准库已经为所有实现了 Iterator trait 的类型自动实现了 IntoIterator

// 实现 IntoIterator trait,允许消费型迭代
// 实现 Index trait
impl<T, const LEN: usize> Index<usize> for HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    type Output = T;
    
    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("索引超出范围")
    }
}

// 实现 IndexMut trait
impl<T, const LEN: usize> IndexMut<usize> for HighSpeedCache<T, LEN>
where
    T: CacheData,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).expect("索引超出范围")
    }
}

impl<T, const LEN: usize> IntoIterator for HighSpeedCache<T, LEN>
where
    T: CacheData + Clone,
{
    type Item = T;
    type IntoIter = HighSpeedCacheIntoIter<T, LEN>;
    
    fn into_iter(self) -> Self::IntoIter {
        let total = self.len();
        HighSpeedCacheIntoIter {
            cache: self,
            current_index: 0,
            items_seen: 0,
            total_items: total,
        }
    }
}

#[cfg(test)]
mod test_高频数据 {
    use chrono::NaiveTime;
    use crate::fasttime::b2_time::TimeExt;

    use super::{CacheData, HighSpeedCache};

    #[derive(Debug, Default, Clone, PartialEq, Eq)]
    struct Demo_高频数据 {
        pub time_发生时间: NaiveTime,
        pub time_接收时间: NaiveTime,
        pub val: i32,
    }

    impl CacheData for Demo_高频数据 {
        fn time(&self) -> NaiveTime {
            self.time_发生时间
        }
    }

    #[test]
    fn test_demo_高频数据() {
        let HighSpeedCache = HighSpeedCache::<Demo_高频数据, 1000>::new();

        // 使用固定增量代替随机数,避免依赖 rand
        let mut micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        for val in 1..1000 {
            let time_发生时间 = NaiveTime::from_micros_day_unsafe(micros);
            micros += 100; // 固定增加100微秒

            HighSpeedCache.push(Demo_高频数据 {
                time_发生时间,
                time_接收时间: time_发生时间,
                val,
            });
            _ = HighSpeedCache.find_找之前的项(30_000, false);
        }
    }
    
    #[test]
    fn test_高频数据_迭代器() {
        // 1. 测试空缓存
        let cache_empty = HighSpeedCache::<Demo_高频数据, 10>::new();
        assert_eq!(cache_empty.len(), 0);
        assert!(cache_empty.is_empty());
        assert_eq!(cache_empty.capacity(), 10);
        
        // 检查空缓存的迭代是否正确
        let mut iter_count = 0;
        for _ in &cache_empty {
            iter_count += 1;
        }
        assert_eq!(iter_count, 0, "空缓存不应该有任何元素可迭代");
        assert_eq!(cache_empty.get(0), None, "空缓存的get应返回None");
        
        // 2. 测试未满缓存
        let cache_partial = HighSpeedCache::<Demo_高频数据, 10>::new();
        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        
        // 添加5个元素
        for val in 1..6 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_partial.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        assert_eq!(cache_partial.len(), 5);
        assert!(!cache_partial.is_empty());
        
        // 测试迭代器顺序 (从最新到最旧)
        let items: Vec<i32> = cache_partial.iter().map(|item| item.val).collect();
        assert_eq!(items, vec![5, 4, 3, 2, 1]);
        
        // 使用 rev() 返回旧元素到新的顺序
        let items_rev: Vec<i32> = cache_partial.iter().rev().map(|item| item.val).collect();
        assert_eq!(items_rev, vec![1, 2, 3, 4, 5]);
        
        // 测试get方法 - 现在是从最新到最旧
        assert_eq!(cache_partial.get(0).map(|item| item.val), Some(5)); // 索引0是最新的元素
        assert_eq!(cache_partial.get(4).map(|item| item.val), Some(1)); // 索引4是最旧的元素
        assert_eq!(cache_partial.get(5), None); // 超出范围
        
        // 测试索引器访问
        assert_eq!(cache_partial[0].val, 5);
        assert_eq!(cache_partial[4].val, 1);
        
        // 3. 测试已满并且环绕的缓存 (用一个更小的缓存容量便于测试)
        let cache_full = HighSpeedCache::<Demo_高频数据, 3>::new();
        
        // 添加5个元素到容量为3的缓存,导致环绕
        for val in 1..6 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_full.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        assert_eq!(cache_full.len(), 3);
        assert_eq!(cache_full.count, 5); // 内部计数应该是5,但实际长度限制为3
        
        // 检验迭代结果 - 应该只有最新的3个元素,现在是从最新到最旧
        let items_full: Vec<i32> = cache_full.iter().map(|item| item.val).collect();
        assert_eq!(items_full, vec![5, 4, 3]);
        
        // 测试 with_capacity 方法
        let cache_with_cap = HighSpeedCache::<Demo_高频数据, 5>::with_capacity(100);
        assert_eq!(cache_with_cap.capacity(), 5); // 容量仍然由模板参数决定
        
        // 测试to_vec方法
        let vec_items = cache_full.to_vec();
        assert_eq!(vec_items.len(), 3);
        assert_eq!(vec_items[0].val, 5);
        assert_eq!(vec_items[2].val, 3);
        
        // 4. 测试into_iter消费迭代器
        let cache_consume = HighSpeedCache::<Demo_高频数据, 3>::new();
        
        // 添加3个元素
        for val in 1..4 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_consume.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 使用into_iter消费缓存
        let consumed: Vec<Demo_高频数据> = cache_consume.into_iter().collect();
        assert_eq!(consumed.len(), 3);
        assert_eq!(consumed[0].val, 3); // 现在是从最新到最旧
        assert_eq!(consumed[2].val, 1);
        
        // 测试IndexMut,修改元素
        let mut cache_mut = HighSpeedCache::<Demo_高频数据, 3>::new();
        
        // 添加3个元素
        for val in 1..4 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_mut.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 使用索引器修改第一个元素(最新的)
        cache_mut[0].val = 100;
        assert_eq!(cache_mut[0].val, 100);
        
        // 验证ExactSizeIterator
        let cache_exact = HighSpeedCache::<Demo_高频数据, 5>::new();
        for val in 1..4 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_exact.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        let iter = cache_exact.iter();
        assert_eq!(iter.len(), 3);
        
        let mut iter2 = cache_exact.iter();
        iter2.next(); // 消费一个元素
        assert_eq!(iter2.len(), 2); // 长度应该减少
    }
    
    #[test]
    fn test_索引器_异常处理() {
        // 测试空缓存索引访问
        {
            let cache = HighSpeedCache::<Demo_高频数据, 5>::new();
            // 不使用 catch_unwind 来避免 UnwindSafe 问题
            // 而是直接检查是否为空
            assert_eq!(cache.len(), 0);
            assert!(cache.is_empty());
            // 手动验证 get 返回 None
            assert_eq!(cache.get(0), None);
        }
        
        // 填充一些数据
        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        // 注意:这里不需要 mut,因为 push 方法接受 &self
        let cache_with_data = HighSpeedCache::<Demo_高频数据, 5>::new();
        for val in 1..4 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_with_data.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 访问有效索引
        assert_eq!(cache_with_data.get(0).map(|item| item.val), Some(3));
        assert_eq!(cache_with_data.get(1).map(|item| item.val), Some(2));
        assert_eq!(cache_with_data.get(2).map(|item| item.val), Some(1));
        
        // 访问超出范围的索引
        assert_eq!(cache_with_data.get(3), None, "超范围索引应该返回 None");
        assert_eq!(cache_with_data.get(100), None, "远超范围索引应该返回 None");
    }
    
    #[test]
    fn test_iter_mut() {
        // 创建缓存并填充数据
        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        let mut cache = HighSpeedCache::<Demo_高频数据, 5>::new();
        
        // 添加5个元素
        for val in 1..6 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 使用 iter_mut 修改所有元素
        for item in cache.iter_mut() {
            let val = &mut item.val;
            *val *= 10; // 将每个元素的 val 乘以 10
        }
        
        // 验证修改是否生效
        let values: Vec<i32> = cache.iter().map(|item| item.val).collect();
        assert_eq!(values, vec![50, 40, 30, 20, 10]); // 从最新到最旧
        
        // 测试部分修改
        let mut iter = cache.iter_mut();
        if let Some(item) = iter.next() {
            item.val = 100; // 修改最新的元素
        }
        if let Some(item) = iter.next() {
            item.val = 200; // 修改第二新的元素
        }
        
        // 验证部分修改是否生效
        assert_eq!(cache[0].val, 100); // 最新的元素
        assert_eq!(cache[1].val, 200); // 第二新的元素
        assert_eq!(cache[2].val, 30);  // 其他元素保持不变
        
        // 测试 ExactSizeIterator 实现
        let mut iter_mut = cache.iter_mut();
        assert_eq!(iter_mut.len(), 5);
        iter_mut.next();
        assert_eq!(iter_mut.len(), 4);
        iter_mut.next();
        assert_eq!(iter_mut.len(), 3);
    }
    
    #[test]
    fn test_iter_rev() {
        // 创建缓存并填充数据
        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        let cache = HighSpeedCache::<Demo_高频数据, 5>::new();
        
        // 添加5个元素
        for val in 1..6 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 测试 iter().rev() - 从最旧到最新
        let values: Vec<i32> = cache.iter().rev().map(|item| item.val).collect();
        assert_eq!(values, vec![1, 2, 3, 4, 5]); // 从最旧到最新
        
        // 测试 iter_mut().rev() - 从最旧到最新
        let mut cache_mut = HighSpeedCache::<Demo_高频数据, 5>::new();
        
        // 添加5个元素
        for val in 1..6 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache_mut.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 使用 iter_mut().rev() 修改所有元素
        for item in cache_mut.iter_mut().rev() {
            let val = &mut item.val;
            *val *= 10; // 将每个元素的 val 乘以 10
        }
        
        // 验证修改是否生效 - 应该是从最旧到最新的顺序修改的
        let values: Vec<i32> = cache_mut.iter().map(|item| item.val).collect();
        assert_eq!(values, vec![50, 40, 30, 20, 10]); // 从最新到最旧
        
        // 测试 for 循环中使用 &mut cache 进行可变迭代
        let mut cache2 = HighSpeedCache::<Demo_高频数据, 3>::new();
        for val in 1..4 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            cache2.push(Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            });
        }
        
        // 使用 &mut 语法直接迭代并修改
        for item in &mut cache2 {
            item.val += 100;
        }
        
        // 验证修改是否生效
        assert_eq!(cache2[0].val, 103); // 最新的元素
        assert_eq!(cache2[1].val, 102); // 第二新的元素
        assert_eq!(cache2[2].val, 101); // 最旧的元素
    }
    
    #[test]
    fn test_完整迭代器行为() {
        // 创建缓存并填充数据
        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
        let mut cache = HighSpeedCache::<Demo_高频数据, 10>::new();
        
        // 添加元素并记录原始值
        let mut original_values = Vec::new();
        for val in 1..11 {
            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
            let item = Demo_高频数据 {
                time_发生时间: time,
                time_接收时间: time,
                val,
            };
            original_values.push(item.clone());
            cache.push(item);
        }
        
        // 测试容量和长度
        assert_eq!(cache.capacity(), 10);
        assert_eq!(cache.len(), 10);
        assert!(!cache.is_empty());
        
        // 1. 测试正向迭代器完整性 - 从最新到最旧
        let mut iter_values = Vec::new();
        for item in &cache {
            iter_values.push(item.val);
        }
        // 验证顺序是否正确(从最新到最旧)
        assert_eq!(iter_values, vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
        
        // 2. 测试反向迭代器完整性 - 从最旧到最新
        let mut rev_iter_values = Vec::new();
        for item in cache.iter().rev() {
            rev_iter_values.push(item.val);
        }
        // 验证顺序是否正确(从最旧到最新)
        assert_eq!(rev_iter_values, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        
        // 3. 测试可变迭代器完整性 - 从最新到最旧
        let mut modified_values = Vec::new();
        for item in cache.iter_mut() {
            item.val *= 2; // 将每个值翻倍
            modified_values.push(item.val);
        }
        // 验证顺序和修改是否正确
        assert_eq!(modified_values, vec![20, 18, 16, 14, 12, 10, 8, 6, 4, 2]);
        
        // 4. 测试可变反向迭代器完整性 - 从最旧到最新
        let mut rev_modified_values = Vec::new();
        for item in cache.iter_mut().rev() {
            item.val += 5; // 每个值加 5
            rev_modified_values.push(item.val);
        }
        // 验证顺序和修改是否正确
        assert_eq!(rev_modified_values, vec![25, 23, 21, 19, 17, 15, 13, 11, 9, 7]);
        
        // 5. 测试索引器访问
        for i in 0..cache.len() {
            // 验证索引器访问的值与迭代器一致
            assert_eq!(cache[i].val, 25 - i as i32 * 2);
        }
        
        // 6. 测试越界处理
        assert!(cache.get(cache.len()).is_none());
        assert!(cache.get(100).is_none());
        
        // 7. 测试环形缓冲区的覆盖行为
        // 添加新元素覆盖最旧的元素
        let new_val = 100;
        let time = NaiveTime::from_micros_day_unsafe(base_micros + (new_val as u64 * 100));
        cache.push(Demo_高频数据 {
            time_发生时间: time,
            time_接收时间: time,
            val: new_val,
        });
        
        // 验证最新元素是否正确
        assert_eq!(cache[0].val, new_val);
        
        // 验证最旧的元素已被覆盖
        let values: Vec<i32> = cache.iter().map(|item| item.val).collect();
        assert_eq!(values.len(), 10); // 长度不变
        assert_eq!(values[0], new_val); // 最新的是新添加的
        assert_eq!(values[9], 9); // 最旧的元素已经不是 1 了
        
        // 8. 测试 ExactSizeIterator 实现
        let mut iter = cache.iter();
        assert_eq!(iter.len(), 10);
        iter.next();
        assert_eq!(iter.len(), 9);
        
        // 9. 测试空缓存的迭代器行为
        let empty_cache = HighSpeedCache::<Demo_高频数据, 5>::new();
        assert_eq!(empty_cache.len(), 0);
        assert!(empty_cache.is_empty());
        assert_eq!(empty_cache.iter().count(), 0);
        assert_eq!(empty_cache.iter().rev().count(), 0);
    }
}