domainstack 1.1.1

Write validation once, use everywhere: Rust rules auto-generate JSON Schema + OpenAPI + TypeScript/Zod. WASM browser validation. Axum/Actix/Rocket adapters.
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
492
493
494
495
496
497
498
499
500
use std::sync::Arc;

/// Represents a path to a field in a nested structure.
///
/// Paths are used to identify which field caused a validation error in nested
/// and collection structures. They support dot notation for nested fields and
/// bracket notation for array indices.
///
/// # Examples
///
/// ```
/// use domainstack::Path;
///
/// // Simple field path
/// let path = Path::root().field("email");
/// assert_eq!(path.to_string(), "email");
///
/// // Nested path
/// let path = Path::root().field("user").field("email");
/// assert_eq!(path.to_string(), "user.email");
///
/// // Collection path
/// let path = Path::root().field("items").index(0).field("name");
/// assert_eq!(path.to_string(), "items[0].name");
/// ```
///
/// # Memory Management
///
/// Path uses `Arc<str>` for field names, providing:
/// - **No memory leaks:** Reference counting ensures proper cleanup
/// - **Efficient cloning:** Cloning a path is cheap (just incrementing reference counts)
/// - **Shared ownership:** Multiple errors can reference the same field names
///
/// Field names from compile-time literals (`"email"`) are converted to `Arc<str>`
/// on first use and reference-counted thereafter.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Path(Vec<PathSegment>);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PathSegment {
    Field(Arc<str>),
    Index(usize),
}

impl Path {
    /// Creates an empty root path.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let path = Path::root();
    /// assert_eq!(path.to_string(), "");
    /// ```
    pub fn root() -> Self {
        Self(Vec::new())
    }

    /// Appends a field name to the path.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let path = Path::root().field("email");
    /// assert_eq!(path.to_string(), "email");
    ///
    /// let nested = Path::root().field("user").field("email");
    /// assert_eq!(nested.to_string(), "user.email");
    /// ```
    pub fn field(mut self, name: impl Into<Arc<str>>) -> Self {
        self.0.push(PathSegment::Field(name.into()));
        self
    }

    /// Appends an array index to the path.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let path = Path::root().field("items").index(0);
    /// assert_eq!(path.to_string(), "items[0]");
    ///
    /// let nested = Path::root().field("items").index(0).field("name");
    /// assert_eq!(nested.to_string(), "items[0].name");
    /// ```
    pub fn index(mut self, idx: usize) -> Self {
        self.0.push(PathSegment::Index(idx));
        self
    }

    /// Parses a path from a string representation.
    ///
    /// Uses `Arc<str>` for field names, ensuring proper memory management
    /// without leaks. Field names are reference-counted and cleaned up
    /// when no longer needed.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let path = Path::parse("user.email");
    /// assert_eq!(path, Path::root().field("user").field("email"));
    ///
    /// let with_index = Path::parse("items[0].name");
    /// assert_eq!(with_index, Path::root().field("items").index(0).field("name"));
    /// ```
    pub fn parse(s: &str) -> Self {
        let mut segments = Vec::new();
        let mut current = String::new();

        let chars: Vec<char> = s.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            match chars[i] {
                '.' => {
                    if !current.is_empty() {
                        segments.push(PathSegment::Field(Arc::from(current.as_str())));
                        current.clear();
                    }
                    i += 1;
                }
                '[' => {
                    if !current.is_empty() {
                        segments.push(PathSegment::Field(Arc::from(current.as_str())));
                        current.clear();
                    }

                    i += 1;
                    let mut index_str = String::new();
                    while i < chars.len() && chars[i] != ']' {
                        index_str.push(chars[i]);
                        i += 1;
                    }

                    if let Ok(idx) = index_str.parse::<usize>() {
                        segments.push(PathSegment::Index(idx));
                    }

                    i += 1;
                }
                _ => {
                    current.push(chars[i]);
                    i += 1;
                }
            }
        }

        if !current.is_empty() {
            segments.push(PathSegment::Field(Arc::from(current.as_str())));
        }

        Path(segments)
    }

    /// Returns a slice of the path segments.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::{Path, PathSegment};
    ///
    /// let path = Path::root().field("user").index(0).field("name");
    /// assert_eq!(path.segments().len(), 3);
    /// ```
    pub fn segments(&self) -> &[PathSegment] {
        &self.0
    }

    /// Pushes a field segment to the path.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let mut path = Path::root();
    /// path.push_field("email");
    /// assert_eq!(path.to_string(), "email");
    /// ```
    pub fn push_field(&mut self, name: impl Into<Arc<str>>) {
        self.0.push(PathSegment::Field(name.into()));
    }

    /// Pushes an index segment to the path.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::Path;
    ///
    /// let mut path = Path::root();
    /// path.push_field("items");
    /// path.push_index(0);
    /// assert_eq!(path.to_string(), "items[0]");
    /// ```
    pub fn push_index(&mut self, idx: usize) {
        self.0.push(PathSegment::Index(idx));
    }
}

impl core::fmt::Display for Path {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        for (i, segment) in self.0.iter().enumerate() {
            match segment {
                PathSegment::Field(name) => {
                    if i > 0 {
                        write!(f, ".")?;
                    }
                    write!(f, "{}", name)?;
                }
                PathSegment::Index(idx) => write!(f, "[{}]", idx)?,
            }
        }
        Ok(())
    }
}

impl From<&'static str> for Path {
    fn from(s: &'static str) -> Self {
        Path(vec![PathSegment::Field(Arc::from(s))])
    }
}

impl From<String> for Path {
    fn from(s: String) -> Self {
        Path::parse(&s)
    }
}

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

    #[test]
    fn test_root() {
        let path = Path::root();
        assert!(path.segments().is_empty());
        assert_eq!(path.to_string(), "");
    }

    #[test]
    fn test_field() {
        let path = Path::root().field("email");
        assert_eq!(path.segments().len(), 1);
        assert_eq!(path.to_string(), "email");
    }

    #[test]
    fn test_nested_field() {
        let path = Path::root().field("guest").field("email");
        assert_eq!(path.segments().len(), 2);
        assert_eq!(path.to_string(), "guest.email");
    }

    #[test]
    fn test_index() {
        let path = Path::root().field("guests").index(0);
        assert_eq!(path.segments().len(), 2);
        assert_eq!(path.to_string(), "guests[0]");
    }

    #[test]
    fn test_complex_path() {
        let path = Path::root()
            .field("booking")
            .field("guests")
            .index(0)
            .field("email");
        assert_eq!(path.to_string(), "booking.guests[0].email");
    }

    #[test]
    fn test_from_str() {
        let path = Path::from("email");
        assert_eq!(path.segments().len(), 1);
        assert_eq!(path.to_string(), "email");
    }

    #[test]
    fn test_parse_simple() {
        let path = Path::parse("email");
        assert_eq!(path.to_string(), "email");
    }

    #[test]
    fn test_parse_nested() {
        let path = Path::parse("guest.email");
        assert_eq!(path.to_string(), "guest.email");
    }

    #[test]
    fn test_parse_with_index() {
        let path = Path::parse("guests[0].email");
        assert_eq!(path.to_string(), "guests[0].email");
    }

    #[test]
    fn test_parse_complex() {
        let path = Path::parse("booking.guests[0].email");
        assert_eq!(path.to_string(), "booking.guests[0].email");
    }

    // Tests for push methods
    #[test]
    fn test_push_field_basic() {
        let mut path = Path::root();
        path.push_field("email");
        assert_eq!(path.segments().len(), 1);
        assert_eq!(path.to_string(), "email");
    }

    #[test]
    fn test_push_field_multiple() {
        let mut path = Path::root();
        path.push_field("user");
        path.push_field("profile");
        path.push_field("email");
        assert_eq!(path.segments().len(), 3);
        assert_eq!(path.to_string(), "user.profile.email");
    }

    #[test]
    fn test_push_index_basic() {
        let mut path = Path::root();
        path.push_field("items");
        path.push_index(0);
        assert_eq!(path.segments().len(), 2);
        assert_eq!(path.to_string(), "items[0]");
    }

    #[test]
    fn test_push_index_multiple() {
        let mut path = Path::root();
        path.push_field("matrix");
        path.push_index(0);
        path.push_index(1);
        assert_eq!(path.segments().len(), 3);
        assert_eq!(path.to_string(), "matrix[0][1]");
    }

    #[test]
    fn test_push_field_and_index_mixed() {
        let mut path = Path::root();
        path.push_field("orders");
        path.push_index(5);
        path.push_field("items");
        path.push_index(3);
        path.push_field("sku");
        assert_eq!(path.segments().len(), 5);
        assert_eq!(path.to_string(), "orders[5].items[3].sku");
    }

    #[test]
    fn test_push_with_string() {
        let mut path = Path::root();
        path.push_field(String::from("dynamic_field"));
        assert_eq!(path.to_string(), "dynamic_field");
    }

    // Parse edge cases
    #[test]
    fn test_parse_empty_string() {
        let path = Path::parse("");
        assert!(path.segments().is_empty());
        assert_eq!(path.to_string(), "");
    }

    #[test]
    fn test_parse_leading_dot() {
        let path = Path::parse(".field");
        // Leading dot should be skipped, resulting in just "field"
        assert_eq!(path.to_string(), "field");
    }

    #[test]
    fn test_parse_trailing_dot() {
        let path = Path::parse("field.");
        // Trailing dot is ignored
        assert_eq!(path.to_string(), "field");
    }

    #[test]
    fn test_parse_consecutive_dots() {
        let path = Path::parse("a..b");
        // Empty segments between dots are skipped
        assert_eq!(path.to_string(), "a.b");
    }

    #[test]
    fn test_parse_consecutive_indices() {
        let path = Path::parse("items[0][1][2]");
        assert_eq!(path.segments().len(), 4);
        assert_eq!(path.to_string(), "items[0][1][2]");
    }

    #[test]
    fn test_parse_invalid_index_ignored() {
        let path = Path::parse("items[abc]");
        // Non-numeric index is ignored, only field is captured
        assert_eq!(path.segments().len(), 1);
        assert_eq!(path.to_string(), "items");
    }

    #[test]
    fn test_parse_negative_index_ignored() {
        let path = Path::parse("items[-1]");
        // Negative index can't be parsed as usize, ignored
        assert_eq!(path.segments().len(), 1);
        assert_eq!(path.to_string(), "items");
    }

    #[test]
    fn test_parse_unclosed_bracket() {
        let path = Path::parse("items[0");
        // Unclosed bracket - index still captured
        assert_eq!(path.segments().len(), 2);
        assert_eq!(path.to_string(), "items[0]");
    }

    #[test]
    fn test_parse_deep_nesting() {
        let path = Path::parse("a.b.c.d.e.f.g.h.i.j.k");
        assert_eq!(path.segments().len(), 11);
        assert_eq!(path.to_string(), "a.b.c.d.e.f.g.h.i.j.k");
    }

    #[test]
    fn test_parse_deep_mixed_nesting() {
        let path = Path::parse("a[0].b[1].c[2].d[3].e[4]");
        assert_eq!(path.segments().len(), 10);
        assert_eq!(path.to_string(), "a[0].b[1].c[2].d[3].e[4]");
    }

    #[test]
    fn test_parse_large_index() {
        let path = Path::parse("items[999999]");
        assert_eq!(path.to_string(), "items[999999]");
    }

    // Equality and hashing tests
    #[test]
    fn test_parsed_equals_constructed() {
        let parsed = Path::parse("user.items[0].name");
        let constructed = Path::root()
            .field("user")
            .field("items")
            .index(0)
            .field("name");
        assert_eq!(parsed, constructed);
    }

    #[test]
    fn test_path_hash_consistency() {
        use std::collections::HashMap;

        let path1 = Path::parse("user.email");
        let path2 = Path::root().field("user").field("email");

        let mut map = HashMap::new();
        map.insert(path1.clone(), "value1");

        // Same path constructed differently should access same entry
        assert_eq!(map.get(&path2), Some(&"value1"));
    }

    #[test]
    fn test_clone_independence() {
        let original = Path::root().field("test");
        let mut cloned = original.clone();
        cloned.push_field("extra");

        assert_eq!(original.segments().len(), 1);
        assert_eq!(cloned.segments().len(), 2);
        assert_eq!(original.to_string(), "test");
        assert_eq!(cloned.to_string(), "test.extra");
    }

    #[test]
    fn test_from_string() {
        let path: Path = String::from("user.email").into();
        assert_eq!(path.to_string(), "user.email");
    }

    #[test]
    fn test_segment_types() {
        let path = Path::root().field("items").index(0).field("name");
        let segments = path.segments();

        assert!(matches!(&segments[0], PathSegment::Field(_)));
        assert!(matches!(&segments[1], PathSegment::Index(0)));
        assert!(matches!(&segments[2], PathSegment::Field(_)));
    }
}