mln-rs-webgpu 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::fmt;
use std::sync::Arc;

use parking_lot::Mutex;
use tracing::field::{Field, Visit};
use tracing_subscriber::layer::{Context, SubscriberExt as _};
use tracing_subscriber::{Layer, registry};

use crate::device::backend_type_to_string;

/// A record that the test subscriber caught: its level, target, message and
/// other fields as `name=value` pairs, in the order the call site lists them.
type Caught = (tracing::Level, String, String, Vec<String>);

/// Collects the events of one crate.
struct Catcher {
    krate: &'static str,
    records: Arc<Mutex<Vec<Caught>>>,
}

impl<S: tracing::Subscriber> Layer<S> for Catcher {
    fn on_event(&self, event: &tracing::Event<'_>, _: Context<'_, S>) {
        let metadata = event.metadata();
        if metadata.target().split("::").next() != Some(self.krate) {
            return;
        }
        let mut fields = Fields { message: String::new(), others: Vec::new() };
        event.record(&mut fields);
        self.records.lock().push((*metadata.level(), metadata.target().to_owned(), fields.message, fields.others));
    }
}

/// An event's `message` and its other fields.
struct Fields {
    message: String,
    others: Vec<String>,
}

impl Visit for Fields {
    fn record_str(&mut self, field: &Field, value: &str) {
        self.record_debug(field, &format_args!("{value}"));
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        if field.name() == "message" {
            self.message = format!("{value:?}");
        } else {
            self.others.push(format!("{}={value:?}", field.name()));
        }
    }
}

/// Runs `f` and returns its result with the events of `krate` that it
/// logged on this thread.
fn capture<T>(krate: &'static str, f: impl FnOnce() -> T) -> (T, Vec<Caught>) {
    let records = Arc::new(Mutex::new(Vec::new()));
    let guard = tracing::subscriber::set_default(registry().with(Catcher { krate, records: Arc::clone(&records) }));
    let result = f();
    drop(guard);
    let records = std::mem::take(&mut *records.lock());
    (result, records)
}

#[test]
fn a_device_logs_its_adapter() {
    let (device, records) = capture("mln_webgpu", super::device);
    let Some(device) = device else {
        return;
    };

    let info = device.adapter_info();
    let fields = vec![format!("adapter={}", info.name), format!("backend={}", backend_type_to_string(info.backend))];
    assert_eq!(
        records,
        [(
            tracing::Level::INFO,
            "mln_webgpu::render".to_owned(),
            "Graphics device uses a WebGPU adapter".to_owned(),
            fields
        )]
    );
}