1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::{
    borrow::Cow,
    collections::HashMap,
    sync::{Arc, RwLock},
};

#[derive(Debug, Clone)]
pub enum WildDocValue {
    Json(serde_json::Value),
    Binary(Vec<u8>),
}
impl From<serde_json::Value> for WildDocValue {
    fn from(value: serde_json::Value) -> Self {
        WildDocValue::Json(value)
    }
}
impl From<Vec<u8>> for WildDocValue {
    fn from(value: Vec<u8>) -> Self {
        WildDocValue::Binary(value)
    }
}

impl std::fmt::Display for WildDocValue {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Json(json) => match json {
                serde_json::Value::String(s) => {
                    write!(f, "{}", s)?;
                    Ok(())
                }
                _ => json.fmt(f),
            },
            Self::Binary(v) => {
                write!(f, "{}", std::str::from_utf8(v).map_or_else(|_| "", |v| v))?;
                Ok(())
            }
        }
    }
}

impl WildDocValue {
    pub fn to_json_value(&self) -> Cow<serde_json::Value> {
        match self {
            Self::Json(json) => Cow::Borrowed(json),
            Self::Binary(value) => Cow::Owned(
                serde_json::from_slice(value).map_or_else(|_| serde_json::json!({}), |v| v),
            ),
        }
    }
    pub fn to_json_value_mut(&mut self) -> Option<&mut serde_json::Value> {
        match self {
            Self::Json(json) => Some(json),
            _ => None,
        }
    }
    pub fn as_bytes(&self) -> Cow<[u8]> {
        match self {
            Self::Json(json) => Cow::Owned(json.to_string().into_bytes()),
            Self::Binary(value) => Cow::Borrowed(value),
        }
    }
    pub fn to_str(&self) -> Cow<str> {
        match self {
            Self::Json(json) => Cow::Owned(json.to_string()),
            Self::Binary(value) => Cow::Borrowed(unsafe { std::str::from_utf8_unchecked(value) }),
        }
    }
}
pub type Vars = HashMap<Vec<u8>, Arc<RwLock<WildDocValue>>>;
pub type VarsStack = Vec<Vars>;