mkwim 0.1.0

Create a bootable Windows installation image from an ISO
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2026 Jarkko Sakkinen
#![allow(clippy::cast_precision_loss)]

//! Small host-side helpers: cryptographically random bytes, human-readable
//! sizes, and a root-privilege check.

use std::io::Read;

use anyhow::Result;

/// Fill an `N`-byte array with random bytes from `/dev/urandom`.
pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N]> {
    let mut buf = [0u8; N];
    let mut f = std::fs::File::open("/dev/urandom")?;
    f.read_exact(&mut buf)?;
    Ok(buf)
}

/// Format a byte count as a human-readable string (e.g. "1.5 GiB").
pub fn human_size(size_b: u64) -> String {
    const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
    let mut size = size_b as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }
    format!("{size:.1} {}", UNITS[unit])
}

/// Whether the current process has superuser privileges.
pub(crate) fn running_as_root() -> bool {
    unsafe { libc::geteuid() == 0 }
}

/// Flush all filesystem buffers to stable storage.
pub(crate) fn sync_all() {
    unsafe { libc::sync() };
}