Skip to main content

feldera_storage/
block.rs

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