Skip to content

Commit c62fa20

Browse files
mmstickcecton
authored andcommitted
✨ Add GPT::find_at_sector() and GPT::remove_at_sector()
Adds two new methods to GPT: - find_at_sector(): Locates a partition by the sector which resides in it. - remove_at_sector(): Removes the partition found by the previous method.
1 parent 984091d commit c62fa20

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/lib.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,9 @@ pub enum Error {
145145
/// included.
146146
#[error(display = "invalid partition number: {}", _0)]
147147
InvalidPartitionNumber(u32),
148+
/// An operation that required to find a partition, was unable to find that partition.
149+
#[error(display = "partition not found")]
150+
PartitionNotFound,
148151
}
149152

150153
/// The result of reading, writing or managing a GPT.
@@ -786,6 +789,17 @@ impl GPT {
786789
Ok(())
787790
}
788791

792+
/// Finds the partition where the given sector resides.
793+
pub fn find_at_sector(&self, sector: u64) -> Option<u32> {
794+
fn between(partition: &GPTPartitionEntry, sector: u64) -> bool {
795+
sector >= partition.starting_lba && sector <= partition.ending_lba
796+
}
797+
798+
self.iter()
799+
.find(|(_, partition)| partition.is_used() && between(partition, sector))
800+
.map(|(id, _)| id)
801+
}
802+
789803
/// Find free spots in the partition table.
790804
/// This function will return a vector of tuple with on the left: the starting LBA of the free
791805
/// spot; and on the right: the size (in sectors) of the free spot.
@@ -1008,6 +1022,17 @@ impl GPT {
10081022
Ok(())
10091023
}
10101024

1025+
/// Remove a partiton entry in the array that resides at a given sector.
1026+
///
1027+
/// # Errors
1028+
/// It is an error to provide a sector which does not belong to a partition.
1029+
pub fn remove_at_sector(&mut self, sector: u64) -> Result<()> {
1030+
self.remove(
1031+
self.find_at_sector(sector)
1032+
.ok_or(Error::PartitionNotFound)?,
1033+
)
1034+
}
1035+
10111036
/// Get an iterator over the partition entries and their index. The index always starts at 1.
10121037
pub fn iter(&self) -> impl Iterator<Item = (u32, &GPTPartitionEntry)> {
10131038
self.partitions

0 commit comments

Comments
 (0)