Skip to main content

hadris_part/
mbr_io.rs

1io_transform! {
2
3#[cfg(feature = "read")]
4use super::super::Read;
5#[cfg(feature = "write")]
6use super::super::Write;
7#[cfg(any(feature = "read", feature = "write"))]
8use crate::mbr::MasterBootRecord;
9
10// I/O operations
11
12/// Extension trait for reading [`MasterBootRecord`] from I/O sources.
13#[cfg(feature = "read")]
14#[cfg_attr(docsrs, doc(cfg(feature = "read")))]
15pub trait MasterBootRecordReadExt: Sized {
16    /// Reads an MBR from the beginning of a reader.
17    ///
18    /// # Errors
19    ///
20    /// Returns an error if reading fails or if the MBR signature is invalid.
21    async fn read_from<R: Read>(reader: &mut R) -> crate::error::Result<Self>;
22}
23
24#[cfg(feature = "read")]
25impl MasterBootRecordReadExt for MasterBootRecord {
26    async fn read_from<R: Read>(reader: &mut R) -> crate::error::Result<Self> {
27        let mut buf = [0u8; 512];
28        reader
29            .read_exact(&mut buf)
30            .await
31            .map_err(crate::error::Error::from)?;
32        let mbr: Self = bytemuck::cast(buf);
33        if !mbr.has_valid_signature() {
34            return Err(crate::error::Error::InvalidMbrSignature {
35                found: mbr.signature,
36            });
37        }
38        Ok(mbr)
39    }
40}
41
42/// Extension trait for writing [`MasterBootRecord`] to I/O sinks.
43#[cfg(feature = "write")]
44#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
45pub trait MasterBootRecordWriteExt {
46    /// Writes this MBR to a writer.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error if writing fails.
51    async fn write_to<W: Write>(&self, writer: &mut W) -> crate::error::Result<()>;
52}
53
54#[cfg(feature = "write")]
55impl MasterBootRecordWriteExt for MasterBootRecord {
56    async fn write_to<W: Write>(&self, writer: &mut W) -> crate::error::Result<()> {
57        writer
58            .write_all(bytemuck::bytes_of(self))
59            .await
60            .map_err(crate::error::Error::from)
61    }
62}
63
64} // io_transform!