use std::collections::VecDeque;
use std::sync::Mutex;
use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, HANDLE};
use super::Kernel;
use crate::identity::Key;
pub(crate) struct FakeKernel {
creation_tokens: Mutex<VecDeque<Result<Key, HRESULT>>>,
terminates: Mutex<VecDeque<Result<(), HRESULT>>>,
}
fn access_denied() -> HRESULT {
HRESULT::from_win32(ERROR_ACCESS_DENIED.0)
}
pub(crate) fn refusing_the_next_terminate() -> FakeKernel {
FakeKernel::new().on_terminate(Err(access_denied()))
}
impl FakeKernel {
pub(crate) fn new() -> Self {
FakeKernel {
creation_tokens: Mutex::new(VecDeque::new()),
terminates: Mutex::new(VecDeque::new()),
}
}
pub(crate) fn on_creation_token(mut self, answer: Result<Key, HRESULT>) -> Self {
self.creation_tokens
.get_mut()
.expect("no thread holds the rows")
.push_back(answer);
self
}
pub(crate) fn on_terminate(mut self, answer: Result<(), HRESULT>) -> Self {
self.terminates
.get_mut()
.expect("no thread holds the rows")
.push_back(answer);
self
}
pub(crate) fn all_rows_taken(&self) -> bool {
self.terminates
.lock()
.expect("no thread panics holding the rows")
.is_empty()
&& self
.creation_tokens
.lock()
.expect("no thread panics holding the rows")
.is_empty()
}
}
impl Kernel for FakeKernel {
fn creation_token(&self, _handle: HANDLE) -> windows::core::Result<Key> {
let row = self
.creation_tokens
.lock()
.expect("no thread panics holding the rows")
.pop_front();
match row.expect("the fake kernel has no row left for creation_token") {
Ok(key) => Ok(key),
Err(code) => Err(windows::core::Error::from_hresult(code)),
}
}
fn terminate(&self, _handle: HANDLE, _exit_code: u32) -> windows::core::Result<()> {
let row = self
.terminates
.lock()
.expect("no thread panics holding the rows")
.pop_front();
match row.expect("the fake kernel has no row left for terminate") {
Ok(()) => Ok(()),
Err(code) => Err(windows::core::Error::from_hresult(code)),
}
}
}