Skip to main content

file_system/mbr/partition/
entry.rs

1//! Partition entry structures for MBR partition tables.
2
3use crate::mbr::PartitionKind;
4
5/// MBR partition table entry structure.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct PartitionEntry {
8    /// Boot indicator.
9    pub bootable: bool,
10    /// Partition type.
11    pub kind: PartitionKind,
12    /// Starting LBA (Logical Block Address).
13    pub start_block: u32,
14    /// Size in sectors.
15    pub block_count: u32,
16    /// Legacy CHS address of the first sector.
17    pub first_chs: mbrman::CHS,
18    /// Legacy CHS address of the last sector.
19    pub last_chs: mbrman::CHS,
20}
21
22impl Default for PartitionEntry {
23    fn default() -> Self {
24        Self {
25            bootable: false,
26            kind: PartitionKind::Empty,
27            start_block: 0,
28            block_count: 0,
29            first_chs: mbrman::CHS::empty(),
30            last_chs: mbrman::CHS::empty(),
31        }
32    }
33}
34
35impl PartitionEntry {
36    /// Check if this partition entry is valid (non-empty and positive sector count).
37    pub fn is_valid(&self) -> bool {
38        self.kind != PartitionKind::Empty && self.block_count > 0
39    }
40
41    pub(crate) fn overlaps_with(&self, other: &Self) -> bool {
42        if !self.is_valid() || !other.is_valid() {
43            return false;
44        }
45
46        let (s1, e1) = (
47            self.start_block as u64,
48            self.start_block as u64 + self.block_count as u64 - 1,
49        );
50        let (s2, e2) = (
51            other.start_block as u64,
52            other.start_block as u64 + other.block_count as u64 - 1,
53        );
54
55        !(e1 < s2 || e2 < s1)
56    }
57
58    pub(crate) fn from_mbrman(entry: &mbrman::MBRPartitionEntry) -> Self {
59        Self {
60            bootable: entry.is_active(),
61            kind: PartitionKind::from(entry.sys),
62            start_block: entry.starting_lba,
63            block_count: entry.sectors,
64            first_chs: entry.first_chs,
65            last_chs: entry.last_chs,
66        }
67    }
68
69    pub(crate) fn to_mbrman(self) -> mbrman::MBRPartitionEntry {
70        mbrman::MBRPartitionEntry {
71            boot: if self.bootable {
72                mbrman::BOOT_ACTIVE
73            } else {
74                mbrman::BOOT_INACTIVE
75            },
76            first_chs: self.first_chs,
77            sys: self.kind.into(),
78            last_chs: self.last_chs,
79            starting_lba: self.start_block,
80            sectors: self.block_count,
81        }
82    }
83}