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