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
|
package segments
import (
"fmt"
"strconv"
"strings"
)
type Slice struct {
startIdx int
endIdx int
}
func ParseSliceSegment(s string) (YamlPathSegment, error) {
idxs := strings.Split(s[1:len(s)-1], ":")
start, err := strconv.Atoi(idxs[0])
if err != nil {
return nil, fmt.Errorf("part '%s' is not an index into an array. %w", s, err)
}
end, err := strconv.Atoi(idxs[1])
if err != nil {
return nil, fmt.Errorf("part '%s' is not an index into an array. %w", s, err)
}
if start > end {
return nil, fmt.Errorf("cannot take slice with reversed indexes '%s'", s)
}
return &Slice{
startIdx: start,
endIdx: end,
}, nil
}
func (s *Slice) NavigateMap(m map[string]interface{}) (interface{}, error) {
return nil, fmt.Errorf("cannot slice map")
}
func (s *Slice) NavigateArray(l []interface{}) (interface{}, error) {
if s.startIdx >= len(l) {
return nil, fmt.Errorf("start slice index out of bounds '%d' for array length '%d'", s.startIdx, len(l))
}
if s.endIdx > len(l) {
return nil, fmt.Errorf("end slice index out of bounds '%d' for array length '%d'", s.endIdx, len(l))
}
slice := []interface{}{}
for i := s.startIdx; i < s.endIdx; i++ {
slice = append(slice, l[i])
}
return slice, nil
}
|