fast_able/
high_speed_cache.rs

1// High frequency data
2// 高频数据
3
4use crossbeam::atomic::AtomicCell;
5use crate::unsafe_cell_type::U;
6use std::ops::Deref;
7use std::{default::Default, usize};
8use chrono::NaiveTime;
9use crate::fasttime::b2_time::TimeExt;
10use crate::fasttime::a8_micros;
11use std::iter::{IntoIterator, Iterator, ExactSizeIterator};
12use std::ops::{Index, IndexMut};
13
14pub trait CacheData: Default + Clone {
15    fn time(&self) -> NaiveTime;
16}
17
18pub struct HighSpeedCache<T, const LEN: usize> {
19    item: U<UnsafeData<T, LEN>>,
20}
21
22impl<T, const LEN: usize> Deref for HighSpeedCache<T, LEN> {
23    type Target = UnsafeData<T, LEN>;
24    fn deref(&self) -> &Self::Target {
25        self.item.as_ref()
26    }
27}
28
29pub struct UnsafeData<T, const LEN: usize> {
30    items: [T; LEN],
31    index: usize,
32    defalut_val: T,
33    pub count: usize,
34    待补数据: AtomicCell<Option<(usize, T)>>,
35}
36
37// HighSpeedCache reference iterator
38// HighSpeedCache 引用迭代器
39pub struct HighSpeedCacheIter<'a, T, const LEN: usize> {
40    cache: &'a HighSpeedCache<T, LEN>,
41    current_index: usize,
42    items_seen: usize,
43    total_items: usize,
44}
45
46// HighSpeedCache mutable reference iterator
47// HighSpeedCache 可变引用迭代器
48pub struct HighSpeedCacheIterMut<'a, T, const LEN: usize> {
49    cache: &'a mut HighSpeedCache<T, LEN>,
50    current_index: usize,
51    items_seen: usize,
52    total_items: usize,
53}
54
55// 定义一个通用的缓存迭代器特征
56trait CacheIteratorCore {
57    fn get_cache_count(&self) -> usize;
58    fn get_cache_index(&self) -> usize;
59    fn get_current_index(&self) -> usize;
60    fn get_items_seen(&self) -> usize;
61    fn get_total_items(&self) -> usize;
62    fn increment_counters(&mut self);
63    
64    // 计算当前元素的实际索引
65    fn calculate_actual_index<const LEN: usize>(&self) -> Option<usize> {
66        if self.get_items_seen() >= self.get_total_items() {
67            return None;
68        }
69        
70        // 循环方向从最新的元素开始遍历
71        let idx = if self.get_cache_count() <= LEN {
72            // 未满或刚好满,从最新的元素开始
73            if self.get_current_index() >= self.get_cache_count() {
74                return None;
75            }
76            // 最新的元素索引是 index,然后依次往前
77            let newest_idx = self.get_cache_index();
78            if self.get_current_index() <= newest_idx {
79                newest_idx - self.get_current_index()
80            } else {
81                // 环绕到数组的尾部
82                LEN - (self.get_current_index() - newest_idx)
83            }
84        } else {
85            // 已满且溢出,从最新的元素(当前 index)开始
86            let newest_idx = self.get_cache_index();
87            (newest_idx + LEN - self.get_current_index()) % LEN
88        };
89        
90        Some(idx)
91    }
92    
93    // 为反向迭代计算实际的索引
94    fn calculate_actual_index_for_back<const LEN: usize>(&self, back_index: usize) -> Option<usize> {
95        let cache_index = self.get_cache_index();
96        let cache_count = self.get_cache_count();
97        
98        // 计算实际索引,考虑环形缓冲区
99        if back_index >= self.get_total_items() {
100            return None;
101        }
102        
103        let actual_index = if cache_count <= LEN {
104            // 未满或刚好满,从最旧的元素开始
105            if back_index >= cache_count {
106                return None; // 超过范围
107            }
108            
109            // 最旧的元素在缓存中的位置
110            let oldest_index = if cache_index + 1 >= cache_count {
111                // 还没有环绕,最旧的元素在索引 0
112                0
113            } else {
114                // 已经环绕,最旧的元素在 (cache_index + 1) % LEN
115                (cache_index + 1) % LEN
116            };
117            
118            // 从最旧的元素开始计算
119            (oldest_index + back_index) % LEN
120        } else {
121            // 已满且溢出,从最旧的元素开始
122            // 最旧的元素在 (cache_index + 1) % LEN
123            (cache_index + 1 + back_index) % LEN
124        };
125        
126        Some(actual_index)
127    }
128}
129
130impl<'a, T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIter<'a, T, LEN> {
131    fn get_cache_count(&self) -> usize {
132        self.cache.count
133    }
134    
135    fn get_cache_index(&self) -> usize {
136        self.cache.index
137    }
138    
139    fn get_current_index(&self) -> usize {
140        self.current_index
141    }
142    
143    fn get_items_seen(&self) -> usize {
144        self.items_seen
145    }
146    
147    fn get_total_items(&self) -> usize {
148        self.total_items
149    }
150    
151    fn increment_counters(&mut self) {
152        self.current_index += 1;
153        self.items_seen += 1;
154    }
155}
156
157// 为可变迭代器实现核心特征
158impl<'a, T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIterMut<'a, T, LEN> {
159    fn get_cache_count(&self) -> usize {
160        self.cache.count
161    }
162    
163    fn get_cache_index(&self) -> usize {
164        self.cache.index
165    }
166    
167    fn get_current_index(&self) -> usize {
168        self.current_index
169    }
170    
171    fn get_items_seen(&self) -> usize {
172        self.items_seen
173    }
174    
175    fn get_total_items(&self) -> usize {
176        self.total_items
177    }
178    
179    fn increment_counters(&mut self) {
180        self.current_index += 1;
181        self.items_seen += 1;
182    }
183}
184
185impl<'a, T, const LEN: usize> Iterator for HighSpeedCacheIter<'a, T, LEN> 
186where
187    T: CacheData,
188{
189    type Item = &'a T;
190
191    fn next(&mut self) -> Option<Self::Item> {
192        if let Some(idx) = self.calculate_actual_index::<LEN>() {
193            let item = &self.cache.items[idx];
194            self.increment_counters();
195            Some(item)
196        } else {
197            None
198        }
199    }
200
201    fn size_hint(&self) -> (usize, Option<usize>) {
202        let remaining = self.get_total_items() - self.get_items_seen();
203        (remaining, Some(remaining))
204    }
205}
206
207impl<'a, T, const LEN: usize> DoubleEndedIterator for HighSpeedCacheIter<'a, T, LEN>
208where
209    T: CacheData,
210{
211    fn next_back(&mut self) -> Option<Self::Item> {
212        if self.items_seen >= self.total_items {
213            return None;
214        }
215        
216        // 计算最后一个元素的索引
217        let back_index = self.total_items - self.items_seen - 1;
218        self.items_seen += 1;
219        self.cache.get(back_index)
220    }
221}
222
223// 实现可变迭代器
224impl<'a, T, const LEN: usize> Iterator for HighSpeedCacheIterMut<'a, T, LEN> 
225where
226    T: CacheData,
227{
228    type Item = &'a mut T;
229
230    fn next(&mut self) -> Option<Self::Item> {
231        if let Some(idx) = self.calculate_actual_index::<LEN>() {
232            // 使用 unsafe 来获取可变引用
233            // 这是安全的,因为我们保证每次返回不同的索引
234            let item = unsafe {
235                let items_ptr = self.cache.item_mut().items.as_mut_ptr();
236                &mut *items_ptr.add(idx)
237            };
238            self.increment_counters();
239            Some(item)
240        } else {
241            None
242        }
243    }
244
245    fn size_hint(&self) -> (usize, Option<usize>) {
246        let remaining = self.get_total_items() - self.get_items_seen();
247        (remaining, Some(remaining))
248    }
249}
250
251// 实现 ExactSizeIterator
252impl<'a, T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIter<'a, T, LEN>
253where
254    T: CacheData,
255{
256    fn len(&self) -> usize {
257        self.get_total_items() - self.get_items_seen()
258    }
259}
260
261// 实现可变迭代器的 ExactSizeIterator
262impl<'a, T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIterMut<'a, T, LEN>
263where
264    T: CacheData,
265{
266    fn len(&self) -> usize {
267        self.get_total_items() - self.get_items_seen()
268    }
269}
270
271// 实现 DoubleEndedIterator trait,支持从两端迭代
272impl<'a, T, const LEN: usize> DoubleEndedIterator for HighSpeedCacheIterMut<'a, T, LEN>
273where
274    T: CacheData,
275{
276    fn next_back(&mut self) -> Option<Self::Item> {
277        if self.items_seen >= self.total_items {
278            return None;
279        }
280        
281        // 计算最后一个元素的索引
282        let back_index = self.total_items - self.items_seen - 1;
283        
284        // 使用 unsafe 来获取可变引用
285        // 这是安全的,因为我们保证每次返回不同的索引
286        if let Some(actual_index) = self.calculate_actual_index_for_back::<LEN>(back_index) {
287            let item = unsafe {
288                let items_ptr = self.cache.item_mut().items.as_mut_ptr();
289                &mut *items_ptr.add(actual_index)
290            };
291            self.items_seen += 1;
292            Some(item)
293        } else {
294            None
295        }
296    }
297}
298
299// 消费型迭代器
300pub struct HighSpeedCacheIntoIter<T, const LEN: usize> {
301    cache: HighSpeedCache<T, LEN>,
302    current_index: usize,
303    items_seen: usize,
304    total_items: usize,
305}
306
307// 实现迭代器核心特征
308impl<T, const LEN: usize> CacheIteratorCore for HighSpeedCacheIntoIter<T, LEN> {
309    fn get_cache_count(&self) -> usize {
310        self.cache.count
311    }
312    
313    fn get_cache_index(&self) -> usize {
314        self.cache.index
315    }
316    
317    fn get_current_index(&self) -> usize {
318        self.current_index
319    }
320    
321    fn get_items_seen(&self) -> usize {
322        self.items_seen
323    }
324    
325    fn get_total_items(&self) -> usize {
326        self.total_items
327    }
328    
329    fn increment_counters(&mut self) {
330        self.current_index += 1;
331        self.items_seen += 1;
332    }
333}
334
335impl<T, const LEN: usize> Iterator for HighSpeedCacheIntoIter<T, LEN> 
336where
337    T: CacheData + Clone,
338{
339    type Item = T;
340
341    fn next(&mut self) -> Option<Self::Item> {
342        if let Some(idx) = self.calculate_actual_index::<LEN>() {
343            let item = self.cache.items[idx].clone();
344            self.increment_counters();
345            Some(item)
346        } else {
347            None
348        }
349    }
350
351    fn size_hint(&self) -> (usize, Option<usize>) {
352        let remaining = self.get_total_items() - self.get_items_seen();
353        (remaining, Some(remaining))
354    }
355}
356
357// 实现 ExactSizeIterator
358impl<T, const LEN: usize> ExactSizeIterator for HighSpeedCacheIntoIter<T, LEN>
359where
360    T: CacheData + Clone,
361{
362    fn len(&self) -> usize {
363        self.get_total_items() - self.get_items_seen()
364    }
365}
366
367impl<T, const LEN: usize> HighSpeedCache<T, LEN>
368where
369    T: CacheData,
370{
371    /// 创建一个新的高速缓存,与 Vec 的 with_capacity 方法类似
372    /// 注意:因为内部已经使用固定大小的数组,参数 capacity 仅用于保持 API 风格一致性
373    pub fn with_capacity(_capacity: usize) -> Self {
374        Self::new()
375    }
376    
377    pub fn new() -> Self {
378        // TODO: 生成 [T; LEN]
379        // 当前报错: error[E0277]: the trait bound `T: std::marker::Copy` is not satisfied
380        // 请在不实现 copy 的情况下, 帮我修改这里的代码, 让它编译通过
381        let items: [T; LEN] = std::array::from_fn(|_i| T::default());
382        let item = UnsafeData {
383            items,
384            index: 0,
385            count: 0,
386            defalut_val: T::default(),
387            待补数据: AtomicCell::new(None),
388        };
389        Self { item: item.into() }
390    }
391
392    fn item_mut(&self) -> &mut UnsafeData<T, LEN> {
393        self.item.as_mut()
394    }
395
396    /// 添加1项
397    /// 请控制此方法不可并发访问
398    pub fn push(&self, item_new: T) {
399        let self_item = self.item_mut();
400        if let Some((i, d)) = self.待补数据.swap(None) {
401            self_item.items[i] = d;
402        }
403
404        if self_item.count == 0 {
405            // 此时 index = 0, 对index不操作
406        } else {
407            self_item.index += 1;
408            if self_item.index == LEN {
409                self_item.index = 0;
410            }
411        }
412        self_item.items[self.index] = item_new;
413        self_item.count += 1;
414    }
415
416    /// 当前项
417    pub fn current(&self) -> &T {
418        if self.count == 0 {
419            return &self.item.as_ref().defalut_val;
420        }
421        &self.items[self.index]
422    }
423
424    /// 请控制此方法不可并发访问
425    pub fn clear(&self) {
426        let self_item = self.item_mut();
427        self_item.index = 0;
428        self_item.count = 0;
429        // 第1条数据要清空,并无实质数据。
430        self_item.items[0] = T::default();
431    }
432
433    /// 传参:毫秒
434    /// 如果找不到精确定位的数据, 则返回最新的那条数据
435    pub fn find_找之前的项(&self, 毫秒数: i64, is_找不到即取最新数据: bool) -> Option<&T> {
436        if self.count == 0 {
437            return None;
438        }
439        let capacity = self.items.len();
440        // 将微秒数转为 u64,但只在非负当前情况才如此
441        let 微秒数 = if 毫秒数 >= 0 {
442            毫秒数 as u64 * a8_micros::MICROS_PER_MILLIS
443        } else {
444            0
445        };
446
447        let ticks_当前项 = self.items[self.index].time().micros_of_day();
448        let index_当前索引 = self.index;
449
450        let mut find_最新 = Option::<&T>::None;
451        for idx in (0..index_当前索引).rev() {
452            let ticks_往前项 = self.items[idx].time().micros_of_day();
453            if ticks_往前项 == 0 {
454                continue;
455            }
456            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
457            if delta_往前微秒数 > 微秒数 {
458                return Some(&self.items[idx]);
459            }
460
461            // 修复: 如果找不到精确定位的数据, 则返回最新的那条数据; 从vec后面开始循环, 第一条数据就是最新的
462            if is_找不到即取最新数据 {
463                match &find_最新 {
464                    None => {
465                        find_最新 = Some(&self.items[idx]);
466                    }
467                    _ => (),
468                }
469            }
470        }
471
472        if self.count <= LEN {
473            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
474            return Some(find_最新.unwrap_or_else(|| &self.item.as_ref().defalut_val));
475        }
476
477        // 从数组后面开始找
478        for idx in ((index_当前索引 + 1)..capacity).rev() {
479            let item = &self.items[idx];
480            let ticks_往前项 = item.time().micros_of_day();
481            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
482            if ticks_往前项 > 0 && delta_往前微秒数 > 微秒数 {
483                return Some(item);
484
485                // 修复: 找前封单时刚好在前一段找不到数据, 再从后面开始找, 匹配到最后一个数据, 但却拿到第一个下标的初始值
486                // if idx + 1 == capacity {
487                //     return &self.items[0];
488                // } else {
489                //     return item;
490                // }
491            }
492        }
493
494        return find_最新;
495    }
496
497    /// 如果十档或者前封单数据如果出现断档的情况,那么把前一个数据的时间戳改成现在数据并且减10毫秒
498    /// 下次找数据时可以直接找到这一条
499    // fn 向前补一个数据(&self) -> Option<T> {
500    //     let idx = if self.index == 0 && self.count >= LEN {
501    //         LEN - 1
502    //     } else if self.index > 0 {
503    //         self.index - 1
504    //     } else {
505    //         // index 等于零, 没有数据的情况
506    //         return None;
507    //     };
508
509    //     let mut item = self.items[idx].clone();
510    //     let millis = self.current().time().micros_of_day() - 10 * 1000;
511    //     let time = NaiveTime::from_micros_day_unsafe(millis);
512    //     item.set_time_发生时间(time);
513    //     self.待补数据.store(Some((idx, item.clone())));
514    //     return Some(item);
515    // }
516
517    // pub fn find<F: Fn(&T) -> bool>(&self, f: F) -> Option<&T> {
518    //     if self.count == 0 {
519    //         return None;
520    //     }
521
522    //     let 当前项 = &self.items[self.index];
523    //     if f(当前项) {
524    //         return Some(当前项);
525    //     }
526
527    //     let index_当前索引 = self.index;
528    //     for idx in (0..index_当前索引).rev() {
529    //         if f(&self.items[idx]) {
530    //             return Some(&self.items[idx]);
531    //         }
532    //     }
533    //     if self.count <= LEN {
534    //         // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
535    //         return None;
536    //     }
537
538    //     for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
539    //         if f(&self.items[idx]) {
540    //             return Some(&self.items[idx]);
541    //         }
542    //     }
543    //     None
544    // }
545
546    /// 找到范围内最大的值
547    /// n: 毫秒数
548    /// is_return_last: true; 两秒内最大值找不到, 即找一个最新的数据
549    /// compare: 比较两个值, 返回true则使用新的值
550    /// 
551    /// TODO: 不要使用补数据的逻辑, 找不到数据即取一个最新的数据
552    pub fn find_limit<F: Fn(&T, &T) -> bool>(
553        &self,
554        n: i64,
555        is_return_last: bool,
556        compare: F,
557    ) -> T {
558        let items = self.list_items(n);
559        let 补一个数据 = None;
560
561        if (items.is_empty() || items.len() == 1) && is_return_last {
562            // TODO: 注释掉不存在的方法调用
563            // 补一个数据 = self.向前补一个数据();
564        }
565
566        if items.is_empty() {
567            return 补一个数据.unwrap_or_else(|| self.defalut_val.clone());
568        }
569
570        let mut find_v = items[0];
571        for item in items.iter().skip(1) {
572            if compare(&find_v, item) {
573                find_v = item;
574            }
575        }
576
577        if let Some(v) = &补一个数据 {
578            if compare(&find_v, v) {
579                find_v = v;
580            }
581        }
582
583        return find_v.clone();
584    }
585
586    /// 传参:找多少个
587    pub fn list_items_len(&self, mut count: usize) -> Vec<&T> {
588        if self.count == 0 {
589            return vec![];
590        }
591        let mut items = vec![];
592
593        let 当前项 = &self.items[self.index];
594        items.push(当前项);
595
596        let index_当前索引 = self.index;
597        for idx in (0..index_当前索引).rev() {
598            if count == 0 {
599                return items;
600            }
601            items.push(&self.items[idx]);
602            count -= 1;
603        }
604
605        if self.count <= LEN {
606            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
607            return items;
608        }
609
610        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
611            if count == 0 {
612                return items;
613            }
614            items.push(&self.items[idx]);
615            count -= 1;
616        }
617        items
618    }
619
620    /// 传参:毫秒
621    pub fn list_items(&self, 毫秒数: i64) -> Vec<&T> {
622        if self.count == 0 {
623            return vec![];
624        }
625        let mut items = vec![];
626
627        // 将微秒数转为 u64,但只在非负当前情况才如此
628        let 微秒数 = if 毫秒数 as i64 >= 0 {
629            毫秒数 as u64 * a8_micros::MICROS_PER_MILLIS
630        } else {
631            0
632        };
633
634        let 当前项 = &self.items[self.index];
635        items.push(当前项);
636
637        let ticks_当前项 = 当前项.time().micros_of_day();
638        let index_当前索引 = self.index;
639        for idx in (0..index_当前索引).rev() {
640            let ticks_往前项 = self.items[idx].time().micros_of_day();
641            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
642            if delta_往前微秒数 > 微秒数 {
643                // return items;
644                break;
645            }
646            items.push(&self.items[idx]);
647        }
648        if self.count <= LEN {
649            // 尚未走出一轮(填满 CAPACTIY 个项),后面没有值
650            return items;
651        }
652
653        for idx in ((index_当前索引 + 1)..self.items.len()).rev() {
654            let ticks_往前项 = self.items[idx].time().micros_of_day();
655            let delta_往前微秒数 = ticks_当前项 - ticks_往前项;
656            if delta_往前微秒数 > 微秒数 {
657                return items;
658            }
659            // 是不是少了这句代码? todo 志松
660            items.push(&self.items[idx]);
661        }
662        items
663    }
664
665    // 补数据, 十档数据有可能在N秒后才有新数据, 逐笔同理, 把之前缺失的数据补上(10毫秒一个)
666    /* pub fn update_补数据(&mut self, last: TimeFT) {
667        let last_ticks = last.micros_of_day();
668
669        if self.current().time().micros_of_day() + 10 >= last_ticks {
670            return;
671        }
672
673        let mut 最新时间的数据 = Option::<T>::None;
674        for ele in &self.items {
675            match 最新时间的数据{
676                Some(v) => {
677                    if v.time().micros_of_day() <= ele.time().micros_of_day() {
678                        最新时间的数据 = Some(ele.clone());
679                    }
680                },
681                None => {
682                    最新时间的数据 = Some(ele.clone());
683                }
684            }
685        }
686
687        let mut 内存_最新数据 = match 最新时间的数据 {
688            Some(v) => v,
689            None => return,
690        };
691
692        let mut 内存_最新数据时间 = 内存_最新数据.time().micros_of_day();
693
694        while last_ticks > 内存_最新数据时间 + 10{
695            内存_最新数据时间 += 10;
696            内存_最新数据.set_接收时间(TimeFT::from_micros_day_unsafe(内存_最新数据时间));
697            self.push(&内存_最新数据);
698        }
699
700    } */
701}
702
703impl<T: CacheData, const LEN: usize> Default for HighSpeedCache<T, LEN> {
704    fn default() -> Self {
705        Self::new()
706    }
707}
708
709impl<T, const LEN: usize> HighSpeedCache<T, LEN>
710where
711    T: CacheData,
712{
713    /// 返回缓存中的元素数量
714    pub fn len(&self) -> usize {
715        // 返回实际可迭代的元素数量,不能超过缓存容量
716        self.count.min(LEN)
717    }
718    
719    /// 检查缓存是否为空
720    pub fn is_empty(&self) -> bool {
721        self.count == 0
722    }
723    
724    /// 返回缓存的容量(最大可存储元素数)
725    pub fn capacity(&self) -> usize {
726        LEN
727    }
728    
729    /// 根据索引获取元素的引用
730    pub fn get(&self, index: usize) -> Option<&T> {
731        if index >= self.count {
732            return None;
733        }
734        
735        // 计算实际索引,考虑环形缓冲区
736        let actual_index = if self.count <= LEN {
737            // 未满或刚好满,从最新的元素开始
738            // 最新的元素索引是 index,然后依次往前
739            if index <= self.index {
740                self.index - index
741            } else {
742                // 环绕到数组的尾部
743                LEN - (index - self.index)
744            }
745        } else {
746            // 已满且溢出,从最新的元素开始
747            (self.index + LEN - index) % LEN
748        };
749        
750        Some(&self.item.as_ref().items[actual_index])
751    }
752    
753    /// 获取元素的可变引用
754    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
755        if index >= self.count {
756            return None;
757        }
758        
759        // 计算实际索引,考虑环形缓冲区
760        let actual_index = if self.count <= LEN {
761            // 未满或刚好满,从最新的元素开始
762            if index >= self.count {
763                return None; // 超过范围
764            }
765            // 最新的元素索引是 index,然后依次往前
766            if index <= self.index {
767                self.index - index
768            } else {
769                // 环绕到数组的尾部
770                LEN - (index - self.index)
771            }
772        } else {
773            // 已满且溢出,从最新的元素开始
774            (self.index + LEN - index) % LEN
775        };
776        
777        Some(&mut self.item_mut().items[actual_index])
778    }
779    
780    /// 返回一个引用迭代器,按从最新到最旧的顺序
781    pub fn iter(&self) -> HighSpeedCacheIter<T, LEN> {
782        HighSpeedCacheIter {
783            cache: self,
784            current_index: 0,
785            items_seen: 0,
786            total_items: self.len(),
787        }
788    }
789    
790    /// 返回一个可变引用迭代器,按从最新到最旧的顺序
791    pub fn iter_mut(&mut self) -> HighSpeedCacheIterMut<T, LEN> {
792        // 先获取长度,避免后续的借用冲突
793        let total = self.len();
794        HighSpeedCacheIterMut {
795            cache: self,
796            current_index: 0,
797            items_seen: 0,
798            total_items: total,
799        }
800    }
801    
802    /// 转换为 Vec
803    pub fn to_vec(&self) -> Vec<T> 
804    where
805        T: Clone,
806    {
807        self.iter().cloned().collect()
808    }
809}
810
811// 实现 IntoIterator trait,允许在 for 循环中使用(引用)
812impl<'a, T, const LEN: usize> IntoIterator for &'a HighSpeedCache<T, LEN>
813where
814    T: CacheData,
815{
816    type Item = &'a T;
817    type IntoIter = HighSpeedCacheIter<'a, T, LEN>;
818    
819    fn into_iter(self) -> Self::IntoIter {
820        self.iter()
821    }
822}
823
824// 实现 IntoIterator trait,允许在 for 循环中使用(可变引用)
825impl<'a, T, const LEN: usize> IntoIterator for &'a mut HighSpeedCache<T, LEN>
826where
827    T: CacheData,
828{
829    type Item = &'a mut T;
830    type IntoIter = HighSpeedCacheIterMut<'a, T, LEN>;
831    
832    fn into_iter(self) -> Self::IntoIter {
833        self.iter_mut()
834    }
835}
836
837// 注意:我们不需要为 HighSpeedCacheIter 和 HighSpeedCacheIterMut 实现 IntoIterator
838// 因为标准库已经为所有实现了 Iterator trait 的类型自动实现了 IntoIterator
839
840// 实现 IntoIterator trait,允许消费型迭代
841// 实现 Index trait
842impl<T, const LEN: usize> Index<usize> for HighSpeedCache<T, LEN>
843where
844    T: CacheData,
845{
846    type Output = T;
847    
848    fn index(&self, index: usize) -> &Self::Output {
849        self.get(index).expect("索引超出范围")
850    }
851}
852
853// 实现 IndexMut trait
854impl<T, const LEN: usize> IndexMut<usize> for HighSpeedCache<T, LEN>
855where
856    T: CacheData,
857{
858    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
859        self.get_mut(index).expect("索引超出范围")
860    }
861}
862
863impl<T, const LEN: usize> IntoIterator for HighSpeedCache<T, LEN>
864where
865    T: CacheData + Clone,
866{
867    type Item = T;
868    type IntoIter = HighSpeedCacheIntoIter<T, LEN>;
869    
870    fn into_iter(self) -> Self::IntoIter {
871        let total = self.len();
872        HighSpeedCacheIntoIter {
873            cache: self,
874            current_index: 0,
875            items_seen: 0,
876            total_items: total,
877        }
878    }
879}
880
881#[cfg(test)]
882mod test_高频数据 {
883    use chrono::NaiveTime;
884    use crate::fasttime::b2_time::TimeExt;
885
886    use super::{CacheData, HighSpeedCache};
887
888    #[derive(Debug, Default, Clone, PartialEq, Eq)]
889    struct Demo_高频数据 {
890        pub time_发生时间: NaiveTime,
891        pub time_接收时间: NaiveTime,
892        pub val: i32,
893    }
894
895    impl CacheData for Demo_高频数据 {
896        fn time(&self) -> NaiveTime {
897            self.time_发生时间
898        }
899    }
900
901    #[test]
902    fn test_demo_高频数据() {
903        let HighSpeedCache = HighSpeedCache::<Demo_高频数据, 1000>::new();
904
905        // 使用固定增量代替随机数,避免依赖 rand
906        let mut micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
907        for val in 1..1000 {
908            let time_发生时间 = NaiveTime::from_micros_day_unsafe(micros);
909            micros += 100; // 固定增加100微秒
910
911            HighSpeedCache.push(Demo_高频数据 {
912                time_发生时间,
913                time_接收时间: time_发生时间,
914                val,
915            });
916            _ = HighSpeedCache.find_找之前的项(30_000, false);
917        }
918    }
919    
920    #[test]
921    fn test_高频数据_迭代器() {
922        // 1. 测试空缓存
923        let cache_empty = HighSpeedCache::<Demo_高频数据, 10>::new();
924        assert_eq!(cache_empty.len(), 0);
925        assert!(cache_empty.is_empty());
926        assert_eq!(cache_empty.capacity(), 10);
927        
928        // 检查空缓存的迭代是否正确
929        let mut iter_count = 0;
930        for _ in &cache_empty {
931            iter_count += 1;
932        }
933        assert_eq!(iter_count, 0, "空缓存不应该有任何元素可迭代");
934        assert_eq!(cache_empty.get(0), None, "空缓存的get应返回None");
935        
936        // 2. 测试未满缓存
937        let cache_partial = HighSpeedCache::<Demo_高频数据, 10>::new();
938        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
939        
940        // 添加5个元素
941        for val in 1..6 {
942            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
943            cache_partial.push(Demo_高频数据 {
944                time_发生时间: time,
945                time_接收时间: time,
946                val,
947            });
948        }
949        
950        assert_eq!(cache_partial.len(), 5);
951        assert!(!cache_partial.is_empty());
952        
953        // 测试迭代器顺序 (从最新到最旧)
954        let items: Vec<i32> = cache_partial.iter().map(|item| item.val).collect();
955        assert_eq!(items, vec![5, 4, 3, 2, 1]);
956        
957        // 使用 rev() 返回旧元素到新的顺序
958        let items_rev: Vec<i32> = cache_partial.iter().rev().map(|item| item.val).collect();
959        assert_eq!(items_rev, vec![1, 2, 3, 4, 5]);
960        
961        // 测试get方法 - 现在是从最新到最旧
962        assert_eq!(cache_partial.get(0).map(|item| item.val), Some(5)); // 索引0是最新的元素
963        assert_eq!(cache_partial.get(4).map(|item| item.val), Some(1)); // 索引4是最旧的元素
964        assert_eq!(cache_partial.get(5), None); // 超出范围
965        
966        // 测试索引器访问
967        assert_eq!(cache_partial[0].val, 5);
968        assert_eq!(cache_partial[4].val, 1);
969        
970        // 3. 测试已满并且环绕的缓存 (用一个更小的缓存容量便于测试)
971        let cache_full = HighSpeedCache::<Demo_高频数据, 3>::new();
972        
973        // 添加5个元素到容量为3的缓存,导致环绕
974        for val in 1..6 {
975            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
976            cache_full.push(Demo_高频数据 {
977                time_发生时间: time,
978                time_接收时间: time,
979                val,
980            });
981        }
982        
983        assert_eq!(cache_full.len(), 3);
984        assert_eq!(cache_full.count, 5); // 内部计数应该是5,但实际长度限制为3
985        
986        // 检验迭代结果 - 应该只有最新的3个元素,现在是从最新到最旧
987        let items_full: Vec<i32> = cache_full.iter().map(|item| item.val).collect();
988        assert_eq!(items_full, vec![5, 4, 3]);
989        
990        // 测试 with_capacity 方法
991        let cache_with_cap = HighSpeedCache::<Demo_高频数据, 5>::with_capacity(100);
992        assert_eq!(cache_with_cap.capacity(), 5); // 容量仍然由模板参数决定
993        
994        // 测试to_vec方法
995        let vec_items = cache_full.to_vec();
996        assert_eq!(vec_items.len(), 3);
997        assert_eq!(vec_items[0].val, 5);
998        assert_eq!(vec_items[2].val, 3);
999        
1000        // 4. 测试into_iter消费迭代器
1001        let cache_consume = HighSpeedCache::<Demo_高频数据, 3>::new();
1002        
1003        // 添加3个元素
1004        for val in 1..4 {
1005            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1006            cache_consume.push(Demo_高频数据 {
1007                time_发生时间: time,
1008                time_接收时间: time,
1009                val,
1010            });
1011        }
1012        
1013        // 使用into_iter消费缓存
1014        let consumed: Vec<Demo_高频数据> = cache_consume.into_iter().collect();
1015        assert_eq!(consumed.len(), 3);
1016        assert_eq!(consumed[0].val, 3); // 现在是从最新到最旧
1017        assert_eq!(consumed[2].val, 1);
1018        
1019        // 测试IndexMut,修改元素
1020        let mut cache_mut = HighSpeedCache::<Demo_高频数据, 3>::new();
1021        
1022        // 添加3个元素
1023        for val in 1..4 {
1024            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1025            cache_mut.push(Demo_高频数据 {
1026                time_发生时间: time,
1027                time_接收时间: time,
1028                val,
1029            });
1030        }
1031        
1032        // 使用索引器修改第一个元素(最新的)
1033        cache_mut[0].val = 100;
1034        assert_eq!(cache_mut[0].val, 100);
1035        
1036        // 验证ExactSizeIterator
1037        let cache_exact = HighSpeedCache::<Demo_高频数据, 5>::new();
1038        for val in 1..4 {
1039            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1040            cache_exact.push(Demo_高频数据 {
1041                time_发生时间: time,
1042                time_接收时间: time,
1043                val,
1044            });
1045        }
1046        
1047        let iter = cache_exact.iter();
1048        assert_eq!(iter.len(), 3);
1049        
1050        let mut iter2 = cache_exact.iter();
1051        iter2.next(); // 消费一个元素
1052        assert_eq!(iter2.len(), 2); // 长度应该减少
1053    }
1054    
1055    #[test]
1056    fn test_索引器_异常处理() {
1057        // 测试空缓存索引访问
1058        {
1059            let cache = HighSpeedCache::<Demo_高频数据, 5>::new();
1060            // 不使用 catch_unwind 来避免 UnwindSafe 问题
1061            // 而是直接检查是否为空
1062            assert_eq!(cache.len(), 0);
1063            assert!(cache.is_empty());
1064            // 手动验证 get 返回 None
1065            assert_eq!(cache.get(0), None);
1066        }
1067        
1068        // 填充一些数据
1069        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
1070        // 注意:这里不需要 mut,因为 push 方法接受 &self
1071        let cache_with_data = HighSpeedCache::<Demo_高频数据, 5>::new();
1072        for val in 1..4 {
1073            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1074            cache_with_data.push(Demo_高频数据 {
1075                time_发生时间: time,
1076                time_接收时间: time,
1077                val,
1078            });
1079        }
1080        
1081        // 访问有效索引
1082        assert_eq!(cache_with_data.get(0).map(|item| item.val), Some(3));
1083        assert_eq!(cache_with_data.get(1).map(|item| item.val), Some(2));
1084        assert_eq!(cache_with_data.get(2).map(|item| item.val), Some(1));
1085        
1086        // 访问超出范围的索引
1087        assert_eq!(cache_with_data.get(3), None, "超范围索引应该返回 None");
1088        assert_eq!(cache_with_data.get(100), None, "远超范围索引应该返回 None");
1089    }
1090    
1091    #[test]
1092    fn test_iter_mut() {
1093        // 创建缓存并填充数据
1094        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
1095        let mut cache = HighSpeedCache::<Demo_高频数据, 5>::new();
1096        
1097        // 添加5个元素
1098        for val in 1..6 {
1099            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1100            cache.push(Demo_高频数据 {
1101                time_发生时间: time,
1102                time_接收时间: time,
1103                val,
1104            });
1105        }
1106        
1107        // 使用 iter_mut 修改所有元素
1108        for item in cache.iter_mut() {
1109            let val = &mut item.val;
1110            *val *= 10; // 将每个元素的 val 乘以 10
1111        }
1112        
1113        // 验证修改是否生效
1114        let values: Vec<i32> = cache.iter().map(|item| item.val).collect();
1115        assert_eq!(values, vec![50, 40, 30, 20, 10]); // 从最新到最旧
1116        
1117        // 测试部分修改
1118        let mut iter = cache.iter_mut();
1119        if let Some(item) = iter.next() {
1120            item.val = 100; // 修改最新的元素
1121        }
1122        if let Some(item) = iter.next() {
1123            item.val = 200; // 修改第二新的元素
1124        }
1125        
1126        // 验证部分修改是否生效
1127        assert_eq!(cache[0].val, 100); // 最新的元素
1128        assert_eq!(cache[1].val, 200); // 第二新的元素
1129        assert_eq!(cache[2].val, 30);  // 其他元素保持不变
1130        
1131        // 测试 ExactSizeIterator 实现
1132        let mut iter_mut = cache.iter_mut();
1133        assert_eq!(iter_mut.len(), 5);
1134        iter_mut.next();
1135        assert_eq!(iter_mut.len(), 4);
1136        iter_mut.next();
1137        assert_eq!(iter_mut.len(), 3);
1138    }
1139    
1140    #[test]
1141    fn test_iter_rev() {
1142        // 创建缓存并填充数据
1143        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
1144        let cache = HighSpeedCache::<Demo_高频数据, 5>::new();
1145        
1146        // 添加5个元素
1147        for val in 1..6 {
1148            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1149            cache.push(Demo_高频数据 {
1150                time_发生时间: time,
1151                time_接收时间: time,
1152                val,
1153            });
1154        }
1155        
1156        // 测试 iter().rev() - 从最旧到最新
1157        let values: Vec<i32> = cache.iter().rev().map(|item| item.val).collect();
1158        assert_eq!(values, vec![1, 2, 3, 4, 5]); // 从最旧到最新
1159        
1160        // 测试 iter_mut().rev() - 从最旧到最新
1161        let mut cache_mut = HighSpeedCache::<Demo_高频数据, 5>::new();
1162        
1163        // 添加5个元素
1164        for val in 1..6 {
1165            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1166            cache_mut.push(Demo_高频数据 {
1167                time_发生时间: time,
1168                time_接收时间: time,
1169                val,
1170            });
1171        }
1172        
1173        // 使用 iter_mut().rev() 修改所有元素
1174        for item in cache_mut.iter_mut().rev() {
1175            let val = &mut item.val;
1176            *val *= 10; // 将每个元素的 val 乘以 10
1177        }
1178        
1179        // 验证修改是否生效 - 应该是从最旧到最新的顺序修改的
1180        let values: Vec<i32> = cache_mut.iter().map(|item| item.val).collect();
1181        assert_eq!(values, vec![50, 40, 30, 20, 10]); // 从最新到最旧
1182        
1183        // 测试 for 循环中使用 &mut cache 进行可变迭代
1184        let mut cache2 = HighSpeedCache::<Demo_高频数据, 3>::new();
1185        for val in 1..4 {
1186            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1187            cache2.push(Demo_高频数据 {
1188                time_发生时间: time,
1189                time_接收时间: time,
1190                val,
1191            });
1192        }
1193        
1194        // 使用 &mut 语法直接迭代并修改
1195        for item in &mut cache2 {
1196            item.val += 100;
1197        }
1198        
1199        // 验证修改是否生效
1200        assert_eq!(cache2[0].val, 103); // 最新的元素
1201        assert_eq!(cache2[1].val, 102); // 第二新的元素
1202        assert_eq!(cache2[2].val, 101); // 最旧的元素
1203    }
1204    
1205    #[test]
1206    fn test_完整迭代器行为() {
1207        // 创建缓存并填充数据
1208        let base_micros = NaiveTime::from_hmsi_friendly_unsafe(93000_000).micros_of_day();
1209        let mut cache = HighSpeedCache::<Demo_高频数据, 10>::new();
1210        
1211        // 添加元素并记录原始值
1212        let mut original_values = Vec::new();
1213        for val in 1..11 {
1214            let time = NaiveTime::from_micros_day_unsafe(base_micros + (val as u64 * 100));
1215            let item = Demo_高频数据 {
1216                time_发生时间: time,
1217                time_接收时间: time,
1218                val,
1219            };
1220            original_values.push(item.clone());
1221            cache.push(item);
1222        }
1223        
1224        // 测试容量和长度
1225        assert_eq!(cache.capacity(), 10);
1226        assert_eq!(cache.len(), 10);
1227        assert!(!cache.is_empty());
1228        
1229        // 1. 测试正向迭代器完整性 - 从最新到最旧
1230        let mut iter_values = Vec::new();
1231        for item in &cache {
1232            iter_values.push(item.val);
1233        }
1234        // 验证顺序是否正确(从最新到最旧)
1235        assert_eq!(iter_values, vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
1236        
1237        // 2. 测试反向迭代器完整性 - 从最旧到最新
1238        let mut rev_iter_values = Vec::new();
1239        for item in cache.iter().rev() {
1240            rev_iter_values.push(item.val);
1241        }
1242        // 验证顺序是否正确(从最旧到最新)
1243        assert_eq!(rev_iter_values, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1244        
1245        // 3. 测试可变迭代器完整性 - 从最新到最旧
1246        let mut modified_values = Vec::new();
1247        for item in cache.iter_mut() {
1248            item.val *= 2; // 将每个值翻倍
1249            modified_values.push(item.val);
1250        }
1251        // 验证顺序和修改是否正确
1252        assert_eq!(modified_values, vec![20, 18, 16, 14, 12, 10, 8, 6, 4, 2]);
1253        
1254        // 4. 测试可变反向迭代器完整性 - 从最旧到最新
1255        let mut rev_modified_values = Vec::new();
1256        for item in cache.iter_mut().rev() {
1257            item.val += 5; // 每个值加 5
1258            rev_modified_values.push(item.val);
1259        }
1260        // 验证顺序和修改是否正确
1261        assert_eq!(rev_modified_values, vec![25, 23, 21, 19, 17, 15, 13, 11, 9, 7]);
1262        
1263        // 5. 测试索引器访问
1264        for i in 0..cache.len() {
1265            // 验证索引器访问的值与迭代器一致
1266            assert_eq!(cache[i].val, 25 - i as i32 * 2);
1267        }
1268        
1269        // 6. 测试越界处理
1270        assert!(cache.get(cache.len()).is_none());
1271        assert!(cache.get(100).is_none());
1272        
1273        // 7. 测试环形缓冲区的覆盖行为
1274        // 添加新元素覆盖最旧的元素
1275        let new_val = 100;
1276        let time = NaiveTime::from_micros_day_unsafe(base_micros + (new_val as u64 * 100));
1277        cache.push(Demo_高频数据 {
1278            time_发生时间: time,
1279            time_接收时间: time,
1280            val: new_val,
1281        });
1282        
1283        // 验证最新元素是否正确
1284        assert_eq!(cache[0].val, new_val);
1285        
1286        // 验证最旧的元素已被覆盖
1287        let values: Vec<i32> = cache.iter().map(|item| item.val).collect();
1288        assert_eq!(values.len(), 10); // 长度不变
1289        assert_eq!(values[0], new_val); // 最新的是新添加的
1290        assert_eq!(values[9], 9); // 最旧的元素已经不是 1 了
1291        
1292        // 8. 测试 ExactSizeIterator 实现
1293        let mut iter = cache.iter();
1294        assert_eq!(iter.len(), 10);
1295        iter.next();
1296        assert_eq!(iter.len(), 9);
1297        
1298        // 9. 测试空缓存的迭代器行为
1299        let empty_cache = HighSpeedCache::<Demo_高频数据, 5>::new();
1300        assert_eq!(empty_cache.len(), 0);
1301        assert!(empty_cache.is_empty());
1302        assert_eq!(empty_cache.iter().count(), 0);
1303        assert_eq!(empty_cache.iter().rev().count(), 0);
1304    }
1305}