-
Notifications
You must be signed in to change notification settings - Fork 54
/
accessors.go
81 lines (77 loc) · 1.84 KB
/
accessors.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package evaluator
import (
"math"
"reflect"
)
// Index returns sequence[ix] according to Liquid semantics.
func Index(sequence, ix interface{}) interface{} { // nolint: gocyclo
ref := reflect.ValueOf(sequence)
ixRef := reflect.ValueOf(ix)
if !ref.IsValid() || !ixRef.IsValid() {
return nil
}
switch ref.Kind() {
case reflect.Array, reflect.Slice:
switch ixRef.Kind() {
case reflect.Float32, reflect.Float64:
if n, frac := math.Modf(ixRef.Float()); frac == 0 {
ix = int(n)
ixRef = reflect.ValueOf(ix)
}
}
switch ixRef.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := int(ixRef.Int())
if n < 0 {
n = ref.Len() + n
}
if 0 <= n && n < ref.Len() {
return ToLiquid(ref.Index(n).Interface())
}
}
case reflect.Map:
if ixRef.Type().ConvertibleTo(ref.Type().Key()) {
item := ref.MapIndex(ixRef.Convert(ref.Type().Key()))
if item.IsValid() {
return ToLiquid(item.Interface())
}
}
}
return nil
}
const (
sizeProperty = "size"
firstProperty = "first"
lastProperty = "last"
)
// ObjectProperty object.name according to Liquid semantics.
func ObjectProperty(object interface{}, name string) interface{} { // nolint: gocyclo
ref := reflect.ValueOf(object)
switch ref.Kind() {
case reflect.Array, reflect.Slice:
if ref.Len() == 0 {
return nil
}
switch name {
case firstProperty:
return ToLiquid(ref.Index(0).Interface())
case lastProperty:
return ToLiquid(ref.Index(ref.Len() - 1).Interface())
case sizeProperty:
return ref.Len()
}
case reflect.String:
if name == sizeProperty {
return ref.Len()
}
case reflect.Map:
value := ref.MapIndex(reflect.ValueOf(name))
if value.Kind() != reflect.Invalid {
return ToLiquid(value.Interface())
}
if name == sizeProperty {
return reflect.ValueOf(name).Len()
}
}
return nil
}