/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

sluggish-write

Copyright (C) 2026  Anonymous



This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

use {
    core::ptr,
    crate::Result,
};

#[cfg(target_pointer_width="64")]
type ULONG = u64;
#[cfg(target_pointer_width="32")]
type ULONG = u32;

const BCRYPT_USE_SYSTEM_PREFERRED_RNG: ULONG = 0x_0000_0002;

//  https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55
const STATUS_SUCCESS: ULONG = 0x_0000_0000;

#[link(name="Bcrypt")]
unsafe extern "system" {
    unsafe fn BCryptGenRandom(h_algorithm: *const ULONG, pb_buffer: *mut u8, cb_buffer: ULONG, dw_flags: ULONG) -> ULONG;
}

pub (super) fn read_exact(buf: &mut [u8]) -> Result<()> {
    if buf.is_empty() {
        return Ok(());
    }
    match unsafe {
        BCryptGenRandom(
            ptr::null(),
            buf.as_mut_ptr(),
            ULONG::try_from(buf.len()).map_err(|_| err!("Could not convert {} into ULONG", buf.len()))?,
            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
        )
    } {
        STATUS_SUCCESS => Ok(()),
        other => Err(err!("BCryptGenRandom() returned: 0x{other:08x?} ({other})")),
    }
}
