feldera_storage/
block.rs

1use std::fmt::Display;
2
3/// A block that can be read or written in a [crate::FileReader] or [crate::FileWriter].
4#[derive(Copy, Clone, Debug)]
5pub struct BlockLocation {
6    /// Byte offset, a multiple of 512.
7    pub offset: u64,
8
9    /// Size in bytes, a multiple of 512, less than `2**31`.
10    ///
11    /// (The upper limit is because some kernel APIs return the number of bytes
12    /// read as an `i32`.)
13    pub size: usize,
14}
15
16impl BlockLocation {
17    /// Constructs a new [BlockLocation], validating `offset` and `size`.
18    pub fn new(offset: u64, size: usize) -> Result<Self, InvalidBlockLocation> {
19        if (offset % 512) != 0 || !(512..1 << 31).contains(&size) || (size % 512) != 0 {
20            Err(InvalidBlockLocation { offset, size })
21        } else {
22            Ok(Self { offset, size })
23        }
24    }
25
26    /// File offset just after this block.
27    pub fn after(&self) -> u64 {
28        self.offset + self.size as u64
29    }
30}
31
32impl Display for BlockLocation {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(f, "{} bytes at offset {}", self.size, self.offset)
35    }
36}
37
38/// A range of bytes in a file that doesn't satisfy the constraints for
39/// [BlockLocation].
40#[derive(Copy, Clone, Debug)]
41pub struct InvalidBlockLocation {
42    /// Byte offset.
43    pub offset: u64,
44
45    /// Number of bytes.
46    pub size: usize,
47}
48
49impl Display for InvalidBlockLocation {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "{} bytes at offset {}", self.size, self.offset)
52    }
53}