Line data Source code
1 : use std::collections::HashMap;
2 :
3 : const BLOCK_SIZE: usize = 8192;
4 :
5 : /// A simple in-memory implementation of a block storage. Can be used to implement external
6 : /// storage in tests.
7 : pub struct BlockStorage {
8 : blocks: HashMap<u64, [u8; BLOCK_SIZE]>,
9 : }
10 :
11 : impl Default for BlockStorage {
12 0 : fn default() -> Self {
13 0 : Self::new()
14 0 : }
15 : }
16 :
17 : impl BlockStorage {
18 10862 : pub fn new() -> Self {
19 10862 : BlockStorage {
20 10862 : blocks: HashMap::new(),
21 10862 : }
22 10862 : }
23 :
24 2207 : pub fn read(&self, pos: u64, buf: &mut [u8]) {
25 2207 : let mut buf_offset = 0;
26 2207 : let mut storage_pos = pos;
27 5321 : while buf_offset < buf.len() {
28 3114 : let block_id = storage_pos / BLOCK_SIZE as u64;
29 3114 : let block = self.blocks.get(&block_id).unwrap_or(&[0; BLOCK_SIZE]);
30 3114 : let block_offset = storage_pos % BLOCK_SIZE as u64;
31 3114 : let block_len = BLOCK_SIZE as u64 - block_offset;
32 3114 : let buf_len = buf.len() - buf_offset;
33 3114 : let copy_len = std::cmp::min(block_len as usize, buf_len);
34 3114 : buf[buf_offset..buf_offset + copy_len]
35 3114 : .copy_from_slice(&block[block_offset as usize..block_offset as usize + copy_len]);
36 3114 : buf_offset += copy_len;
37 3114 : storage_pos += copy_len as u64;
38 3114 : }
39 2207 : }
40 :
41 13269 : pub fn write(&mut self, pos: u64, buf: &[u8]) {
42 13269 : let mut buf_offset = 0;
43 13269 : let mut storage_pos = pos;
44 26881 : while buf_offset < buf.len() {
45 13612 : let block_id = storage_pos / BLOCK_SIZE as u64;
46 13612 : let block = self.blocks.entry(block_id).or_insert([0; BLOCK_SIZE]);
47 13612 : let block_offset = storage_pos % BLOCK_SIZE as u64;
48 13612 : let block_len = BLOCK_SIZE as u64 - block_offset;
49 13612 : let buf_len = buf.len() - buf_offset;
50 13612 : let copy_len = std::cmp::min(block_len as usize, buf_len);
51 13612 : block[block_offset as usize..block_offset as usize + copy_len]
52 13612 : .copy_from_slice(&buf[buf_offset..buf_offset + copy_len]);
53 13612 : buf_offset += copy_len;
54 13612 : storage_pos += copy_len as u64
55 : }
56 13269 : }
57 : }
|