Struct Mbr

Source
pub struct Mbr {
    pub bootstrap_code: [u8; 440],
    pub disk_signature: [u8; 4],
    pub reserved: [u8; 2],
    pub partitions: [PartitionEntry; 4],
    pub boot_signature: [u8; 2],
}
Expand description

Master Boot Record structure (512 bytes)

Fields§

§bootstrap_code: [u8; 440]

Bootstrap code (440 bytes)

§disk_signature: [u8; 4]

Optional disk signature (4 bytes)

§reserved: [u8; 2]

Reserved (usually 0x0000)

§partitions: [PartitionEntry; 4]

Partition table (4 entries × 16 bytes = 64 bytes)

§boot_signature: [u8; 2]

Boot signature (0x55AA)

Implementations§

Source§

impl Mbr

Source

pub const SIGNATURE: [u8; 2]

MBR signature bytes

Source

pub const SIZE: usize = 512usize

Size of MBR in bytes

Source

pub const MAXIMUM_PARTITIONS_COUNT: usize = 4usize

Maximum number of primary partitions in MBR

Source

pub fn new() -> Self

Create a new empty MBR

Source

pub fn new_with_signature(disk_signature: u32) -> Self

Create a new MBR with a specific disk signature

Source

pub fn from_bytes(data: &[u8]) -> Result<Self>

Parse MBR from raw bytes

Source

pub fn read_from_device(device: &Device) -> Result<Self>

Read and parse MBR from a device

Source

pub fn write_to_device(&self, device: &Device) -> Result<()>

Write MBR to a device

Source

pub fn is_valid(&self) -> bool

Check if MBR has a valid signature

Source

pub fn get_valid_partitions(&self) -> Vec<&PartitionEntry>

Get all valid partitions

Source

pub fn get_valid_partitions_mut(&mut self) -> Vec<&mut PartitionEntry>

Get all valid partitions (mutable)

Source

pub fn get_bootable_partition(&self) -> Option<&PartitionEntry>

Get bootable partition (if any)

Source

pub fn get_bootable_partition_mut(&mut self) -> Option<&mut PartitionEntry>

Get bootable partition (mutable, if any)

Source

pub fn set_bootable_partition(&mut self, index: usize) -> Result<()>

Set a partition as bootable (clears bootable flag from other partitions)

Source

pub fn has_gpt_protective_partition(&self) -> bool

Check if this MBR contains a GPT protective partition

Source

pub fn get_disk_signature(&self) -> u32

Get disk signature as u32

Source

pub fn set_disk_signature(&mut self, signature: u32)

Set disk signature

Source

pub fn get_free_partition_slot(&self) -> Option<usize>

Get the first free partition slot

Source

pub fn add_partition( &mut self, partition_type: PartitionKind, start_lba: u32, size_sectors: u32, bootable: bool, ) -> Result<usize>

Add a new partition

Source

pub fn remove_partition(&mut self, index: usize) -> Result<()>

Remove a partition by index

Source

pub fn has_overlapping_partitions(&self) -> bool

Check for partition overlaps

Source

pub fn get_partition_count(&self) -> usize

Get partition count

Source

pub fn create_all_partition_devices( &self, base_device: Device, ) -> Result<Vec<PartitionDevice>>

Create partition devices for all valid partitions in this MBR.

This method iterates through all partition entries in this MBR and creates PartitionDevice instances for each valid partition. This is useful when you need to access all partitions on a disk programmatically.

§Arguments
  • base_device - The underlying storage device containing all partitions
§Returns
  • Ok(Vec<Partition_device_type>) - Vector of partition devices for all valid partitions
  • Err(Error) - Error if any partition device creation fails
§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));
// Create an MBR with multiple partitions
let mut mbr = MBR_type::New_with_signature(0x12345678);
mbr.Add_partition(Partition_type_type::Fat32_lba, 2048, 1024, true).unwrap();
mbr.Add_partition(Partition_type_type::Linux, 4096, 2048, false).unwrap();
mbr.Write_to_device(&device).unwrap();

// Read it back and create all partition devices
let mbr = MBR_type::Read_from_device(&device).unwrap();
let partition_devices = mbr.Create_all_partition_devices(device).unwrap();
println!("Created {} partition devices", partition_devices.len());

for (i, partition) in partition_devices.iter().enumerate() {
    println!("Partition {}: {} sectors", i, partition.get_sector_count());
}
Source

pub fn find_partitions_by_type( &self, partition_type: PartitionKind, ) -> Vec<(usize, &PartitionEntry)>

Find partitions of a specific type within this MBR.

This method searches through all partitions in this MBR and returns references to those that match the specified partition type. This is useful for locating specific types of partitions (e.g., FAT32, Linux, etc.) without creating partition devices.

§Arguments
  • partition_type - The specific partition type to find
§Returns

A vector of tuples containing the partition index and reference to the partition entry for each matching partition.

§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));
// Create an MBR with FAT32 partition
let mut mbr = MBR_type::New_with_signature(0x12345678);
mbr.Add_partition(Partition_type_type::Fat32_lba, 2048, 1024, true).unwrap();
mbr.Write_to_device(&device).unwrap();

// Read it back and find FAT32 partitions
let mbr = MBR_type::Read_from_device(&device).unwrap();
let fat32_partitions = mbr.Find_partitions_by_type(Partition_type_type::Fat32_lba);
println!("Found {} FAT32 partitions", fat32_partitions.len());
Source

pub fn validate(&self) -> Result<()>

Validate this MBR structure for consistency and correctness.

This method performs comprehensive validation of this MBR structure, checking:

  • MBR signature validity (0x55AA boot signature)
  • Partition overlap detection
  • Bootable partition count (at most one partition should be bootable)
§Returns
  • Ok(()) - MBR is valid and consistent
  • Err(Error::Corrupted) - MBR is invalid or corrupted
§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));
// First create and write a valid MBR
let mut mbr = MBR_type::New_with_signature(0x12345678);
mbr.Add_partition(Partition_type_type::Fat32_lba, 2048, 1024, true).unwrap();
mbr.Write_to_device(&device).unwrap();

// Read it back and validate
let mbr = MBR_type::Read_from_device(&device).unwrap();
match mbr.Validate() {
    Ok(()) => println!("MBR is valid"),
    Err(Error::Corrupted) => println!("MBR is corrupted"),
    Err(e) => println!("Validation error: {}", e),
}
Source

pub fn generate_statistics(&self) -> PartitionStatistics

Generate comprehensive statistics from this MBR.

This method analyzes all partitions in this MBR and generates detailed statistics about partition types, sizes, and other characteristics.

§Returns

A new Partition_statistics_type containing the computed statistics.

§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));
// Create an MBR with some partitions
let mut mbr = MBR_type::New_with_signature(0x12345678);
mbr.Add_partition(Partition_type_type::Fat32_lba, 2048, 1024, true).unwrap();
mbr.Add_partition(Partition_type_type::Linux, 4096, 2048, false).unwrap();
mbr.Write_to_device(&device).unwrap();

// Read it back and analyze
let mbr = MBR_type::Read_from_device(&device).unwrap();
let stats = mbr.Generate_statistics();
if stats.Total_partitions > 0 {
    println!("Average partition size: {} sectors",
             stats.Total_used_sectors / stats.Total_partitions as u64);
}
Source

pub fn create_basic( disk_signature: u32, partition_type: PartitionKind, total_sectors: u32, ) -> Result<Self>

Create a basic MBR with a single partition covering most of the disk.

This function creates a simple MBR structure with one partition that uses most of the available disk space. It leaves 2048 sectors at the beginning for proper alignment, which is standard practice for modern storage devices.

§Arguments
  • disk_signature - Unique 32-bit signature for the disk
  • partition_type - Type of partition to create (e.g., FAT32, Linux, etc.)
  • total_sectors - Total number of sectors available on the disk
§Returns
  • Ok(MBR_type) - Successfully created MBR with single partition
  • Err(Error::InvalidParameter) - Disk is too small for a partition
§Examples
use file_system::*;

// Create MBR for a 4MB device (8192 sectors)
let mbr = MBR_type::Create_basic(0x12345678, Partition_type_type::Fat32_lba, 8192).unwrap();

// The MBR will have one FAT32 partition starting at sector 2048
let partitions = mbr.get_valid_partitions();
assert_eq!(partitions.len(), 1);
assert_eq!(partitions[0].get_start_lba(), 2048);
Source

pub fn to_bytes(&self) -> [u8; 512]

Convert MBR back to bytes

Source

pub fn find_or_create_partition_with_signature( device: &Device, target_signature: u32, partition_type: PartitionKind, ) -> Result<PartitionDevice>

Find or create a partition with a specific disk signature.

This function searches for an MBR with the specified disk signature on the device. If found, it returns a partition device for the first valid partition. If not found, or if no valid partitions exist, it formats the disk with a new MBR containing a single partition that occupies the full disk space.

§Arguments
  • device - The storage device to search or format
  • target_signature - The disk signature to look for
  • partition_type - The type of partition to create if formatting is needed
§Returns
  • Ok(Partition_device_type) - Partition device for the found or created partition
  • Err(Error) - Error if operation failed
§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));

// Look for partition with signature 0x12345678, create FAT32 partition if not found
let partition = MBR_type::Find_or_create_partition_with_signature(
    &device,
    0x12345678,
    Partition_type_type::Fat32_lba
).unwrap();

// The partition device is ready to use
assert!(partition.is_valid());
Source

pub fn format_disk_with_signature_and_partition( device: &Device, disk_signature: u32, partition_type: PartitionKind, ) -> Result<PartitionDevice>

Format a disk with a specific signature and create a single partition.

This function creates a new MBR with the specified disk signature and a single partition that occupies most of the available disk space, leaving standard alignment space at the beginning.

§Arguments
  • device - The storage device to format
  • disk_signature - The disk signature to set in the new MBR
  • partition_type - The type of partition to create
§Returns
  • Ok(Partition_device_type) - Partition device for the created partition
  • Err(Error) - Error if operation failed
§Examples
extern crate alloc;
use file_system::*;

let device = create_device!(Memory_device_type::<512>::new(4 * 1024 * 1024));

// Format disk and create a Linux partition with specific signature
let partition = MBR_type::Format_disk_with_signature_and_partition(
    &device,
    0xABCDEF00,
    Partition_type_type::Linux
).unwrap();

// Verify the partition was created correctly
assert!(partition.is_valid());
assert_eq!(partition.get_start_lba(), 2048); // Standard alignment

Trait Implementations§

Source§

impl Clone for Mbr

Source§

fn clone(&self) -> Mbr

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Mbr

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Mbr

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Mbr

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Mbr

§

impl RefUnwindSafe for Mbr

§

impl Send for Mbr

§

impl Sync for Mbr

§

impl Unpin for Mbr

§

impl UnwindSafe for Mbr

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToSmolStr for T
where T: Display + ?Sized,

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.