moon-driver-utils 0.1.0

Windows Kernel Utils
use core::ops::{Deref, DerefMut};
use wdk_sys::_POOL_TYPE::NonPagedPool;

use super::AllocationError;
use super::PoolMemory;

pub struct NPP<T: ?Sized> {
    m: PoolMemory<T>,
}

unsafe impl<T: Send> Send for NPP<T> {}
unsafe impl<T: Sync> Sync for NPP<T> {}

impl<T: Sized> NPP<T> {
    pub fn new(value: T) -> Result<Self, AllocationError> {
        let p = PoolMemory::new(value, NonPagedPool)?;
        Ok(Self { m: p })
    }

    pub fn new_type() -> Result<Self, AllocationError> {
        let p = PoolMemory::new_type(NonPagedPool)?;
        Ok(Self { m: p })
    }

    pub fn new_bytes(byte_size: u64) -> Result<Self, AllocationError> {
        let p = PoolMemory::new_bytes(NonPagedPool, byte_size)?;
        Ok(Self { m: p })
    }
}

impl<T: ?Sized> NPP<T> {
    pub fn into_raw(self) -> *mut T {
        self.m.into_raw()
    }

    pub unsafe fn from_raw(raw: *mut T) -> Result<Self, AllocationError> {
        let m = PoolMemory::from_raw(raw)?;
        Ok(Self { m })
    }

    pub fn as_ptr(&self) -> *mut T {
        self.m.as_ptr()
    }
}

impl<T: ?Sized> Deref for NPP<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &*self.m
    }
}

impl<T: ?Sized> DerefMut for NPP<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self.m
    }
}