github.com/ipld/go-ipld-prime@v0.21.0/traversal/selector/exploreIndex.go (about)

     1  package selector
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/ipld/go-ipld-prime/datamodel"
     7  )
     8  
     9  // ExploreIndex traverses a specific index in a list, and applies a next
    10  // selector to the reached node.
    11  type ExploreIndex struct {
    12  	next     Selector                 // selector for element we're interested in
    13  	interest [1]datamodel.PathSegment // index of element we're interested in
    14  }
    15  
    16  // Interests for ExploreIndex is just the index specified by the selector node
    17  func (s ExploreIndex) Interests() []datamodel.PathSegment {
    18  	return s.interest[:]
    19  }
    20  
    21  // Explore returns the node's selector if
    22  // the path matches the index for this selector or nil if not
    23  func (s ExploreIndex) Explore(n datamodel.Node, p datamodel.PathSegment) (Selector, error) {
    24  	if n.Kind() != datamodel.Kind_List {
    25  		return nil, nil
    26  	}
    27  	expectedIndex, expectedErr := p.Index()
    28  	actualIndex, actualErr := s.interest[0].Index()
    29  	if expectedErr != nil || actualErr != nil || expectedIndex != actualIndex {
    30  		return nil, nil
    31  	}
    32  	return s.next, nil
    33  }
    34  
    35  // Decide always returns false because this is not a matcher
    36  func (s ExploreIndex) Decide(n datamodel.Node) bool {
    37  	return false
    38  }
    39  
    40  // Match always returns false because this is not a matcher
    41  func (s ExploreIndex) Match(node datamodel.Node) (datamodel.Node, error) {
    42  	return nil, nil
    43  }
    44  
    45  // ParseExploreIndex assembles a Selector
    46  // from a ExploreIndex selector node
    47  func (pc ParseContext) ParseExploreIndex(n datamodel.Node) (Selector, error) {
    48  	if n.Kind() != datamodel.Kind_Map {
    49  		return nil, fmt.Errorf("selector spec parse rejected: selector body must be a map")
    50  	}
    51  	indexNode, err := n.LookupByString(SelectorKey_Index)
    52  	if err != nil {
    53  		return nil, fmt.Errorf("selector spec parse rejected: index field must be present in ExploreIndex selector")
    54  	}
    55  	indexValue, err := indexNode.AsInt()
    56  	if err != nil {
    57  		return nil, fmt.Errorf("selector spec parse rejected: index field must be a number in ExploreIndex selector")
    58  	}
    59  	next, err := n.LookupByString(SelectorKey_Next)
    60  	if err != nil {
    61  		return nil, fmt.Errorf("selector spec parse rejected: next field must be present in ExploreIndex selector")
    62  	}
    63  	selector, err := pc.ParseSelector(next)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	return ExploreIndex{selector, [1]datamodel.PathSegment{datamodel.PathSegmentOfInt(indexValue)}}, nil
    68  }