xref: /DragonOS/kernel/src/driver/block/cache/cache_iter.rs (revision 471d65cf158c9bf741c21f5d0ab92efe7bf1c3d4)
1 use crate::driver::base::block::block_device::BlockId;
2 
3 /// # 结构功能
4 /// 一个简单的结构体,是BlockIter的输出
5 #[derive(Debug)]
6 pub struct BlockData {
7     /// 表示单个块对应的lba_id
8     lba_id: BlockId,
9     /// 表示该块在buf中的起始地址,目前并没有作用(例如:若该块是第2个块,那么该数据成员值为2*BLOCK_SIZE)
10     _data_start_addr: BlockId,
11     /// 表示该块的大小
12     _block_size: usize,
13 }
14 
15 impl BlockData {
16     pub fn new(lba_id: BlockId, data_start_addr: BlockId, block_size: usize) -> Self {
17         Self {
18             lba_id,
19             _data_start_addr: data_start_addr,
20             _block_size: block_size,
21         }
22     }
23     #[inline]
24     pub fn lba_id(&self) -> BlockId {
25         self.lba_id
26     }
27     #[inline]
28     pub fn _data_start_addr(&self) -> BlockId {
29         self._data_start_addr
30     }
31     #[inline]
32     pub fn _block_size(&self) -> usize {
33         self._block_size
34     }
35 }
36 
37 /// # 结构功能
38 /// 块迭代器,它获取需求(起始块,连续块的个数),并将连续的块输出为单一的块(如你需要读取lba_id为10~20的连续块,它就可以输出10,11...,20的BlockData)
39 #[derive(Copy, Clone)]
40 pub struct BlockIter {
41     /// 表示起始块的lba_id
42     lba_id_start: BlockId,
43     /// 表示从起始块开始你需要读多少个块
44     count: usize,
45     /// 表示当前遍历到第几个块了
46     current: usize,
47     /// 规定块的大小
48     block_size: usize,
49 }
50 
51 impl BlockIter {
52     pub fn new(lba_id_start: BlockId, count: usize, block_size: usize) -> Self {
53         Self {
54             lba_id_start,
55             count,
56             block_size,
57             current: 0,
58         }
59     }
60 }
61 
62 impl Iterator for BlockIter {
63     type Item = BlockData;
64 
65     fn next(&mut self) -> Option<Self::Item> {
66         if self.current < self.count {
67             let ans = BlockData::new(
68                 self.lba_id_start + self.current,
69                 self.current * self.block_size,
70                 self.block_size,
71             );
72             self.current += 1;
73             Some(ans)
74         } else {
75             None
76         }
77     }
78 }
79 
80 /// # 结构功能
81 /// 表示缺块信息的数据结构,往往在读取的时候发现缺块并产生FailData,在插入的时候使用FailData
82 pub struct FailData {
83     /// 表示缺块的lba_id
84     lba_id: BlockId,
85     /// 表示缺块在buf中的位置,用于在insert的时候定位缺块数据的位置
86     index: usize,
87 }
88 
89 impl FailData {
90     pub fn new(lba_id: BlockId, index: usize) -> Self {
91         FailData { lba_id, index }
92     }
93     #[inline]
94     pub fn lba_id(&self) -> BlockId {
95         self.lba_id
96     }
97     /// # 函数的功能
98     /// 该函数返回的是缺块在buf中的位置,比如:index=1,那么我们就应该取buf\[512..1024\]
99     pub fn index(&self) -> usize {
100         self.index
101     }
102 }
103