use std::cell::RefCell;
use std::future::Future;
use std::io::Write;
use std::rc::Rc;
tokio::task_local! {
static CALL: Call;
}
struct Call {
http: reqwest::Client,
input: Option<String>,
output: Rc<RefCell<Vec<u8>>>,
}
pub struct Sink(Rc<RefCell<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.borrow_mut().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
pub fn active() -> bool {
CALL.try_with(|_| ()).is_ok()
}
pub fn http_client() -> Option<reqwest::Client> {
CALL.try_with(|call| call.http.clone()).ok()
}
pub fn sink() -> Option<Sink> {
CALL.try_with(|call| Sink(Rc::clone(&call.output))).ok()
}
pub fn input() -> Option<String> {
CALL.try_with(|call| call.input.clone()).ok().flatten()
}
pub async fn scope<F: Future>(
http: reqwest::Client,
input: Option<String>,
command: F,
) -> (F::Output, Vec<u8>) {
let output = Rc::new(RefCell::new(Vec::new()));
let call = Call {
http,
input,
output: Rc::clone(&output),
};
let result = CALL.scope(call, command).await;
let written = std::mem::take(&mut *output.borrow_mut());
(result, written)
}