Add Kind checks to findInArray and findKeyInMap

findInArray and findKeyInMap accept any *CandidateNode but produce
wrong results when called on the wrong Kind: findInArray uses stride 1,
correct for SequenceNodes but dangerous on MappingNodes (where
key-value pairs live at even-odd indices); findKeyInMap uses stride 2,
correct for MappingNodes but silently skips elements in SequenceNodes.

Commit b0ba9589 fixed two call sites that passed MappingNodes to
findInArray, but nothing prevents the same mistake from recurring.
Each function now logs a warning and returns -1 on a Kind mismatch,
surfacing misuse in tests and debug output rather than letting it
corrupt results silently.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jan Dubois 2026-04-06 15:38:57 -07:00
parent 3b2423e871
commit 546f52515c

View File

@ -52,7 +52,10 @@ func recurseNodeArrayEqual(lhs *CandidateNode, rhs *CandidateNode) bool {
}
func findInArray(array *CandidateNode, item *CandidateNode) int {
if array.Kind != SequenceNode {
log.Warningf("findInArray called on %v node, expected SequenceNode", array.Tag)
return -1
}
for index := 0; index < len(array.Content); index = index + 1 {
if recursiveNodeEqual(array.Content[index], item) {
return index
@ -62,7 +65,10 @@ func findInArray(array *CandidateNode, item *CandidateNode) int {
}
func findKeyInMap(dataMap *CandidateNode, item *CandidateNode) int {
if dataMap.Kind != MappingNode {
log.Warningf("findKeyInMap called on %v node, expected MappingNode", dataMap.Tag)
return -1
}
for index := 0; index < len(dataMap.Content); index = index + 2 {
if recursiveNodeEqual(dataMap.Content[index], item) {
return index