pjson-rs-domain 0.5.2

Pure domain logic for PJS - WASM-compatible core
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Domain-specific JSON data value object
//!
//! Provides a Clean Architecture compliant representation of JSON data
//! without depending on external serialization libraries in the domain layer.

use crate::{DomainError, DomainResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

/// Domain-specific representation of JSON-like data
/// This replaces serde_json::Value to maintain Clean Architecture principles
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub enum JsonData {
    #[default]
    /// Null value
    Null,
    /// Boolean value
    Bool(bool),
    /// Integer value
    Integer(i64),
    /// Float value (stored as f64 for simplicity)
    Float(f64),
    /// String value
    String(String),
    /// Array of JsonData values
    Array(Vec<JsonData>),
    /// Object with string keys and JsonData values
    Object(HashMap<String, JsonData>),
}

impl JsonData {
    /// Create a new null value
    pub fn null() -> Self {
        Self::Null
    }

    /// Create a new boolean value
    pub fn bool(value: bool) -> Self {
        Self::Bool(value)
    }

    /// Create a new integer value
    pub fn integer(value: i64) -> Self {
        Self::Integer(value)
    }

    /// Create a new float value.
    ///
    /// Returns `Err` when `value` is NaN or infinite. JSON (RFC 8259 §6) does not
    /// allow non-finite numbers, so a `JsonData` containing one could never be
    /// serialized to valid JSON.
    ///
    /// # Examples
    ///
    /// ```
    /// use pjson_rs_domain::value_objects::JsonData;
    ///
    /// assert!(JsonData::float(3.14).is_ok());
    /// assert!(JsonData::float(f64::NAN).is_err());
    /// assert!(JsonData::float(f64::INFINITY).is_err());
    /// ```
    pub fn float(value: f64) -> DomainResult<Self> {
        if value.is_nan() || value.is_infinite() {
            return Err(DomainError::InvalidInput(
                "JSON does not support NaN or infinite float values (RFC 8259 §6)".to_string(),
            ));
        }
        Ok(Self::Float(value))
    }

    /// Create a new string value
    pub fn string<S: Into<String>>(value: S) -> Self {
        Self::String(value.into())
    }

    /// Create a new array value
    pub fn array(values: Vec<JsonData>) -> Self {
        Self::Array(values)
    }

    /// Create a new object value
    pub fn object(values: HashMap<String, JsonData>) -> Self {
        Self::Object(values)
    }

    /// Check if value is null
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Check if value is boolean
    pub fn is_bool(&self) -> bool {
        matches!(self, Self::Bool(_))
    }

    /// Check if value is integer
    pub fn is_integer(&self) -> bool {
        matches!(self, Self::Integer(_))
    }

    /// Check if value is float
    pub fn is_float(&self) -> bool {
        matches!(self, Self::Float(_))
    }

    /// Check if value is number (integer or float)
    pub fn is_number(&self) -> bool {
        matches!(self, Self::Integer(_) | Self::Float(_))
    }

    /// Check if value is string
    pub fn is_string(&self) -> bool {
        matches!(self, Self::String(_))
    }

    /// Check if value is array
    pub fn is_array(&self) -> bool {
        matches!(self, Self::Array(_))
    }

    /// Check if value is object
    pub fn is_object(&self) -> bool {
        matches!(self, Self::Object(_))
    }

    /// Get boolean value if this is a boolean
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Get integer value if this is an integer
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Get float value if this is a float
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Float(f) => Some(*f),
            Self::Integer(i) => Some(*i as f64),
            _ => None,
        }
    }

    /// Get string value if this is a string
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// Get array value if this is an array
    pub fn as_array(&self) -> Option<&Vec<JsonData>> {
        match self {
            Self::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Get mutable array value if this is an array
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<JsonData>> {
        match self {
            Self::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Get object value if this is an object
    pub fn as_object(&self) -> Option<&HashMap<String, JsonData>> {
        match self {
            Self::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Get mutable object value if this is an object
    pub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, JsonData>> {
        match self {
            Self::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Get value by key (if this is an object)
    pub fn get(&self, key: &str) -> Option<&JsonData> {
        match self {
            Self::Object(obj) => obj.get(key),
            _ => None,
        }
    }

    /// Get nested value by path (dot notation)
    pub fn get_path(&self, path: &str) -> Option<&JsonData> {
        let parts: Vec<&str> = path.split('.').collect();
        let mut current = self;

        for part in parts {
            match current {
                Self::Object(obj) => {
                    current = obj.get(part)?;
                }
                _ => return None,
            }
        }

        Some(current)
    }

    /// Set nested value by path (dot notation)
    pub fn set_path(&mut self, path: &str, value: JsonData) -> bool {
        let parts: Vec<&str> = path.split('.').collect();
        if parts.is_empty() {
            return false;
        }

        if parts.len() == 1 {
            if let Self::Object(obj) = self {
                obj.insert(parts[0].to_string(), value);
                return true;
            }
            return false;
        }

        // Navigate to parent and create intermediate objects if needed
        let mut current = self;
        for part in &parts[..parts.len() - 1] {
            match current {
                Self::Object(obj) => {
                    if !obj.contains_key(*part) {
                        obj.insert(part.to_string(), Self::object(HashMap::new()));
                    }
                    current = obj
                        .get_mut(*part)
                        .expect("Key must exist as we just inserted it above");
                }
                _ => return false,
            }
        }

        // Set final value
        if let Self::Object(obj) = current {
            obj.insert(parts[parts.len() - 1].to_string(), value);
            true
        } else {
            false
        }
    }

    /// Estimate memory size in bytes
    pub fn memory_size(&self) -> usize {
        match self {
            Self::Null => 1,
            Self::Bool(_) => 1,
            Self::Integer(_) => 8,
            Self::Float(_) => 8,
            Self::String(s) => s.len() * 2, // UTF-16 estimation
            Self::Array(arr) => 8 + arr.iter().map(|v| v.memory_size()).sum::<usize>(),
            Self::Object(obj) => {
                16 + obj
                    .iter()
                    .map(|(k, v)| k.len() * 2 + v.memory_size())
                    .sum::<usize>()
            }
        }
    }
}

impl fmt::Display for JsonData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => write!(f, "null"),
            Self::Bool(b) => write!(f, "{b}"),
            Self::Integer(i) => write!(f, "{i}"),
            Self::Float(float_val) => write!(f, "{float_val}"),
            Self::String(s) => write!(f, "\"{s}\""),
            Self::Array(arr) => {
                write!(f, "[")?;
                for (i, item) in arr.iter().enumerate() {
                    if i > 0 {
                        write!(f, ",")?;
                    }
                    write!(f, "{item}")?;
                }
                write!(f, "]")
            }
            Self::Object(obj) => {
                write!(f, "{{")?;
                for (i, (key, value)) in obj.iter().enumerate() {
                    if i > 0 {
                        write!(f, ",")?;
                    }
                    write!(f, "\"{key}\":{value}")?;
                }
                write!(f, "}}")
            }
        }
    }
}

impl Eq for JsonData {}

impl std::hash::Hash for JsonData {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Self::Null => 0u8.hash(state),
            Self::Bool(b) => {
                1u8.hash(state);
                b.hash(state);
            }
            Self::Integer(i) => {
                2u8.hash(state);
                i.hash(state);
            }
            Self::Float(f) => {
                3u8.hash(state);
                // For floats, convert to bits for consistent hashing
                f.to_bits().hash(state);
            }
            Self::String(s) => {
                4u8.hash(state);
                s.hash(state);
            }
            Self::Array(arr) => {
                5u8.hash(state);
                arr.hash(state);
            }
            Self::Object(obj) => {
                6u8.hash(state);
                // HashMap doesn't have deterministic iteration order,
                // so we need to sort keys for consistent hashing
                let mut pairs: Vec<_> = obj.iter().collect();
                pairs.sort_by_key(|(k, _)| *k);
                pairs.hash(state);
            }
        }
    }
}

impl From<bool> for JsonData {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i64> for JsonData {
    fn from(value: i64) -> Self {
        Self::Integer(value)
    }
}

impl From<String> for JsonData {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for JsonData {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

impl From<Vec<JsonData>> for JsonData {
    fn from(value: Vec<JsonData>) -> Self {
        Self::Array(value)
    }
}

impl From<HashMap<String, JsonData>> for JsonData {
    fn from(value: HashMap<String, JsonData>) -> Self {
        Self::Object(value)
    }
}

impl From<serde_json::Value> for JsonData {
    fn from(value: serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::Null,
            serde_json::Value::Bool(b) => Self::Bool(b),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Self::Integer(i)
                } else if let Some(f) = n.as_f64() {
                    Self::Float(f)
                } else {
                    Self::Float(0.0) // fallback
                }
            }
            serde_json::Value::String(s) => Self::String(s),
            serde_json::Value::Array(arr) => {
                let converted: Vec<JsonData> = arr.into_iter().map(JsonData::from).collect();
                Self::Array(converted)
            }
            serde_json::Value::Object(obj) => {
                let converted: HashMap<String, JsonData> = obj
                    .into_iter()
                    .map(|(k, v)| (k, JsonData::from(v)))
                    .collect();
                Self::Object(converted)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_data_creation() {
        assert_eq!(JsonData::null(), JsonData::Null);
        assert_eq!(JsonData::bool(true), JsonData::Bool(true));
        assert_eq!(JsonData::float(42.0).unwrap(), JsonData::Float(42.0));
        assert_eq!(
            JsonData::string("hello"),
            JsonData::String("hello".to_string())
        );
    }

    #[test]
    fn test_json_data_type_checks() {
        assert!(JsonData::null().is_null());
        assert!(JsonData::bool(true).is_bool());
        assert!(JsonData::float(42.0).unwrap().is_number());
        assert!(JsonData::string("hello").is_string());
        assert!(JsonData::array(vec![]).is_array());
        assert!(JsonData::object(HashMap::new()).is_object());
    }

    #[test]
    fn test_json_data_conversions() {
        assert_eq!(JsonData::bool(true).as_bool(), Some(true));
        assert_eq!(JsonData::float(42.0).unwrap().as_f64(), Some(42.0));
        assert_eq!(JsonData::integer(42).as_i64(), Some(42));
        assert_eq!(JsonData::string("hello").as_str(), Some("hello"));
    }

    #[test]
    fn test_path_operations() {
        let mut data = JsonData::object(HashMap::new());

        // Set nested path
        assert!(data.set_path("user.name", JsonData::string("John")));
        assert!(data.set_path("user.age", JsonData::integer(30)));

        // Get nested path
        assert_eq!(data.get_path("user.name").unwrap().as_str(), Some("John"));
        assert_eq!(data.get_path("user.age").unwrap().as_i64(), Some(30));

        // Non-existent path
        assert!(data.get_path("user.email").is_none());
    }

    #[test]
    fn test_memory_size() {
        let data = JsonData::object(
            [
                ("name".to_string(), JsonData::string("John")),
                ("age".to_string(), JsonData::integer(30)),
            ]
            .into_iter()
            .collect(),
        );

        assert!(data.memory_size() > 0);
    }

    #[test]
    fn test_display() {
        let data = JsonData::object(
            [
                ("name".to_string(), JsonData::string("John")),
                ("active".to_string(), JsonData::bool(true)),
            ]
            .into_iter()
            .collect(),
        );

        let display = format!("{data}");
        assert!(display.contains("name"));
        assert!(display.contains("John"));
    }
}