libpart/
util.rs

1use std::ops::{Add, Sub};
2
3#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
4pub struct Block(pub u64);
5
6impl Block {
7    /// Gets the byte offset of a block
8    pub fn to_bytes(&self, sector_size: u16) -> u64 {
9        let sector_size = sector_size as u64;
10        self.0 * sector_size
11    }
12
13    /// Gets the Block from a byte offset
14    /// Returns none if not at valid byte offset
15    pub fn from_bytes(bytes: u64, sector_size: u16) -> Option<Block> {
16        let sector_size = sector_size as u64;
17        if bytes % sector_size == 0 {
18            Some(Block(bytes / 512))
19        } else {
20            None
21        }
22    }
23
24    /// Gets the Block as well as the offset within the block of a given offset
25    pub fn from_bytes_offset(bytes: u64, sector_size: u16) -> (Block, u16) {
26        let sector_size = sector_size as u64;
27        (Block(bytes / sector_size), (bytes % sector_size) as u16)
28    }
29}
30
31impl Add for Block {
32    type Output = Block;
33
34    fn add(self, other: Block) -> Block {
35        Block(self.0 + other.0)
36    }
37}
38
39impl Sub for Block {
40    type Output = Block;
41
42    fn sub(self, other: Block) -> Block {
43        Block(self.0 - other.0)
44    }
45}