openusd 0.3.0

Rust native USD library
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::{fmt, result, str::FromStr};

use anyhow::{bail, ensure, Result};

#[inline]
pub fn path(str: impl AsRef<str>) -> Result<Path> {
    let path = str.as_ref();
    Path::new(path)
}

/// `SdfPath` implementation.
///
/// # Syntax
/// - Two separators are used between parts of a path. A slash ("/")
///   following an identifier is used to introduce a namespace child.
/// - A period (".") following an identifier is used to introduce a property.
/// - A property may also have several non-sequential colons (':') in its name
///   to provide a rudimentary namespace within properties but may not end or
///   begin with a colon.
/// - Brackets ("[" and "]") are used to indicate relationship target paths for
///   relational attributes.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Path {
    path: String,
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.path)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Path {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.path.serialize(serializer)
    }
}

impl FromStr for Path {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> result::Result<Path, Self::Err> {
        Ok(Path { path: s.to_string() })
    }
}

impl Path {
    pub fn new(path: &str) -> Result<Self> {
        Path::from_str(path)
    }

    #[inline]
    pub fn abs_root() -> Path {
        Path::from_str_unchecked("/")
    }

    fn from_str_unchecked(path: &str) -> Path {
        Path { path: path.to_string() }
    }

    #[inline]
    pub fn is_abs(&self) -> bool {
        self.path.starts_with('/')
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.path.is_empty()
    }

    pub fn append_property(&self, property: &str) -> Result<Path> {
        // TODO: Validate property name more carefully here.
        ensure!(!property.is_empty(), "Property name cannot be empty");
        ensure!(!self.is_property_path(), "Cannot append property to property path");
        ensure!(property != ".", "Property name cannot be '.'");

        let mut new_path = self.path.clone();
        new_path.push('.');
        new_path.push_str(property);

        Ok(Path { path: new_path })
    }

    pub fn append_path(&self, path: impl Into<Path>) -> Result<Path> {
        let append: Path = path.into();

        if self.is_abs() && append.is_abs() {
            bail!("Cannot append absolute path to absolute path");
        }

        ensure!(!self.is_property_path(), "Cannot append path to property path");

        if append.as_str() == "." {
            return Ok(self.clone());
        }

        // If base is slash only.
        // "/" + "foo/bar" => "/foo/bar"
        let combined = if self.path.as_str() == "/" {
            format!("/{}", append.path)
        } else {
            format!("{}/{}", self.path, append.path)
        };

        Ok(Path { path: combined })
    }

    pub fn is_property_path(&self) -> bool {
        let pos = match self.path.rfind('.') {
            Some(index) => index,
            // No dot, not a property path
            None => return false,
        };

        // Make sure the dot is preceded by a prim name character (not a variant
        // selection closing brace or another dot) and followed by a valid
        // property name. Property names may contain alphanumerics, underscores,
        // and colons (for namespaced properties like `primvars:displayColor`).
        let tail = &self.path[pos + 1..];
        !tail.is_empty() && tail.chars().all(|c| c.is_alphanumeric() || c == '_' || c == ':')
    }

    pub fn prim_path(&self) -> Path {
        // Split at last slash.
        // "/A/B/C.foo[target].bar:baz" will become "/A/B" and "C.foo[target].bar:baz"
        let Some((before, after)) = self.path.rsplit_once('/') else {
            return self.clone();
        };

        // For cases like ../.foo[target].bar, just return ..
        if after.starts_with('.') {
            return Path::from_str_unchecked(before);
        }

        // "/A/B/C{set=sel}" => "/A/B/C"
        if after.ends_with('}') {
            if let Some(pos) = after.find('{') {
                let sz = before.len() + pos + 1;
                return Path::from_str_unchecked(&self.path[..sz]);
            }
        }

        let first_dot = match after.find('.') {
            Some(dot) => dot,
            // No dots found, so we have a prim path
            None => return self.clone(),
        };

        // Return everything up to the first dot
        let sz = before.len() + first_dot + 1;
        Path::from_str_unchecked(&self.path[..sz])
    }

    /// Returns the parent path, or `None` for the pseudo-root `/` and empty paths.
    ///
    /// ```text
    /// "/A/B/C" -> Some("/A/B")
    /// "/A"     -> Some("/")
    /// "/"      -> None
    /// ""       -> None
    /// ```
    pub fn parent(&self) -> Option<Path> {
        if self.path.is_empty() || self.path == "/" {
            return None;
        }
        match self.path.rsplit_once('/') {
            Some(("", _)) => Some(Path::abs_root()),
            Some((before, _)) => Some(Path::from_str_unchecked(before)),
            None => None,
        }
    }

    /// Returns the final component name, or `None` for the pseudo-root and empty paths.
    ///
    /// ```text
    /// "/A/B/C" -> Some("C")
    /// "/A"     -> Some("A")
    /// "/"      -> None
    /// ""       -> None
    /// ```
    pub fn name(&self) -> Option<&str> {
        if self.path.is_empty() || self.path == "/" {
            return None;
        }
        match self.path.rsplit_once('/') {
            Some((_, after)) => Some(after),
            None => Some(&self.path),
        }
    }

    /// Replaces a prefix path with a new prefix, used for namespace remapping
    /// during composition (e.g. references and inherits).
    ///
    /// Returns `None` if `self` does not start with `old_prefix`.
    ///
    /// ```text
    /// "/Ref/Child".replace_prefix("/Ref", "/MyPrim") -> Some("/MyPrim/Child")
    /// "/Ref".replace_prefix("/Ref", "/MyPrim")       -> Some("/MyPrim")
    /// "/Other".replace_prefix("/Ref", "/MyPrim")     -> None
    /// ```
    pub fn replace_prefix(&self, old_prefix: &Path, new_prefix: &Path) -> Option<Path> {
        let old = old_prefix.as_str();
        let me = self.as_str();

        if me == old {
            return Some(new_prefix.clone());
        }

        // Must start with old_prefix followed by '/' or '{' (variant segment).
        let suffix = me.strip_prefix(old)?;
        // The absolute root "/" is a prefix of all absolute paths; after
        // stripping it the remainder won't start with '/' (e.g. "Foo/Bar").
        if old != "/" && !suffix.starts_with('/') && !suffix.starts_with('{') {
            return None;
        }
        // Ensure a separator between new prefix and suffix for non-root.
        if old == "/" && !suffix.is_empty() {
            let new = new_prefix.as_str();
            if new == "/" {
                return Some(Path::from_str_unchecked(&format!("/{suffix}")));
            }
            return Some(Path::from_str_unchecked(&format!("{new}/{suffix}")));
        }

        let new = new_prefix.as_str();
        if new == "/" {
            Some(Path::from_str_unchecked(suffix))
        } else {
            Some(Path::from_str_unchecked(&format!("{new}{suffix}")))
        }
    }

    /// Appends a variant selection to a prim path, producing a path like
    /// `/MyPrim{variantSet=selection}`.
    pub fn append_variant_selection(&self, set: &str, selection: &str) -> Path {
        Path::from_str_unchecked(&format!("{}{{{set}={selection}}}", self.path))
    }

    /// Appends a raw variant segment (e.g. `{set=sel}`) directly to this path.
    ///
    /// Unlike [`append_path`], no `/` separator is inserted — variant segments
    /// attach directly to the prim path to produce canonical forms like
    /// `/Prim{set=sel}`.
    pub fn append_variant_segment(&self, segment: &str) -> Path {
        Path::from_str_unchecked(&format!("{}{segment}", self.path))
    }

    /// Resolve a relative path against this path as anchor.
    ///
    /// Absolute paths are returned as-is. Relative segments (`..`) walk up
    /// from the anchor's prim path.
    ///
    /// Equivalent to C++ `SdfPath::MakeAbsolutePath`.
    ///
    /// ```text
    /// "/A/B".make_absolute("../C")   -> "/A/C"
    /// "/A/B".make_absolute("C/D")    -> "/A/B/C/D"
    /// "/A".make_absolute("/X")       -> "/X"
    /// ```
    pub fn make_absolute(&self, target: &Path) -> Path {
        let s = target.as_str();
        if s.starts_with('/') {
            return target.clone();
        }

        // Walk up from the anchor for each leading `..` segment.
        let base = self.prim_path();
        let mut anchor = base.as_str();
        let mut rest = s;
        while let Some(tail) = rest.strip_prefix("..") {
            // Strip one parent from anchor.
            anchor = anchor
                .rsplit_once('/')
                .map_or("/", |(pre, _)| if pre.is_empty() { "/" } else { pre });
            rest = tail.strip_prefix('/').unwrap_or(tail);
        }

        if rest.is_empty() {
            return Path::from_str_unchecked(anchor);
        }
        if anchor == "/" {
            return Path::from_str_unchecked(&format!("/{rest}"));
        }
        Path::from_str_unchecked(&format!("{anchor}/{rest}"))
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Validate identifier
    ///
    /// Rules are:
    /// - Must be 1 char len
    /// - Must start with a letter or underscore
    /// - Must contain only letters, underscores, and numbers.
    pub fn is_valid_identifier(name: &str) -> bool {
        if name.is_empty() {
            return false;
        }

        name.chars()
            .enumerate()
            .all(|(i, c)| c == '_' || if i == 0 { c.is_alphabetic() } else { c.is_alphanumeric() })
    }

    pub fn is_valid_namespace_identifier(name: &str) -> bool {
        name.split(&[':', '.']).all(Self::is_valid_identifier)
    }
}

impl From<&Path> for Path {
    fn from(p: &Path) -> Self {
        p.clone()
    }
}

impl From<&str> for Path {
    fn from(s: &str) -> Self {
        Path { path: s.to_string() }
    }
}

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

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

    #[test]
    fn test_append_property() {
        let base = Path::new("/foo").unwrap();

        assert_eq!(base.append_property("prop").unwrap().as_str(), "/foo.prop");
        assert_eq!(
            base.append_property("prop:foo:bar").unwrap().as_str(),
            "/foo.prop:foo:bar"
        );

        let base = Path::new("/foo.prop").unwrap();
        assert!(base.append_property("prop2").is_err());
        assert!(base.append_property("prop2:foo:bar").is_err());
    }

    #[test]
    fn test_append_path() -> Result<()> {
        assert_eq!(Path::new("/prim")?.append_path(".")?.as_str(), "/prim");

        assert_eq!(Path::new("/")?.append_path("foo/bar.attr")?.as_str(), "/foo/bar.attr");
        assert_eq!(
            Path::new("/")?.append_path("foo/bar.attr:argle:bargle")?.as_str(),
            "/foo/bar.attr:argle:bargle"
        );

        assert_eq!(Path::new("/foo")?.append_path("bar.attr")?.as_str(), "/foo/bar.attr");
        assert_eq!(
            Path::new("/foo")?.append_path("bar.attr:argle:bargle")?.as_str(),
            "/foo/bar.attr:argle:bargle"
        );
        assert_eq!(
            Path::new("/foo")?.append_path("bar.rel[/target].attr")?.as_str(),
            "/foo/bar.rel[/target].attr"
        );

        assert_eq!(
            Path::new("/foo")?
                .append_path("bar.rel[/target].attr:argle:bargle")?
                .as_str(),
            "/foo/bar.rel[/target].attr:argle:bargle"
        );

        assert_eq!(
            Path::new("/foo")?.append_path("bar.attr[/target.attr]")?.as_str(),
            "/foo/bar.attr[/target.attr]"
        );

        assert_eq!(
            Path::new("/foo")?
                .append_path("bar.attr[/target.attr:argle:bargle]")?
                .as_str(),
            "/foo/bar.attr[/target.attr:argle:bargle]"
        );

        assert_eq!(
            Path::new("/foo")?.append_path("bar.attr.mapper[/target].arg")?.as_str(),
            "/foo/bar.attr.mapper[/target].arg"
        );

        Ok(())
    }

    #[test]
    fn test_append_invalid_path() -> Result<()> {
        assert!(Path::new("/prim")?.append_path("/abs").is_err());
        assert!(Path::new("/prim.attr")?.append_path("abs").is_err());

        Ok(())
    }

    #[test]
    fn test_prim_path() {
        #[rustfmt::skip]
        let cases = [
            ("/A/B/C", "/A/B/C"),

            ("/A/B{set=sel}C", "/A/B{set=sel}C"),
            ("/A/B/C{set=sel}", "/A/B/C"),

            ("/A/B/C.foo", "/A/B/C"),
            ("/A/B/C.foo:bar:baz", "/A/B/C"),

            ("/A/B/C.foo[target].bar", "/A/B/C"),
            ("/A/B/C.foo[target].bar:baz", "/A/B/C"),

            ("A/B/C.foo[target].bar", "A/B/C"),
            ("A/B/C.foo[target].bar:baz", "A/B/C"),

            ("../C.foo", "../C"),
            ("../C.foo:bar:baz", "../C"),

            ("../.foo[target].bar", ".."),
            ("../.foo[target].bar:baz", ".."),
        ];

        for (path, expected) in cases {
            assert_eq!(
                Path::new(path).unwrap().prim_path().as_str(),
                expected,
                "Unable to parse: {path}",
            );
        }
    }

    #[test]
    fn test_is_property() {
        #[rustfmt::skip]
        let cases = [
            ("/Foo/Bar.baz", true),
            ("Foo", false),
            ("Foo/Bar", false),
            ("Foo.bar", true),
            ("Foo/Bar.bar", true),
            (".bar", true),
            ("/Some/Kinda/Long/Path/Just/To/Make/Sure", false),
            ("Some/Kinda/Long/Path/Just/To/Make/Sure.property", true),
            ("../Some/Kinda/Long/Path/Just/To/Make/Sure", false),
            ("../../Some/Kinda/Long/Path/Just/To/Make/Sure.property", true),
            ("/Foo/Bar.baz[targ].boom", true),
            ("Foo.bar[targ].boom", true),
            (".bar[targ].boom", true),
            ("Foo.bar[targ.attr].boom", true),
            ("/A/B/C.rel3[/Blah].attr3", true),
            ("A/B.rel2[/A/B/C.rel3[/Blah].attr3].attr2", true),
            ("/A.rel1[/A/B.rel2[/A/B/C.rel3[/Blah].attr3].attr2].attr1", true),
        ];

        for (path, expected) in cases {
            assert_eq!(Path::new(path).unwrap().is_property_path(), expected);
        }
    }

    #[test]
    fn test_path_cmp() {
        // Less then
        assert!(Path::from_str("aaa").unwrap() < Path::from_str("aab").unwrap());
        assert!(Path::from_str("/").unwrap() < Path::from_str("/a").unwrap());

        // Greater then
        assert!(Path::from_str("aab").unwrap() > Path::from_str("aaa").unwrap());

        // Less equal
        assert!(Path::from_str("aaa").unwrap() <= Path::from_str("aab").unwrap());
        assert!(Path::from_str("aaa").unwrap() <= Path::from_str("aaa").unwrap());

        // Greater equal
        assert!(Path::from_str("aab").unwrap() >= Path::from_str("aaa").unwrap());
        assert!(Path::from_str("aaa").unwrap() >= Path::from_str("aaa").unwrap());
    }

    #[test]
    fn test_parent() {
        #[rustfmt::skip]
        let cases: &[(&str, Option<&str>)] = &[
            ("/A/B/C", Some("/A/B")),
            ("/A/B",   Some("/A")),
            ("/A",     Some("/")),
            ("/",      None),
            ("",       None),
        ];

        for &(path, expected) in cases {
            assert_eq!(
                Path::new(path).unwrap().parent().as_ref().map(|p| p.as_str()),
                expected,
                "parent of {path:?}",
            );
        }
    }

    #[test]
    fn test_name() {
        #[rustfmt::skip]
        let cases: &[(&str, Option<&str>)] = &[
            ("/A/B/C", Some("C")),
            ("/A/B",   Some("B")),
            ("/A",     Some("A")),
            ("/",      None),
            ("",       None),
            ("Foo",    Some("Foo")),
        ];

        for &(path, expected) in cases {
            assert_eq!(Path::new(path).unwrap().name(), expected, "name of {path:?}",);
        }
    }

    #[test]
    fn test_replace_prefix() {
        let p = |s| Path::new(s).unwrap();

        // Exact match.
        assert_eq!(
            p("/Ref").replace_prefix(&p("/Ref"), &p("/MyPrim")).unwrap().as_str(),
            "/MyPrim"
        );

        // Child remapping.
        assert_eq!(
            p("/Ref/Child")
                .replace_prefix(&p("/Ref"), &p("/MyPrim"))
                .unwrap()
                .as_str(),
            "/MyPrim/Child"
        );

        // Deeper nesting.
        assert_eq!(
            p("/Ref/A/B").replace_prefix(&p("/Ref"), &p("/X")).unwrap().as_str(),
            "/X/A/B"
        );

        // Remap to root.
        assert_eq!(
            p("/Ref/Child").replace_prefix(&p("/Ref"), &p("/")).unwrap().as_str(),
            "/Child"
        );

        // No match.
        assert!(p("/Other").replace_prefix(&p("/Ref"), &p("/MyPrim")).is_none());

        // Partial name overlap must not match (e.g. /RefExtra should not match /Ref).
        assert!(p("/RefExtra").replace_prefix(&p("/Ref"), &p("/X")).is_none());
    }

    #[test]
    fn test_append_variant_selection() {
        let p = Path::new("/MyPrim").unwrap();
        assert_eq!(
            p.append_variant_selection("model", "high").as_str(),
            "/MyPrim{model=high}"
        );

        let root = Path::new("/").unwrap();
        assert_eq!(root.append_variant_selection("s", "v").as_str(), "/{s=v}");
    }

    #[test]
    fn validate_identifier() {
        // Valid identifiers
        assert!(Path::is_valid_identifier("_"));
        assert!(Path::is_valid_identifier("x"));
        assert!(Path::is_valid_identifier("_1"));
        assert!(Path::is_valid_identifier("a1"));
        assert!(Path::is_valid_identifier("test"));
        assert!(Path::is_valid_identifier("_test"));
        assert!(Path::is_valid_identifier("test123"));
        assert!(Path::is_valid_identifier("Test"));
        assert!(Path::is_valid_identifier("teST"));
        assert!(Path::is_valid_identifier("TEST"));

        // Invalid ones
        assert!(!Path::is_valid_identifier(""));
        assert!(!Path::is_valid_identifier(" "));
        assert!(!Path::is_valid_identifier("?"));
        assert!(!Path::is_valid_identifier("1"));
        assert!(!Path::is_valid_identifier("x!"));
        assert!(!Path::is_valid_identifier("_abc?"));
        assert!(!Path::is_valid_identifier("_!"));
        assert!(!Path::is_valid_identifier("test "));
        assert!(!Path::is_valid_identifier(" test"));
        assert!(!Path::is_valid_identifier("te st"));
        assert!(!Path::is_valid_identifier("te.st"));
        assert!(!Path::is_valid_identifier("te:st"));
    }

    #[test]
    fn make_absolute() {
        let abs = |anchor, target| Path::from_str_unchecked(anchor).make_absolute(&Path::from_str_unchecked(target));

        assert_eq!(abs("/A/B", "/X/Y").as_str(), "/X/Y");
        assert_eq!(abs("/A/B", "../C").as_str(), "/A/C");
        assert_eq!(abs("/A/B/C", "../../D").as_str(), "/A/D");
        assert_eq!(abs("/A", "../X").as_str(), "/X");
        assert_eq!(abs("/A/B", "..").as_str(), "/A");
        assert_eq!(abs("/A/B", "C/D").as_str(), "/A/B/C/D");
    }

    #[test]
    fn append_variant_segment() {
        let p = |s| Path::from_str_unchecked(s);

        // Variant set and selection attach directly without a slash separator.
        assert_eq!(p("/A").append_variant_segment("{v=sel}").as_str(), "/A{v=sel}");
        assert_eq!(
            p("/A/B").append_variant_segment("{color=red}").as_str(),
            "/A/B{color=red}"
        );
        // Empty selection (variant set path).
        assert_eq!(p("/A").append_variant_segment("{v=}").as_str(), "/A{v=}");
        // Nested variant segments stack.
        assert_eq!(p("/A{v=x}").append_variant_segment("{w=y}").as_str(), "/A{v=x}{w=y}");
    }
}