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
71
72
73
74
75
76
77
78
use ore_encoding_rs::{siphash, OrePlaintext};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(untagged)]
pub enum Value {
    Uint64(u64),
    Float64(f64),
    String(String),
    Boolean(bool),
    Date(f64),
    Map(HashMap<String, Value>),
}

impl From<u64> for Value {
    fn from(val: u64) -> Self {
        Self::Uint64(val)
    }
}

impl From<f64> for Value {
    fn from(val: f64) -> Self {
        Self::Float64(val)
    }
}

impl From<String> for Value {
    fn from(val: String) -> Self {
        Self::String(val)
    }
}

impl From<&str> for Value {
    fn from(val: &str) -> Self {
        Self::String(val.into())
    }
}

impl From<bool> for Value {
    fn from(val: bool) -> Self {
        Self::Boolean(val)
    }
}

impl From<HashMap<String, Value>> for Value {
    fn from(val: HashMap<String, Value>) -> Self {
        Self::Map(val)
    }
}

impl Value {
    /// Convert the value into it's CipherStash plaintext
    ///
    /// Values that don't have a u64 plaintext representation (maps and arrays) will
    /// return None
    pub fn as_plaintext(&self) -> Option<OrePlaintext<u64>> {
        match &self {
            Value::Uint64(x) => Some((*x).into()),
            Value::Float64(x) => Some((*x).into()),
            Value::Date(x) => Some((*x).into()),
            // Strings are typically only used for exact matches, so instead of converting every
            // character in the string into a plaintext, the entire string is siphashed so it'll
            // fit into a u64.
            Value::String(x) => Some((siphash(x.as_bytes())).into()),
            Value::Boolean(x) => Some((*x).into()),
            _ => None,
        }
    }

    /// Check whether the current value is a string
    pub fn is_string(&self) -> bool {
        match self {
            Value::String(_) => true,
            _ => false,
        }
    }
}