use serde_json::Value as Json;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Waker};
use troupekit_trace::TraceSink;
static GLOBAL: Mutex<()> = Mutex::new(());
pub fn lock() -> MutexGuard<'static, ()> {
GLOBAL.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Default)]
pub struct Collect {
lines: Mutex<Vec<String>>,
}
impl Collect {
pub fn new() -> Arc<Collect> {
Arc::new(Collect::default())
}
pub fn lines(&self) -> Vec<String> {
self.lines
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub fn records(&self) -> Vec<Json> {
self.lines()
.iter()
.map(|l| serde_json::from_str(l).expect(l))
.collect()
}
pub fn of(&self, kind: &str) -> Vec<Json> {
self.records()
.into_iter()
.filter(|r| r["t"] == kind)
.collect()
}
pub fn named(&self, name: &str) -> Json {
let found: Vec<Json> = self
.records()
.into_iter()
.filter(|r| r["name"] == name)
.collect();
assert_eq!(found.len(), 1, "records named {name}: {found:?}");
found.into_iter().next().unwrap()
}
}
impl TraceSink for Collect {
fn write(&self, line: &str) {
self.lines
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(line.to_owned());
}
}
pub fn poll_once<F: Future + ?Sized>(fut: Pin<&mut F>) -> Poll<F::Output> {
fut.poll(&mut Context::from_waker(Waker::noop()))
}
#[derive(Default)]
pub struct YieldOnce {
polled: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.polled {
return Poll::Ready(());
}
self.polled = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
pub fn num(record: &Json, key: &str) -> u64 {
record[key]
.as_u64()
.unwrap_or_else(|| panic!("{key} missing in {record}"))
}
pub fn scratch_dir(label: &str) -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir()
.join("troupekit-trace-tests")
.join(format!("{label}-{}-{n}", std::process::id()));
if dir.exists() {
std::fs::remove_dir_all(&dir).unwrap();
}
std::fs::create_dir_all(&dir).unwrap();
assert!(dir.is_dir(), "the scratch dir was created");
dir
}