garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /disk/src/lib.rs

raw

//! What a whole disk holds around Pinnacle's own file system (`pfs`): its
//! partition table (`gpt`), and the FAT32 partition a UEFI firmware starts
//! a system from (`fat`). Shared by the kernel, which reads both and whose
//! installer writes them, and by `cargo xtask`, which makes an install
//! medium on the host with no outside tool.
//!
//! Both speak in bytes at offsets on the disk, through [`Medium`], so they
//! do not care how large a sector or a block of the disk below is.

#![no_std]

extern crate alloc;

pub mod fat;
pub mod gpt;

#[cfg(test)]
mod tests;

/// A disk as bytes: what `gpt` and `fat` read and write through.
pub trait Medium {
    /// Fills `into` from the disk's bytes at `offset`. False when that
    /// lies beyond the disk or the read failed.
    fn read_at(&mut self, offset: u64, into: &mut [u8]) -> bool;
    /// Writes `from` at `offset`. False when it did not.
    fn write_at(&mut self, offset: u64, from: &[u8]) -> bool;
    /// The disk's size in bytes.
    fn size(&self) -> u64;
}

impl Medium for alloc::vec::Vec<u8> {
    fn read_at(&mut self, offset: u64, into: &mut [u8]) -> bool {
        let Some(end) = (offset as usize)
            .checked_add(into.len())
            .filter(|&e| e <= self.len())
        else {
            return false;
        };
        into.copy_from_slice(&self[offset as usize..end]);
        true
    }

    fn write_at(&mut self, offset: u64, from: &[u8]) -> bool {
        let Some(end) = (offset as usize)
            .checked_add(from.len())
            .filter(|&e| e <= self.len())
        else {
            return false;
        };
        self[offset as usize..end].copy_from_slice(from);
        true
    }

    fn size(&self) -> u64 {
        self.len() as u64
    }
}

/// CRC-32 as GPT (and zip, and Ethernet) has it: IEEE 802.3, reflected.
pub fn crc32(bytes: &[u8]) -> u32 {
    let mut crc = !0u32;
    for &b in bytes {
        crc ^= u32::from(b);
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0xedb8_8320
            } else {
                crc >> 1
            };
        }
    }
    !crc
}

pub(crate) fn u16_at(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([b[at], b[at + 1]])
}

pub(crate) fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}

pub(crate) fn u64_at(b: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
}