fast_able/
high_speed_cache.rs

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