ad4m_client/
literal.rs

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use anyhow::{anyhow, Result};
use std::fmt::Display;

#[derive(Clone, Debug, PartialEq)]
pub enum LiteralValue {
    String(String),
    Number(f64),
    Json(serde_json::Value),
}

impl Display for LiteralValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LiteralValue::String(string) => write!(f, "{}", string),
            LiteralValue::Number(number) => write!(f, "{}", number),
            LiteralValue::Json(json) => write!(f, "{}", json),
        }
    }
}

pub struct Literal {
    value: Option<LiteralValue>,
    url: Option<String>,
}

impl Literal {
    pub fn from_url(url: String) -> Result<Self> {
        if url.starts_with("literal://") {
            Ok(Self {
                value: None,
                url: Some(url),
            })
        } else {
            Err(anyhow!("Not a literal URL"))
        }
    }

    pub fn from_string(string: String) -> Self {
        Self {
            value: Some(LiteralValue::String(string)),
            url: None,
        }
    }

    pub fn from_number(number: f64) -> Self {
        Self {
            value: Some(LiteralValue::Number(number)),
            url: None,
        }
    }

    pub fn from_json(json: serde_json::Value) -> Self {
        Self {
            value: Some(LiteralValue::Json(json)),
            url: None,
        }
    }

    pub fn to_url(&self) -> Result<String> {
        if let Some(url) = &self.url {
            Ok(url.clone())
        } else if let Some(value) = &self.value {
            match value {
                LiteralValue::String(string) => {
                    let encoded = urlencoding::encode(string);
                    Ok(format!("literal://string:{}", encoded))
                }
                LiteralValue::Number(number) => Ok(format!("literal://number:{}", number)),
                LiteralValue::Json(json) => {
                    let encoded = urlencoding::encode(&json.to_string()).to_string();
                    Ok(format!("literal://json:{}", encoded))
                }
            }
        } else {
            Err(anyhow!("No value or URL"))
        }
    }

    pub fn parse_url(&self) -> Result<LiteralValue> {
        if let Some(url) = &self.url {
            if url.starts_with("literal://") {
                let literal = url.replace("literal://", "");
                if literal.starts_with("string:") {
                    let string = literal.replace("string:", "");
                    let decoded = urlencoding::decode(&string)?;
                    Ok(LiteralValue::String(decoded.into()))
                } else if literal.starts_with("number:") {
                    let number = literal.replace("number:", "");
                    let parsed = number.parse::<f64>()?;
                    Ok(LiteralValue::Number(parsed))
                } else if literal.starts_with("json:") {
                    let json = literal.replace("json:", "");
                    let decoded = urlencoding::decode(&json)?;
                    let parsed = serde_json::from_str::<serde_json::Value>(&decoded)?;
                    Ok(LiteralValue::Json(parsed))
                } else {
                    Err(anyhow!("Unknown literal type"))
                }
            } else {
                Err(anyhow!("Not a literal URL"))
            }
        } else {
            Err(anyhow!("No URL"))
        }
    }

    pub fn get(&self) -> Result<LiteralValue> {
        if let Some(value) = &self.value {
            Ok(value.clone())
        } else if self.url.is_some() {
            self.parse_url()
        } else {
            Err(anyhow!("No value or URL"))
        }
    }

    pub fn convert(&mut self) -> Result<()> {
        if self.value.is_some() {
            self.url = Some(self.to_url()?);
            Ok(())
        } else if self.url.is_some() {
            self.value = Some(self.parse_url()?);
            Ok(())
        } else {
            Err(anyhow!("No value or URL"))
        }
    }
}

#[cfg(test)]
mod test {
    use serde_json::json;

    #[test]
    fn can_handle_strings() {
        let test_string = "test string";
        let test_url = "literal://string:test%20string";

        let literal = super::Literal::from_string(test_string.into());
        assert_eq!(literal.to_url().unwrap(), test_url);

        let mut literal2 = super::Literal::from_url(test_url.into()).unwrap();
        assert_eq!(
            literal2.get().unwrap(),
            super::LiteralValue::String(test_string.into())
        );

        literal2.convert().expect("Failed to convert");
        assert_eq!(
            literal2.value.unwrap(),
            super::LiteralValue::String(test_string.into())
        );
    }

    #[test]
    fn can_handle_numbers() {
        let test_number = 3.1;
        let test_url = "literal://number:3.1";

        let literal = super::Literal::from_number(test_number);
        assert_eq!(literal.to_url().unwrap(), test_url);

        let mut literal2 = super::Literal::from_url(test_url.into()).unwrap();
        assert_eq!(
            literal2.get().unwrap(),
            super::LiteralValue::Number(test_number)
        );

        literal2.convert().expect("Failed to convert");
        assert_eq!(
            literal2.value.unwrap(),
            super::LiteralValue::Number(test_number)
        );
    }

    #[test]
    fn can_handle_objects() {
        let test_object = json!({
            "testString": "test",
            "testNumber": "1337",
        });
        let test_url =
            "literal://json:%7B%22testNumber%22%3A%221337%22%2C%22testString%22%3A%22test%22%7D";

        let literal = super::Literal::from_json(test_object.clone());
        assert_eq!(literal.to_url().unwrap(), test_url);

        let mut literal2 = super::Literal::from_url(test_url.into()).unwrap();
        assert_eq!(
            literal2.get().unwrap(),
            super::LiteralValue::Json(test_object.clone())
        );

        literal2.convert().expect("Failed to convert");
        assert_eq!(
            literal2.value.unwrap(),
            super::LiteralValue::Json(test_object)
        );
    }

    #[test]
    fn can_handle_special_characters() {
        let test_string = "message(X) :- triple('ad4m://self', _, X).";
        let test_url = "literal://string:message%28X%29%20%3A-%20triple%28%27ad4m%3A%2F%2Fself%27%2C%20_%2C%20X%29.";

        let literal = super::Literal::from_string(test_string.into());
        assert_eq!(literal.to_url().unwrap(), test_url);

        let mut literal2 = super::Literal::from_url(test_url.into()).unwrap();
        assert_eq!(
            literal2.get().unwrap(),
            super::LiteralValue::String(test_string.into())
        );

        literal2.convert().expect("Failed to convert");
        assert_eq!(
            literal2.value.unwrap(),
            super::LiteralValue::String(test_string.into())
        );
    }
}