openusd 0.6.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Asset resolution framework.
//!
//! USD layers reference external assets through asset paths — the `@...@` syntax in
//! `.usda` files. These paths appear in sublayers, references, payloads, and asset-valued
//! attributes. An asset path is a logical identifier that may be relative, absolute, or
//! use package-relative notation (`Model.usdz[Geom.usd]`).
//!
//! This module resolves those logical paths to physical locations that can be opened
//! and read. It corresponds to the C++ Ar (Asset Resolution) module:
//! <https://openusd.org/dev/api/ar_page_front.html>
//!
//! The [`Resolver`] trait defines the resolution interface. The [`DefaultResolver`]
//! provides a filesystem-based implementation that searches configurable directories
//! for matching files. Custom resolvers can map asset paths to databases, cloud storage,
//! or other backends.
//!
//! # Example
//!
//! ```no_run
//! use openusd::ar::{DefaultResolver, Resolver};
//!
//! let resolver = DefaultResolver::new();
//! if let Some(resolved) = resolver.resolve("model.usda") {
//!     let mut asset = resolver.open_asset(&resolved).unwrap();
//!     let data = asset.read_all().unwrap();
//! }
//! ```

use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::io::{self, Read, Seek};
use std::ops::Deref;
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;

/// A resolved asset path representing the physical location of an asset.
///
/// This is a newtype around a [`PathBuf`] that distinguishes resolved paths
/// from unresolved asset path strings. An empty resolved path indicates
/// that the asset could not be found.
///
/// Implements [`Deref<Target = Path>`] for transparent access to [`Path`] methods.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ResolvedPath(PathBuf);

impl ResolvedPath {
    /// Creates a new resolved path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self(path.into())
    }

    /// Returns `true` if the resolved path is empty (resolution failed).
    pub fn is_empty(&self) -> bool {
        self.0.as_os_str().is_empty()
    }

    /// The file extension (without the leading dot), lowercased, or `""` when
    /// there is none or it is not valid UTF-8. Lowercased so a caller can match a
    /// format case-insensitively — `resolved.extension() == "usdz"` — the way the
    /// format registry's `find_by_extension` does, without juggling `OsStr`.
    pub(crate) fn extension(&self) -> String {
        // For a package-relative path (`pkg.usdz[inner/layer.usd]`) the format is
        // the innermost packaged layer's extension, not the literal trailing
        // chars (`.usd]`), so inspect the inner path rather than `self.0`.
        let s = self.0.to_string_lossy();
        let inner = is_package_relative_path(&s)
            .then(|| split_package_relative_path_inner(&s))
            .flatten()
            .map(|(_, inner)| inner);
        let path = inner.as_deref().map(Path::new).unwrap_or(self.0.as_path());
        path.extension()
            .and_then(|ext| ext.to_str())
            .map(str::to_ascii_lowercase)
            .unwrap_or_default()
    }
}

impl Deref for ResolvedPath {
    type Target = Path;

    fn deref(&self) -> &Path {
        &self.0
    }
}

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

impl AsRef<Path> for ResolvedPath {
    fn as_ref(&self) -> &Path {
        self
    }
}

/// Metadata about a resolved asset.
#[derive(Debug, Default, Clone)]
pub struct AssetInfo {
    /// Version of the asset, if known.
    pub version: String,
    /// Display name for the asset.
    pub asset_name: String,
    /// Repository path, if the asset is managed by a version control system.
    pub repo_path: String,
    /// Additional resolver-specific metadata.
    pub resolver_info: HashMap<String, String>,
}

/// Readable asset handle returned by [`Resolver::open_asset`].
///
/// This trait abstracts over the underlying storage mechanism (filesystem,
/// in-memory buffer, archive entry, etc.) and provides random-access reading.
pub trait Asset: Read + Seek + Send {
    /// Returns the total size of the asset in bytes.
    fn size(&self) -> io::Result<u64>;

    /// Reads the entire asset into a byte buffer.
    fn read_all(&mut self) -> io::Result<Vec<u8>> {
        let size = self.size()? as usize;
        let mut buf = Vec::with_capacity(size);
        self.read_to_end(&mut buf)?;
        Ok(buf)
    }
}

impl Asset for fs::File {
    fn size(&self) -> io::Result<u64> {
        self.metadata().map(|m| m.len())
    }
}

impl Asset for io::Cursor<Vec<u8>> {
    fn size(&self) -> io::Result<u64> {
        Ok(self.get_ref().len() as u64)
    }
}

/// Interface for resolving asset paths to physical locations.
///
/// Implementations of this trait map logical asset paths (as authored in USD
/// layers) to resolved paths that can be opened and read. The default
/// implementation, [`DefaultResolver`], performs filesystem-based resolution
/// with configurable search paths.
///
/// # Correspondence
///
/// This trait corresponds to `ArResolver` in the C++ USD API:
/// <https://openusd.org/dev/api/class_ar_resolver.html>
pub trait Resolver {
    /// Canonicalizes an asset path into a stable identifier.
    ///
    /// The `anchor` path, if provided, is used to resolve relative paths.
    /// Two asset paths that refer to the same asset must produce the same identifier.
    fn create_identifier(&self, asset_path: &str, anchor: Option<&ResolvedPath>) -> String;

    /// Resolves an asset path to a physical location.
    ///
    /// Returns [`Some`] with the resolved path if the asset exists,
    /// or [`None`] if the asset cannot be found.
    fn resolve(&self, asset_path: &str) -> Option<ResolvedPath>;

    /// Resolves an asset path for creating a new asset.
    ///
    /// Unlike [`resolve`](Resolver::resolve), the asset need not exist yet.
    fn resolve_for_new_asset(&self, asset_path: &str) -> Option<ResolvedPath>;

    /// Opens a resolved asset for reading.
    fn open_asset(&self, resolved_path: &ResolvedPath) -> io::Result<Box<dyn Asset>>;

    /// Returns the file extension of the given asset path (without the leading dot).
    fn get_extension<'a>(&self, asset_path: &'a str) -> &'a str {
        Path::new(asset_path)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default()
    }

    /// Returns metadata about a resolved asset.
    fn get_asset_info(&self, _asset_path: &str, _resolved_path: &ResolvedPath) -> AssetInfo {
        AssetInfo::default()
    }

    /// Returns the modification timestamp of a resolved asset.
    fn get_modification_timestamp(&self, _asset_path: &str, resolved_path: &ResolvedPath) -> Option<SystemTime> {
        fs::metadata(&**resolved_path).and_then(|m| m.modified()).ok()
    }

    /// A stable token identifying this resolver's configuration, used as the
    /// resolver component of a composed stack's
    /// [`LayerStackIdentifier`](crate::pcp::LayerStackIdentifier).
    ///
    /// Two resolvers that resolve every asset path identically must return the
    /// same token, and two that may resolve some path differently must return
    /// different tokens — so two stages opened under different resolver
    /// configurations are distinguished (the cross-stage edit-target guard).
    ///
    /// The base trait reports an empty token, meaning "indistinguishable from
    /// any other unconfigured resolver". Any implementation whose resolution can
    /// differ from another's — a different backend, or configuration such as
    /// search paths, a base URL, or a repository revision — must override this
    /// to render that distinguishing identity; otherwise it collides with the
    /// empty default and the guard treats the two as the same composition input.
    /// It is read once per stage, so computing it on demand is fine.
    fn identity(&self) -> String {
        String::new()
    }
}

/// Default filesystem-based asset resolver.
///
/// Resolves asset paths by searching the filesystem using a configurable
/// list of search directories. Resolution proceeds in order:
///
/// 1. If the path is absolute and the file exists, return it directly.
/// 2. Search the resolver's configured search directories.
/// 3. Search relative to the current working directory.
///
/// # Correspondence
///
/// This corresponds to `ArDefaultResolver` in the C++ USD API:
/// <https://openusd.org/dev/api/class_ar_default_resolver.html>
pub struct DefaultResolver {
    search_paths: Vec<PathBuf>,
}

impl DefaultResolver {
    /// Creates a new default resolver with no search paths.
    pub fn new() -> Self {
        Self {
            search_paths: Vec::new(),
        }
    }

    /// Creates a new default resolver with the given search paths.
    ///
    /// Each path is canonicalized to a stable spelling — relative paths are
    /// anchored to the current working directory and lexical noise (`.`
    /// components, redundant and trailing separators) is collapsed — so that
    /// directories named equivalently resolve, and render via
    /// [`identity`](Self::identity), identically.
    pub fn with_search_paths(paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
        let search_paths = paths.into_iter().map(|p| normalize_search_path(p.into())).collect();
        Self { search_paths }
    }

    /// Searches for an asset by trying the path against the resolver's search
    /// directories, then the current working directory.
    fn resolve_with_search_paths(&self, asset_path: &str) -> Option<ResolvedPath> {
        let rel_path = Path::new(asset_path);

        // If the path is absolute, just check existence.
        if rel_path.is_absolute() {
            return if rel_path.exists() {
                Some(ResolvedPath::new(rel_path.canonicalize().ok()?))
            } else {
                None
            };
        }

        for dir in &self.search_paths {
            let candidate = dir.join(rel_path);
            if candidate.exists() {
                return Some(ResolvedPath::new(candidate.canonicalize().ok()?));
            }
        }

        // Try relative to the current working directory.
        if let Ok(cwd) = std::env::current_dir() {
            let candidate = cwd.join(rel_path);
            if candidate.exists() {
                return Some(ResolvedPath::new(candidate.canonicalize().ok()?));
            }
        }

        None
    }
}

impl Default for DefaultResolver {
    fn default() -> Self {
        Self::new()
    }
}

impl Resolver for DefaultResolver {
    fn create_identifier(&self, asset_path: &str, anchor: Option<&ResolvedPath>) -> String {
        if asset_path.is_empty() {
            return String::new();
        }

        // An already package-relative asset path (`pkg.usdz[inner]`): anchor its
        // outer package path like any other path (so a relative `pkg.usdz` is
        // resolved against the anchor), then nest the inner packaged path back
        // inside the anchored package.
        if is_package_relative_path(asset_path) {
            if let Some((package, inner)) = split_package_relative_path_outer(asset_path) {
                let anchored = self.create_identifier(&package, anchor);
                return nest_packaged_path(&anchored, &inner);
            }
            return asset_path.to_string();
        }

        let path = Path::new(asset_path);

        // Absolute paths are their own identifier.
        if path.is_absolute() {
            return canonical_identifier(path.to_path_buf());
        }

        // Anchor relative paths.
        if let Some(anchor) = anchor {
            let anchor_str = anchor.to_string_lossy();
            // Anchor lives inside a package (`pkg.usdz[inner/layer.usd]`): keep
            // the reference inside the package, relative to the inner layer's
            // directory → `pkg.usdz[inner/asset.usd]`.
            if is_package_relative_path(&anchor_str) {
                if let Some((package, inner)) = split_package_relative_path_inner(&anchor_str) {
                    let inner_dir = inner.rsplit_once('/').map(|(dir, _)| dir).unwrap_or("");
                    let joined = join_packaged_path(inner_dir, asset_path);
                    return nest_packaged_path(&package, &joined);
                }
            }
            // Anchor IS a package file (`foo.usdz`): a relative reference from
            // the package's root layer is package-relative → `foo.usdz[asset]`.
            if anchor_str.to_ascii_lowercase().ends_with(".usdz") {
                let joined = join_packaged_path("", asset_path);
                return join_package_relative_path(&anchor_str, &joined);
            }
            if let Some(dir) = anchor.parent() {
                return canonical_identifier(dir.join(path));
            }
        }

        // Without an anchor, resolve relative to the current working directory so
        // every identifier is stable and absolute (matching canonicalized dependencies).
        if let Ok(cwd) = std::env::current_dir() {
            return canonical_identifier(cwd.join(path));
        }

        asset_path.to_string()
    }

    fn resolve(&self, asset_path: &str) -> Option<ResolvedPath> {
        if asset_path.is_empty() {
            return None;
        }

        // A package-relative path (`pkg.usdz[inner]`) resolves its outer package
        // as a plain file, then reattaches the inner packaged path. The inner
        // entry must actually exist in the archive: a path to a missing entry is
        // unresolved, not merely unreadable, so the caller reports it as such
        // rather than as a malformed layer.
        if is_package_relative_path(asset_path) {
            let (package, inner) = split_package_relative_path_outer(asset_path)?;
            let resolved_package = self.resolve_with_search_paths(&package)?;
            if !package_contains(&resolved_package, &inner) {
                return None;
            }
            let package_str = resolved_package.to_string_lossy();
            return Some(ResolvedPath::new(join_package_relative_path(&package_str, &inner)));
        }

        self.resolve_with_search_paths(asset_path)
    }

    fn resolve_for_new_asset(&self, asset_path: &str) -> Option<ResolvedPath> {
        if asset_path.is_empty() {
            return None;
        }

        let path = Path::new(asset_path);

        if path.is_absolute() {
            return Some(ResolvedPath::new(path));
        }

        // Resolve relative to the current working directory.
        std::env::current_dir()
            .ok()
            .map(|cwd| ResolvedPath::new(cwd.join(path)))
    }

    /// Renders the canonicalized search paths as the resolver's identity token,
    /// so two `DefaultResolver`s with different search roots key distinct stacks.
    ///
    /// Each path is rendered via [`Debug`](std::fmt::Debug), which escapes
    /// losslessly — including newlines and non-UTF-8 bytes that
    /// [`to_string_lossy`](std::path::Path::to_string_lossy) would flatten — and
    /// wraps each segment in quotes. The concatenation is therefore injective:
    /// distinct path lists never collapse to the same token.
    fn identity(&self) -> String {
        self.search_paths.iter().map(|p| format!("{p:?}")).collect()
    }

    fn open_asset(&self, resolved_path: &ResolvedPath) -> io::Result<Box<dyn Asset>> {
        let path_str = resolved_path.to_str().unwrap_or_default();

        // Handle package-relative paths by extracting from the archive.
        if is_package_relative_path(path_str) {
            let (package, inner) = split_package_relative_path_outer(path_str).ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("invalid package-relative path: {}", resolved_path),
                )
            })?;

            let mut archive = open_package_archive(Path::new(&package))?;
            let mut entry = archive.by_name(&inner).map_err(io::Error::other)?;

            let mut buffer = Vec::new();
            entry.read_to_end(&mut buffer)?;

            return Ok(Box::new(io::Cursor::new(buffer)));
        }

        let file = fs::File::open(&**resolved_path)?;
        Ok(Box::new(file))
    }
}

/// Lexically normalizes `path`: drops `.` components (including a leading one)
/// and collapses redundant separators, with no filesystem access. `..` is
/// preserved, since collapsing it lexically could change meaning across
/// symlinks. Matches the normalization C++ `TfNormPath` performs.
fn lexically_normalize(path: &Path) -> PathBuf {
    path.components().filter(|c| !matches!(c, Component::CurDir)).collect()
}

/// Renders `path` as a stable layer identifier: its filesystem-canonical
/// spelling when it resolves (collapsing equivalent spellings and following
/// symlinks), else the [`lexically_normalize`]d path.
///
/// `.` components are dropped either way, matching C++
/// [`ArResolver::CreateIdentifier`], which normalizes via `TfNormPath` without
/// touching the filesystem. So a target authored `./foo.usda` produces the same
/// identifier as `foo.usda` even when it is an in-memory layer that cannot be
/// canonicalized, and the registry's exact-identifier lookup still finds it.
///
/// [`ArResolver::CreateIdentifier`]: https://openusd.org/release/api/class_ar_resolver.html
fn canonical_identifier(path: PathBuf) -> String {
    path.canonicalize()
        .unwrap_or_else(|_| lexically_normalize(&path))
        .to_string_lossy()
        .into_owned()
}

/// Canonicalizes a search-path spelling for [`DefaultResolver`].
///
/// Relative paths are anchored to the current working directory, then lexical
/// noise is collapsed (see [`lexically_normalize`]). The result resolves
/// candidates identically to the input while giving equivalent directories one
/// canonical rendering.
fn normalize_search_path(path: PathBuf) -> PathBuf {
    let path = if path.is_relative() {
        std::env::current_dir().unwrap_or_default().join(path)
    } else {
        path
    };
    lexically_normalize(&path)
}

/// Opens `package` as a ZIP archive, reading only its central directory.
///
/// Shared by [`DefaultResolver::open_asset`], which then extracts an entry, and
/// [`package_contains`], which only checks an entry's presence.
fn open_package_archive(package: &Path) -> io::Result<zip::ZipArchive<fs::File>> {
    let file = fs::File::open(package)?;
    zip::ZipArchive::new(file).map_err(io::Error::other)
}

/// Whether `inner` should be treated as present in the package at `package`.
///
/// Reading only the archive's central directory — not its entry data — a
/// readable archive that genuinely lacks a flat entry reports it absent, so
/// [`DefaultResolver::resolve`] reports a missing inner layer as unresolved
/// rather than as a layer that exists but cannot be read. Two cases are
/// deliberately treated as present so the eventual open surfaces the accurate
/// error instead of a misleading "missing asset": a `package` that cannot be
/// opened right now (a transient IO error or a corrupt archive — distinct from
/// a genuinely absent entry), and a nested packaged path
/// (`inner.usdz[deep.usd]`, which is not a flat entry name and whose support is
/// decided when the inner package opens).
///
/// TODO(perf): opens the package's central directory on every package-relative
/// resolve (per in-package arc, re-run each composition pass). Cache parsed
/// central directories keyed by resolved package path so repeated probes and
/// the eventual load share one parse.
fn package_contains(package: &Path, inner: &str) -> bool {
    if is_package_relative_path(inner) {
        return true;
    }
    match open_package_archive(package) {
        Ok(mut archive) => archive.by_name(inner).is_ok(),
        Err(_) => true,
    }
}

// ---------------------------------------------------------------------------
// Package-relative path utilities
// ---------------------------------------------------------------------------

/// Returns `true` if the path contains a package-relative component (bracket syntax).
///
/// Package-relative paths reference assets inside package files (e.g., USDZ archives)
/// using bracket notation: `Model.usdz[Geom.usd]`.
pub fn is_package_relative_path(path: &str) -> bool {
    path.contains('[') && path.ends_with(']')
}

/// Splits a package-relative path at the outermost bracket.
///
/// Returns the outer package path and the inner packaged path.
///
/// # Examples
///
/// ```
/// use openusd::ar::split_package_relative_path_outer;
///
/// let result = split_package_relative_path_outer("Model.usdz[Geom.usd]");
/// assert_eq!(result, Some(("Model.usdz".to_string(), "Geom.usd".to_string())));
///
/// let nested = split_package_relative_path_outer("Outer.usdz[Inner.usdz[Geom.usd]]");
/// assert_eq!(nested, Some(("Outer.usdz".to_string(), "Inner.usdz[Geom.usd]".to_string())));
/// ```
pub fn split_package_relative_path_outer(path: &str) -> Option<(String, String)> {
    let bracket = path.find('[')?;
    if !path.ends_with(']') {
        return None;
    }
    let outer = &path[..bracket];
    let inner = &path[bracket + 1..path.len() - 1];
    Some((outer.to_string(), inner.to_string()))
}

/// Splits a package-relative path at the innermost bracket.
///
/// Returns the outer package path (potentially still package-relative) and the
/// innermost asset path.
///
/// # Examples
///
/// ```
/// use openusd::ar::split_package_relative_path_inner;
///
/// let result = split_package_relative_path_inner("Model.usdz[Geom.usd]");
/// assert_eq!(result, Some(("Model.usdz".to_string(), "Geom.usd".to_string())));
///
/// let nested = split_package_relative_path_inner("Outer.usdz[Inner.usdz[Geom.usd]]");
/// assert_eq!(nested, Some(("Outer.usdz[Inner.usdz]".to_string(), "Geom.usd".to_string())));
/// ```
pub fn split_package_relative_path_inner(path: &str) -> Option<(String, String)> {
    if !path.ends_with(']') {
        return None;
    }

    // Find the last '[' — this starts the innermost packaged path.
    let open = path.rfind('[')?;

    // Find the matching ']' — the first ']' after the last '['.
    let close = path[open..].find(']').map(|i| open + i)?;

    let inner = &path[open + 1..close];
    // Outer is everything before the '[' plus everything after the ']'.
    let mut outer = path[..open].to_string();
    let remainder = &path[close + 1..];
    outer.push_str(remainder);

    Some((outer, inner.to_string()))
}

/// Joins a package path and an inner path into a package-relative path.
///
/// # Examples
///
/// ```
/// use openusd::ar::join_package_relative_path;
///
/// assert_eq!(
///     join_package_relative_path("Model.usdz", "Geom.usd"),
///     "Model.usdz[Geom.usd]"
/// );
/// ```
pub fn join_package_relative_path(package_path: &str, packaged_path: &str) -> String {
    format!("{}[{}]", package_path, packaged_path)
}

/// Joins a package-internal directory with a relative reference authored inside
/// it, producing the entry name a packaged layer is stored under.
///
/// Package entry names are always `/`-separated and carry no filesystem
/// semantics, so unlike [`lexically_normalize`] this collapses `..` as well as
/// `.` and always emits forward slashes — the spelling
/// [`zip::ZipArchive::by_name`] matches against. `dir` is the directory of the
/// anchoring inner layer (empty for a layer at the package root); `rel` is the
/// relative path it references. A `..` that would climb above the package root
/// is dropped, since there is nothing above it inside the archive.
fn join_packaged_path(dir: &str, rel: &str) -> String {
    let mut components: Vec<&str> = dir.split('/').filter(|c| !c.is_empty()).collect();
    for part in rel.split(['/', '\\']) {
        match part {
            "" | "." => {}
            ".." => {
                components.pop();
            }
            other => components.push(other),
        }
    }
    components.join("/")
}

/// Attaches `leaf` as a packaged layer inside the deepest package of `base`.
///
/// For a plain `base` this is [`join_package_relative_path`]. When `base` is
/// itself package-relative — its outer package holds a nested package — the
/// `leaf` is nested into the innermost bracket so the result stays well-formed
/// (`pkg[inner[leaf]]`) rather than gaining a stray second bracket pair
/// (`pkg[inner][leaf]`), which no split or resolve step can interpret.
fn nest_packaged_path(base: &str, leaf: &str) -> String {
    match split_package_relative_path_outer(base) {
        Some((package, inner)) => join_package_relative_path(&package, &nest_packaged_path(&inner, leaf)),
        None => join_package_relative_path(base, leaf),
    }
}

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

    // -----------------------------------------------------------------------
    // ResolvedPath
    // -----------------------------------------------------------------------

    #[test]
    fn resolved_path_empty() {
        let p = ResolvedPath::new("");
        assert!(p.is_empty());
    }

    #[test]
    fn resolved_path_display() {
        let p = ResolvedPath::new("/tmp/model.usda");
        assert_eq!(format!("{}", p), "/tmp/model.usda");
        assert!(!p.is_empty());
    }

    #[test]
    fn resolved_path_deref() {
        let p = ResolvedPath::new("some/path/model.usda");
        // The string-typed `extension` accessor, then a Path method via Deref.
        assert_eq!(p.extension(), "usda");
        assert_eq!(p.file_name().unwrap(), "model.usda");
        // The extension is lowercased for case-insensitive format matching.
        assert_eq!(ResolvedPath::new("x/Model.USDZ").extension(), "usdz");
        assert_eq!(ResolvedPath::new("x/noext").extension(), "");
    }

    #[test]
    fn resolver_identity_renders_search_paths() {
        // No search paths → empty identity (no distinguishing configuration).
        assert!(DefaultResolver::new().identity().is_empty());

        // Same search paths → equal identity; different → distinct.
        let a = DefaultResolver::with_search_paths(["/show/assets", "/lib"]);
        let b = DefaultResolver::with_search_paths(["/show/assets", "/lib"]);
        let c = DefaultResolver::with_search_paths(["/other"]);
        assert_eq!(a.identity(), b.identity());
        assert_ne!(a.identity(), c.identity());

        // Equivalent spellings canonicalize to one identity: a relative path
        // anchors to the cwd, and `.` lexical noise is collapsed.
        let cwd = std::env::current_dir().unwrap();
        let rel = DefaultResolver::with_search_paths(["assets"]);
        let abs = DefaultResolver::with_search_paths([cwd.join("assets")]);
        assert_eq!(rel.identity(), abs.identity());

        let plain = DefaultResolver::with_search_paths([cwd.join("lib")]);
        let noisy = DefaultResolver::with_search_paths([cwd.join("lib").join(".")]);
        assert_eq!(plain.identity(), noisy.identity());

        // The encoding is injective: a single path embedding a separator must
        // not collide with two distinct paths. `["a\nb"]` and `["a", "b"]` key
        // different stacks, keeping the cross-stage guard sound.
        let embedded = DefaultResolver::with_search_paths([cwd.join("a\nb")]);
        let split = DefaultResolver::with_search_paths([cwd.join("a"), cwd.join("b")]);
        assert_ne!(embedded.identity(), split.identity());
    }

    // -----------------------------------------------------------------------
    // Package-relative paths
    // -----------------------------------------------------------------------

    #[test]
    fn is_package_relative() {
        assert!(is_package_relative_path("Model.usdz[Geom.usd]"));
        assert!(is_package_relative_path("A.usdz[B.usdz[C.usd]]"));
        assert!(!is_package_relative_path("Model.usdz"));
        assert!(!is_package_relative_path("Model.usdz["));
        assert!(!is_package_relative_path("plain/path.usd"));
    }

    #[test]
    fn split_outer_simple() {
        let result = split_package_relative_path_outer("Model.usdz[Geom.usd]");
        assert_eq!(result, Some(("Model.usdz".to_string(), "Geom.usd".to_string())));
    }

    #[test]
    fn split_outer_nested() {
        let result = split_package_relative_path_outer("Outer.usdz[Inner.usdz[Geom.usd]]");
        assert_eq!(
            result,
            Some(("Outer.usdz".to_string(), "Inner.usdz[Geom.usd]".to_string()))
        );
    }

    #[test]
    fn split_inner_simple() {
        let result = split_package_relative_path_inner("Model.usdz[Geom.usd]");
        assert_eq!(result, Some(("Model.usdz".to_string(), "Geom.usd".to_string())));
    }

    #[test]
    fn split_inner_nested() {
        let result = split_package_relative_path_inner("Outer.usdz[Inner.usdz[Geom.usd]]");
        assert_eq!(
            result,
            Some(("Outer.usdz[Inner.usdz]".to_string(), "Geom.usd".to_string()))
        );
    }

    #[test]
    fn split_invalid() {
        assert_eq!(split_package_relative_path_outer("no_brackets"), None);
        assert_eq!(split_package_relative_path_inner("no_brackets"), None);
        assert_eq!(split_package_relative_path_outer("open[only"), None);
        assert_eq!(split_package_relative_path_inner("open[only"), None);
    }

    #[test]
    fn join_package_path() {
        assert_eq!(
            join_package_relative_path("Model.usdz", "Geom.usd"),
            "Model.usdz[Geom.usd]"
        );
    }

    // -----------------------------------------------------------------------
    // DefaultResolver
    // -----------------------------------------------------------------------

    #[test]
    fn resolver_empty_path() {
        let resolver = DefaultResolver::new();
        assert_eq!(resolver.resolve(""), None);
        assert_eq!(resolver.create_identifier("", None), "");
    }

    #[test]
    fn resolver_extension() {
        let resolver = DefaultResolver::new();
        assert_eq!(resolver.get_extension("model.usda"), "usda");
        assert_eq!(resolver.get_extension("archive.usdz"), "usdz");
        assert_eq!(resolver.get_extension("no_extension"), "");
        assert_eq!(resolver.get_extension("path/to/file.usdc"), "usdc");
    }

    #[test]
    fn resolver_resolve_existing_file() {
        // Use Cargo.toml as a known existing file.
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let resolver = DefaultResolver::with_search_paths([&manifest]);

        let resolved = resolver.resolve("Cargo.toml");
        assert!(resolved.is_some());
        let resolved = resolved.unwrap();
        assert!(!resolved.is_empty());
        assert!(resolved.exists());
    }

    #[test]
    fn resolver_resolve_nonexistent() {
        let resolver = DefaultResolver::new();
        assert_eq!(resolver.resolve("nonexistent_file_12345.usda"), None);
    }

    #[test]
    fn resolver_resolve_absolute_path() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let abs_path = Path::new(&manifest).join("Cargo.toml");

        let resolver = DefaultResolver::new();
        let resolved = resolver.resolve(abs_path.to_str().unwrap());
        assert!(resolved.is_some());
    }

    #[test]
    fn resolver_create_identifier_absolute() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let abs_path = Path::new(&manifest).join("Cargo.toml");
        let abs_str = abs_path.to_str().unwrap();

        let resolver = DefaultResolver::new();
        let id = resolver.create_identifier(abs_str, None);
        assert!(!id.is_empty());
    }

    #[test]
    fn resolver_create_identifier_anchored() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let anchor = ResolvedPath::new(PathBuf::from(&manifest).join("src/lib.rs"));

        let resolver = DefaultResolver::new();
        let id = resolver.create_identifier("ar.rs", Some(&anchor));
        // The identifier should resolve relative to the anchor's directory.
        assert!(id.contains("ar.rs"));
    }

    /// A `.`-relative asset path that cannot be canonicalized (the target does
    /// not exist on disk, as for an in-memory layer) still has its `.` components
    /// dropped lexically, matching C++ `ArResolver::CreateIdentifier`'s
    /// `TfNormPath`. So `./sub.usda` and `sub.usda` yield the same identifier and
    /// the registry's exact-identifier lookup resolves an in-memory sublayer.
    #[test]
    fn resolver_create_identifier_dot_relative() {
        let resolver = DefaultResolver::new();
        let anchor = ResolvedPath::new(PathBuf::from("root.usda"));
        assert_eq!(
            resolver.create_identifier("./sub.usda", Some(&anchor)),
            resolver.create_identifier("sub.usda", Some(&anchor)),
            "a leading `./` normalizes away when the target cannot be canonicalized"
        );
    }

    #[test]
    fn resolver_create_identifier_package_relative_anchored() {
        let resolver = DefaultResolver::new();
        let anchor = ResolvedPath::new(PathBuf::from("/scene/root.usda"));
        // A package-relative target anchors its outer package path to the
        // anchor's directory (not returned verbatim), then reattaches the inner
        // packaged path — the same identifier as anchoring the bare package.
        assert_eq!(
            resolver.create_identifier("model.usdz[geom.usd]", Some(&anchor)),
            join_package_relative_path(&resolver.create_identifier("model.usdz", Some(&anchor)), "geom.usd"),
        );
    }

    #[test]
    fn packaged_path_join_forward_slash() {
        // Package entry names are `/`-separated regardless of host platform, and
        // `.`/`..` collapse since there is no filesystem inside the archive.
        assert_eq!(join_packaged_path("geom", "mesh.usd"), "geom/mesh.usd");
        assert_eq!(join_packaged_path("geom", "./mesh.usd"), "geom/mesh.usd");
        assert_eq!(join_packaged_path("geom", "../tex/foo.usda"), "tex/foo.usda");
        assert_eq!(join_packaged_path("", "geom/mesh.usd"), "geom/mesh.usd");
        // A back-slash spelling is normalized to forward slashes.
        assert_eq!(join_packaged_path("geom", r"sub\mesh.usd"), "geom/sub/mesh.usd");
    }

    #[test]
    fn in_package_anchor_crosses_dirs() {
        let resolver = DefaultResolver::new();
        // A reference authored in a sub-directory layer that climbs out of it
        // resolves to a forward-slash, `..`-collapsed entry name — the spelling
        // the archive is keyed by — not a host path with separators or `..`.
        let anchor = ResolvedPath::new(PathBuf::from("pkg.usdz[geom/scene.usda]"));
        assert_eq!(
            resolver.create_identifier("../tex/foo.usda", Some(&anchor)),
            "pkg.usdz[tex/foo.usda]",
        );
    }

    #[test]
    fn nest_packaged_well_formed() {
        // A leaf nests into the innermost package rather than appending a stray
        // second bracket pair.
        assert_eq!(nest_packaged_path("pkg.usdz", "geom.usd"), "pkg.usdz[geom.usd]");
        assert_eq!(
            nest_packaged_path("pkg.usdz[model.usdz]", "geom.usd"),
            "pkg.usdz[model.usdz[geom.usd]]",
        );
        assert_eq!(
            nest_packaged_path("a.usdz[b.usdz[c.usdz]]", "d.usd"),
            "a.usdz[b.usdz[c.usdz[d.usd]]]",
        );
    }

    #[test]
    fn resolver_open_asset() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let resolver = DefaultResolver::with_search_paths([&manifest]);

        let resolved = resolver.resolve("Cargo.toml").unwrap();
        let mut asset = resolver.open_asset(&resolved).unwrap();

        let size = asset.size().unwrap();
        assert!(size > 0);

        let data = asset.read_all().unwrap();
        assert_eq!(data.len() as u64, size);
        assert!(String::from_utf8_lossy(&data).contains("[package]"));
    }

    #[test]
    fn resolver_modification_timestamp() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let resolver = DefaultResolver::with_search_paths([&manifest]);

        let resolved = resolver.resolve("Cargo.toml").unwrap();
        let ts = resolver.get_modification_timestamp("Cargo.toml", &resolved);
        assert!(ts.is_some());
    }

    #[test]
    fn resolve_for_new_asset_relative() {
        let resolver = DefaultResolver::new();
        let resolved = resolver.resolve_for_new_asset("new_file.usda");
        assert!(resolved.is_some());
        let resolved = resolved.unwrap();
        assert!(resolved.is_absolute());
    }

    // -----------------------------------------------------------------------
    // Asset impls
    // -----------------------------------------------------------------------

    #[test]
    fn cursor_asset_read() {
        let data = b"hello world".to_vec();
        let mut asset = io::Cursor::new(data.clone());

        assert_eq!(asset.size().unwrap(), 11);

        let result = asset.read_all().unwrap();
        assert_eq!(result, data);
    }

    #[test]
    fn cursor_asset_seek() {
        let data = b"hello world".to_vec();
        let mut asset = io::Cursor::new(data);

        asset.seek(io::SeekFrom::Start(6)).unwrap();
        let mut buf = [0u8; 5];
        asset.read_exact(&mut buf).unwrap();
        assert_eq!(&buf, b"world");
    }
}