Skip to main content

workflow_wasm/
printable.rs

1//! Printable representation for a JsValue. Will print the string
2//! representation if it is a string, otherwise
3//! will output the debug representation.
4
5use wasm_bindgen::prelude::*;
6
7/// Wrapper around a [`JsValue`] that provides a human-friendly `Display`
8/// implementation, printing the string contents when the value is a string
9/// and falling back to its debug representation otherwise.
10#[derive(Clone, Debug)]
11pub struct Printable(JsValue);
12
13unsafe impl Send for Printable {}
14unsafe impl Sync for Printable {}
15
16impl Printable {
17    /// Wraps the given [`JsValue`] for printable display.
18    pub fn new(value: JsValue) -> Self {
19        Self(value)
20    }
21}
22
23impl std::fmt::Display for Printable {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        if let Some(string) = self.0.as_string() {
26            write!(f, "{}", string)
27        } else {
28            write!(f, "{:?}", self.0)
29        }
30    }
31}
32
33impl AsRef<JsValue> for Printable {
34    fn as_ref(&self) -> &JsValue {
35        &self.0
36    }
37}
38
39impl From<JsValue> for Printable {
40    fn from(value: JsValue) -> Self {
41        Self(value)
42    }
43}
44
45impl From<JsError> for Printable {
46    fn from(value: JsError) -> Self {
47        Self(value.into())
48    }
49}
50
51impl From<&Printable> for JsValue {
52    fn from(value: &Printable) -> Self {
53        value.0.clone()
54    }
55}