From 3c527d146ed46daef0344041774486f50512dae2 Mon Sep 17 00:00:00 2001 From: Joshua Miller Date: Mon, 13 Jan 2025 12:05:52 -0800 Subject: [PATCH] [sdf] Fix Sdf_Children::Find to return correct value In most cases, Sdf_Children::Find would return the incorrect value of 0 instead the size of _childNames. This would incorrectly index into the first element when a matching element was not found --- pxr/usd/sdf/children.cpp | 9 ++++----- pxr/usd/sdf/testenv/testSdfPrim.py | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/pxr/usd/sdf/children.cpp b/pxr/usd/sdf/children.cpp index 5370056366..4801b706af 100644 --- a/pxr/usd/sdf/children.cpp +++ b/pxr/usd/sdf/children.cpp @@ -86,19 +86,18 @@ size_t Sdf_Children::Find(const KeyType &key) const { if (!TF_VERIFY(IsValid())) { - return 0; + return _childNames.size(); } _UpdateChildNames(); const FieldType expectedKey(_keyPolicy.Canonicalize(key)); - size_t i = 0; - for (i=0; i < _childNames.size(); i++) { + for (size_t i=0; i < _childNames.size(); i++) { if (_childNames[i] == expectedKey) { - break; + return i; } } - return i; + return _childNames.size(); } template diff --git a/pxr/usd/sdf/testenv/testSdfPrim.py b/pxr/usd/sdf/testenv/testSdfPrim.py index d071be5eae..789ebbc276 100644 --- a/pxr/usd/sdf/testenv/testSdfPrim.py +++ b/pxr/usd/sdf/testenv/testSdfPrim.py @@ -79,6 +79,31 @@ def test_NameChildrenInsert(self): print(" previous list {0}".format(prevGroundTruthList)) self.fail("Prim insertion test failed") + def test_NameChildrenFind(self): + layer = Sdf.Layer.CreateAnonymous("test") + rootPrim = Sdf.PrimSpec(layer, 'Root', Sdf.SpecifierDef, 'Scope') + + # find the index of a non-existent prim with no children + index = rootPrim.nameChildren.index('nonexistent') + self.assertEqual(index, -1) + + # insert some child prims to find + for i in range(10): + primName = 'geom{0}'.format(i) + primSpec = Sdf.PrimSpec(layer, primName, Sdf.SpecifierDef, 'Scope') + + rootPrim.nameChildren.insert(i, primSpec) + + # find the index of the prims + for i in range(10): + primName = 'geom{0}'.format(i) + index = rootPrim.nameChildren.index(primName) + self.assertEqual(index, i) + + # find the index of a non-existent prim + index = rootPrim.nameChildren.index('nonexistent') + self.assertEqual(index, -1) + def test_InertSpecRemoval(self): layer = Sdf.Layer.CreateAnonymous()