use std::collections::VecDeque;
use std::sync::{Mutex, OnceLock, PoisonError};
use crate::{Response, sys};
pub(crate) const DELIVER_EXPORT: &str = "__mirust_deliver";
pub(crate) const RUN_EXPORT: &str = "__mirust_run";
static QUEUE: Mutex<VecDeque<(String, String)>> = Mutex::new(VecDeque::new());
fn queue() -> std::sync::MutexGuard<'static, VecDeque<(String, String)>> {
QUEUE.lock().unwrap_or_else(PoisonError::into_inner)
}
fn call_self(export: &str) -> String {
format!("dll \" $+ $1- $+ \" {export}")
}
pub(crate) fn intercept(response: Response) -> Response {
let mut queue = queue();
if let Response::Command { command, parms } = response {
if command.is_empty() {
} else {
queue.push_back((command, parms));
}
} else if queue.is_empty() {
return response;
}
if queue.is_empty() {
return Response::Continue;
}
drop(queue);
Response::command_with(call_self(DELIVER_EXPORT), own_path())
}
pub(crate) fn deliver(max_len: usize) -> Response {
let pending = queue().len();
if pending == 0 {
return Response::Continue;
}
let run = call_self(RUN_EXPORT);
let again = call_self(DELIVER_EXPORT);
const SEPARATOR: &str = " | ";
let all_fit = pending * (run.len() + SEPARATOR.len()) - SEPARATOR.len() <= max_len;
let mut segments = if all_fit {
vec![run.as_str(); pending]
} else {
let fit = max_len.saturating_sub(again.len()) / (run.len() + SEPARATOR.len());
vec![run.as_str(); fit.max(1)]
};
if !all_fit {
segments.push(&again);
}
Response::command_with(segments.join(SEPARATOR), own_path())
}
pub(crate) fn run_next() -> Response {
match queue().pop_front() {
Some((command, parms)) => Response::Command { command, parms },
None => Response::Continue,
}
}
pub(crate) fn own_path() -> String {
static PATH: OnceLock<String> = OnceLock::new();
PATH.get_or_init(|| {
let Some(module) = crate::entry::own_module() else {
return String::new();
};
let mut buf = vec![0u16; 260];
loop {
let len = unsafe { sys::GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32) }
as usize;
if len < buf.len() {
return String::from_utf16_lossy(&buf[..len]);
}
buf.resize(buf.len() * 2, 0);
}
})
.clone()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queues_commands_and_delivers_each_once_in_order() {
let delivery = Response::command_with(call_self(DELIVER_EXPORT), own_path());
assert!(own_path().ends_with(".exe") || own_path().ends_with(".dll"));
assert_eq!(intercept(Response::Continue), Response::Continue);
assert_eq!(
intercept(Response::Return("x".into())),
Response::Return("x".into())
);
assert_eq!(intercept(Response::command("")), Response::Continue);
assert_eq!(
intercept(Response::command_with("first $1-", "a")),
delivery
);
assert_eq!(
intercept(Response::command_with("second $1-", "b")),
delivery
);
assert_eq!(intercept(Response::Continue), delivery);
let Response::Command { command, parms } = deliver(10_000) else {
panic!("expected a command");
};
assert_eq!(command, format!("{0} | {0}", call_self(RUN_EXPORT)));
assert_eq!(parms, own_path());
assert_eq!(run_next(), Response::command_with("first $1-", "a"));
assert_eq!(run_next(), Response::command_with("second $1-", "b"));
assert_eq!(run_next(), Response::Continue);
assert_eq!(deliver(10_000), Response::Continue);
for i in 0..50 {
intercept(Response::command_with("cmd", i.to_string()));
}
let Response::Command { command, .. } = deliver(200) else {
panic!("expected a command");
};
assert!(command.len() <= 200, "{} > 200", command.len());
assert!(command.ends_with(&call_self(DELIVER_EXPORT)));
let runs = command.matches(RUN_EXPORT).count();
assert!((1..50).contains(&runs), "{runs} runs");
while run_next() != Response::Continue {}
}
}