foundation_core 0.0.3

Central crate for all foundation crates for the ewe-platform project
Documentation
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::collections::VecDeque;

use serde::de::DeserializeOwned;
use serde::Serialize;
use toml::{map::Map, Value};
use toml_datetime::{Date, Datetime};

use super::{AsType, DynamicValueExt, PointerValueExt, ValueError, ValueResult};

// -- Implement AsType

impl AsType<'_, Value> for String {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        Ok(String::from(
            value.as_str().ok_or(ValueError::ValueNotType("str"))?,
        ))
    }
}

impl<'a> AsType<'a, Value> for &'a str {
    fn from_value(value: &'a Value) -> ValueResult<Self, ValueError> {
        value.as_str().ok_or(ValueError::ValueNotType("str"))
    }
}

impl AsType<'_, Value> for bool {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value.as_bool().ok_or(ValueError::ValueNotType("bool"))
    }
}

impl AsType<'_, Value> for f64 {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value.as_float().ok_or(ValueError::ValueNotType("f64"))
    }
}

impl AsType<'_, Value> for u32 {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value
            .as_integer()
            .map(i64::unsigned_abs)
            .and_then(|v| u32::try_from(v).ok())
            .ok_or(ValueError::ValueNotType("u32"))
    }
}

impl AsType<'_, Value> for i32 {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value
            .as_integer()
            .and_then(|v| i32::try_from(v).ok())
            .ok_or(ValueError::ValueNotType("i32"))
    }
}

impl AsType<'_, Value> for i64 {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value.as_integer().ok_or(ValueError::ValueNotType("i64"))
    }
}

impl AsType<'_, Value> for Date {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        match value.as_datetime() {
            Some(item) => match item.date {
                Some(item_date) => Ok(item_date),
                None => Err(ValueError::ValueNotType("date")),
            },
            None => Err(ValueError::ValueNotType("date")),
        }
    }
}

impl AsType<'_, Value> for Datetime {
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value
            .as_datetime()
            .map(std::borrow::ToOwned::to_owned)
            .ok_or(ValueError::ValueNotType("datetime"))
    }
}

impl AsType<'_, Value> for u64 {
    /// For u64 we take the integer (i64) value and convert into an unsigned absolute
    /// of the value, so be aware you might loose sign and potential precision.
    fn from_value(value: &Value) -> ValueResult<Self, ValueError> {
        value
            .as_integer()
            .map(i64::unsigned_abs)
            .ok_or(ValueError::ValueNotType("u64"))
    }
}

// -- Error and Result

#[derive(Debug, derive_more::From)]
pub enum TomlError {
    #[from(ignore)]
    Value(ValueError),

    #[from(ignore)]
    NotFound,

    #[from(ignore)]
    NotTable,

    #[from(ignore)]
    NoValueAt(String),

    #[from(ignore)]
    FailedDeserialization(toml::de::Error),

    #[from(ignore)]
    FailedSerialization(toml::ser::Error),
}

// -- From<T> and Into<TomlError>

impl From<toml::ser::Error> for TomlError {
    fn from(value: toml::ser::Error) -> Self {
        Self::FailedSerialization(value)
    }
}

impl From<toml::de::Error> for TomlError {
    fn from(value: toml::de::Error) -> Self {
        Self::FailedDeserialization(value)
    }
}

impl From<ValueError> for TomlError {
    fn from(value: ValueError) -> Self {
        Self::Value(value)
    }
}

// --- region: Custom methods

impl TomlError {
    pub fn value<V: Into<ValueError>>(val: V) -> Self {
        Self::Value(val.into())
    }

    pub fn custom<T>(val: T) -> Self
    where
        T: std::fmt::Display,
    {
        Self::Value(ValueError::Custom(val.to_string()))
    }

    pub fn into_custom<T>(val: T) -> Self
    where
        T: Into<String>,
    {
        Self::Value(ValueError::Custom(val.into()))
    }
}

// --- end region: Custom methods

// --- region: Error & Display boilerplate

impl std::error::Error for TomlError {}

impl core::fmt::Display for TomlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

// --- end region: Error & Display boilerplate

// --- end region: TomlError

impl PointerValueExt for Value {
    type Item = Value;
    type Error = TomlError;

    fn get_path(&self, name_or_pointer: &str) -> ValueResult<&Self::Item, Self::Error> {
        if !name_or_pointer.contains('/') {
            return self
                .get(name_or_pointer)
                .ok_or_else(|| ValueError::PropertyNotFound(name_or_pointer.to_string()).into());
        }

        let pointer_parts: Vec<&str> = name_or_pointer.split('/').skip(1).collect();

        let mut current_value = self;
        for &part in &pointer_parts[..pointer_parts.len() - 1] {
            match current_value {
                Value::Table(table) => {
                    if !table.contains_key(part) {
                        return Err(TomlError::NotFound);
                    }
                    match table.get(part) {
                        Some(item) => {
                            current_value = item;
                        }
                        None => return Err(TomlError::NoValueAt(String::from(part))),
                    }
                }
                _ => return Err(TomlError::NotTable),
            }
        }

        if let Some(&last_part) = pointer_parts.last() {
            match current_value {
                Value::Table(table) => {
                    if !table.contains_key(last_part) {
                        return Err(TomlError::NotFound);
                    }
                    match table.get(last_part) {
                        Some(item) => {
                            return Ok(item);
                        }
                        None => return Err(TomlError::NoValueAt(String::from(last_part))),
                    }
                }
                _ => return Err(TomlError::NotTable),
            }
        }

        Err(TomlError::custom("invalid path"))
    }

    fn take_path(&mut self, name_or_pointer: &str) -> ValueResult<Self::Item, Self::Error> {
        if !name_or_pointer.contains('/') {
            return self
                .get(name_or_pointer)
                .map(std::borrow::ToOwned::to_owned)
                .ok_or_else(|| ValueError::PropertyNotFound(name_or_pointer.to_string()).into());
        }

        let pointer_parts: Vec<&str> = name_or_pointer.split('/').skip(1).collect();

        let mut current_value = self;
        for &part in &pointer_parts[..pointer_parts.len() - 1] {
            match current_value {
                Value::Table(table) => {
                    if !table.contains_key(part) {
                        return Err(TomlError::NotFound);
                    }
                    match table.get_mut(part) {
                        Some(item) => {
                            current_value = item;
                        }
                        None => return Err(TomlError::NoValueAt(String::from(part))),
                    }
                }
                _ => return Err(TomlError::NotTable),
            }
        }

        if let Some(&last_part) = pointer_parts.last() {
            match current_value {
                Value::Table(table) => {
                    if !table.contains_key(last_part) {
                        return Err(TomlError::NotFound);
                    }
                    match table.get_mut(last_part) {
                        Some(item) => {
                            return Ok(item.to_owned());
                        }
                        None => return Err(TomlError::NoValueAt(String::from(last_part))),
                    }
                }
                _ => return Err(TomlError::NotTable),
            }
        }

        Err(TomlError::custom("invalid path"))
    }
}

pub trait TomlValueExt: DynamicValueExt {
    /// Walks through all properties in the JSON value tree and calls the callback function
    /// on each key.
    /// It creates a missing `Value::Table` entries as needed.
    fn d_walk<F>(&mut self, callback: F) -> bool
    where
        F: FnMut(&mut Map<String, Value>, &str) -> bool;
}

impl DynamicValueExt for Value {
    type Item = Value;
    type Error = TomlError;

    fn d_new() -> Value {
        Value::Table(Map::new())
    }

    fn d_get<T: DeserializeOwned>(&self, name_or_pointer: &str) -> ValueResult<T, Self::Error> {
        let value = PointerValueExt::get_path(self, name_or_pointer)?;
        T::deserialize(value.to_owned()).map_err(std::convert::Into::into)
    }

    fn d_get_as<'a, V: AsType<'a, Self::Item>>(
        &'a self,
        name_or_pointer: &str,
    ) -> ValueResult<V, Self::Error> {
        let value = PointerValueExt::get_path(self, name_or_pointer)?;
        V::from_value(value).map_err(std::convert::Into::into)
    }

    fn d_take<T: DeserializeOwned>(
        &mut self,
        name_or_pointer: &str,
    ) -> ValueResult<T, Self::Error> {
        let value = PointerValueExt::take_path(self, name_or_pointer)?;
        T::deserialize(value.clone()).map_err(std::convert::Into::into)
    }

    fn d_insert<T: Serialize>(
        &mut self,
        name_or_pointer: &str,
        value: T,
    ) -> ValueResult<(), Self::Error> {
        let new_value = Value::try_from(value)?;

        if name_or_pointer.starts_with('/') {
            let parts: Vec<&str> = name_or_pointer.split('/').skip(1).collect();
            let mut current = self;

            // -- Add the eventual missing parents
            for &part in &parts[..parts.len() - 1] {
                match current {
                    Value::Table(table) => {
                        current = table
                            .entry(part)
                            .or_insert_with(|| toml::Value::Table(Map::new()));
                    }
                    _ => return Err(TomlError::custom("Path does not point to an Table")),
                }
            }

            // -- Set the value at the last element
            if let Some(&last_part) = parts.last() {
                match current {
                    Value::Table(map) => {
                        map.insert(last_part.to_string(), new_value);
                        Ok(())
                    }
                    _ => Err(TomlError::into_custom("Path does not point to an Table")),
                }
            } else {
                Err(TomlError::into_custom("Invalid path"))
            }
        } else {
            match self {
                Value::Table(map) => {
                    map.insert(name_or_pointer.to_string(), new_value);
                    Ok(())
                }
                _ => Err(TomlError::custom("Value is not an Table, cannot d_insert")),
            }
        }
    }

    fn d_pretty(&self) -> ValueResult<String, Self::Error> {
        let content = toml::to_string_pretty(self)?;
        Ok(content)
    }
}

impl TomlValueExt for Value {
    fn d_walk<F>(&mut self, mut callback: F) -> bool
    where
        F: FnMut(&mut Map<String, Value>, &str) -> bool,
    {
        let mut queue = VecDeque::new();
        queue.push_back(self);

        while let Some(current) = queue.pop_front() {
            if let Value::Table(map) = current {
                // Call the callback for each property name in the current map
                for key in map.keys().cloned().collect::<Vec<_>>() {
                    let res = callback(map, &key);
                    if !res {
                        return false;
                    }
                }

                // Add all nested Tables and arrays to the queue for further processing
                for (_, value) in map.iter_mut() {
                    if value.is_table() || value.is_array() {
                        queue.push_back(value);
                    }
                }
            } else if let Value::Array(arr) = current {
                // If current value is an array, add its elements to the queue
                for value in arr.iter_mut() {
                    if value.is_table() || value.is_array() {
                        queue.push_back(value);
                    }
                }
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::{DynamicValueExt, TomlValueExt};
    use toml::toml;

    #[test]
    fn test_value_can_walk() {
        // -- Setup & Fixtures
        let mut value = toml::Value::Table(toml! {
            token=3

            [hello]
            word = "hello"

            [hello.wreckage]
            where = "londo"
        });

        // -- Exec
        assert!(value.d_walk(|tree, key| {
            assert!(tree.contains_key(key));
            true
        }));
    }

    #[test]
    fn test_value_can_take() {
        // -- Setup & Fixtures
        let mut value = toml::Value::Table(toml! {
            token=3

            [hello]
            word = "hello"
        });

        // -- Exec
        let content: String = value.d_take("/hello/word").unwrap();
        assert_eq!(&content, "hello");

        // Should
        assert!(value.d_get::<String>("hello").is_err());
        assert!(value.d_get::<String>("hello/word").is_err());
    }

    #[test]
    fn test_value_insert_ok() {
        // -- Setup & Fixtures
        let mut value = toml::Value::Table(toml! {
            token=3

            [hello]
            word = "hello"
        });

        let fx_node_value = "hello";

        // -- Exec
        let result = value.d_insert("/happy/word", fx_node_value);
        assert!(matches!(result, Ok(())));

        // -- Check
        let actual_value: String = value.d_get("/happy/word").unwrap();
        assert_eq!(actual_value.as_str(), fx_node_value);
    }
}