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 85747 : pub fn new() -> Self {
19 85747 : BlockStorage {
20 85747 : blocks: HashMap::new(),
21 85747 : }
22 85747 : }
23 :
24 34188 : pub fn read(&self, pos: u64, buf: &mut [u8]) {
25 34188 : let mut buf_offset = 0;
26 34188 : let mut storage_pos = pos;
27 51913 : while buf_offset < buf.len() {
28 17725 : let block_id = storage_pos / BLOCK_SIZE as u64;
29 17725 : let block = self.blocks.get(&block_id).unwrap_or(&[0; BLOCK_SIZE]);
30 17725 : let block_offset = storage_pos % BLOCK_SIZE as u64;
31 17725 : let block_len = BLOCK_SIZE as u64 - block_offset;
32 17725 : let buf_len = buf.len() - buf_offset;
33 17725 : let copy_len = std::cmp::min(block_len as usize, buf_len);
34 17725 : buf[buf_offset..buf_offset + copy_len]
35 17725 : .copy_from_slice(&block[block_offset as usize..block_offset as usize + copy_len]);
36 17725 : buf_offset += copy_len;
37 17725 : storage_pos += copy_len as u64;
38 17725 : }
39 34188 : }
40 :
41 140837 : pub fn write(&mut self, pos: u64, buf: &[u8]) {
42 140837 : let mut buf_offset = 0;
43 140837 : let mut storage_pos = pos;
44 282086 : while buf_offset < buf.len() {
45 141249 : let block_id = storage_pos / BLOCK_SIZE as u64;
46 141249 : let block = self.blocks.entry(block_id).or_insert([0; BLOCK_SIZE]);
47 141249 : let block_offset = storage_pos % BLOCK_SIZE as u64;
48 141249 : let block_len = BLOCK_SIZE as u64 - block_offset;
49 141249 : let buf_len = buf.len() - buf_offset;
50 141249 : let copy_len = std::cmp::min(block_len as usize, buf_len);
51 141249 : block[block_offset as usize..block_offset as usize + copy_len]
52 141249 : .copy_from_slice(&buf[buf_offset..buf_offset + copy_len]);
53 141249 : buf_offset += copy_len;
54 141249 : storage_pos += copy_len as u64
55 : }
56 140837 : }
57 : }
|