exploreIndex.go 1.98 KB
Newer Older
1 2 3 4 5
package selector

import (
	"fmt"

tavit ohanian's avatar
tavit ohanian committed
6
	ld "gitlab.dms3.io/ld/go-ld-prime"
7 8 9 10 11
)

// ExploreIndex traverses a specific index in a list, and applies a next
// selector to the reached node.
type ExploreIndex struct {
tavit ohanian's avatar
tavit ohanian committed
12 13
	next     Selector          // selector for element we're interested in
	interest [1]ld.PathSegment // index of element we're interested in
14 15 16
}

// Interests for ExploreIndex is just the index specified by the selector node
tavit ohanian's avatar
tavit ohanian committed
17
func (s ExploreIndex) Interests() []ld.PathSegment {
18
	return s.interest[:]
19 20 21
}

// Explore returns the node's selector if
Bryan White's avatar
Bryan White committed
22
// the path matches the index for this selector or nil if not
tavit ohanian's avatar
tavit ohanian committed
23 24
func (s ExploreIndex) Explore(n ld.Node, p ld.PathSegment) Selector {
	if n.Kind() != ld.Kind_List {
25 26
		return nil
	}
27 28
	expectedIndex, expectedErr := p.Index()
	actualIndex, actualErr := s.interest[0].Index()
29 30
	if expectedErr != nil || actualErr != nil || expectedIndex != actualIndex {
		return nil
31
	}
32
	return s.next
33 34 35
}

// Decide always returns false because this is not a matcher
tavit ohanian's avatar
tavit ohanian committed
36
func (s ExploreIndex) Decide(n ld.Node) bool {
37 38 39 40 41
	return false
}

// ParseExploreIndex assembles a Selector
// from a ExploreIndex selector node
tavit ohanian's avatar
tavit ohanian committed
42 43
func (pc ParseContext) ParseExploreIndex(n ld.Node) (Selector, error) {
	if n.Kind() != ld.Kind_Map {
44 45
		return nil, fmt.Errorf("selector spec parse rejected: selector body must be a map")
	}
46
	indexNode, err := n.LookupByString(SelectorKey_Index)
47 48
	if err != nil {
		return nil, fmt.Errorf("selector spec parse rejected: index field must be present in ExploreIndex selector")
49 50 51
	}
	indexValue, err := indexNode.AsInt()
	if err != nil {
52
		return nil, fmt.Errorf("selector spec parse rejected: index field must be a number in ExploreIndex selector")
53
	}
54
	next, err := n.LookupByString(SelectorKey_Next)
55 56 57
	if err != nil {
		return nil, fmt.Errorf("selector spec parse rejected: next field must be present in ExploreIndex selector")
	}
58
	selector, err := pc.ParseSelector(next)
59 60 61
	if err != nil {
		return nil, err
	}
tavit ohanian's avatar
tavit ohanian committed
62
	return ExploreIndex{selector, [1]ld.PathSegment{ld.PathSegmentOfInt(indexValue)}}, nil
63
}