1
0
mirror of https://github.com/danog/liquid.git synced 2024-12-02 20:57:47 +01:00
liquid/generics/generics.go

63 lines
1.5 KiB
Go
Raw Normal View History

2017-06-27 16:28:39 +02:00
package generics
import (
"fmt"
"reflect"
)
// GenericError is an error regarding generic conversion.
type GenericError string
func (e GenericError) Error() string { return string(e) }
func genericErrorf(format string, a ...interface{}) error {
return GenericError(fmt.Sprintf(format, a...))
}
2017-06-28 23:18:48 +02:00
// Contains returns a boolean indicating whether array is a sequence that contains item.
func Contains(array interface{}, item interface{}) bool {
ref := reflect.ValueOf(array)
switch ref.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < ref.Len(); i++ {
if ref.Index(i).Interface() == item {
return true
}
}
}
return false
}
// IsEmpty returns a bool indicating whether the value is empty according to Liquid semantics.
2017-06-27 23:54:24 +02:00
func IsEmpty(value interface{}) bool {
if value == nil {
return false
2017-06-27 16:28:39 +02:00
}
2017-06-27 23:54:24 +02:00
r := reflect.ValueOf(value)
switch r.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return r.Len() == 0
case reflect.Bool:
2017-06-29 18:26:04 +02:00
return !r.Bool()
default:
return false
2017-06-27 16:28:39 +02:00
}
}
2017-06-27 22:53:34 +02:00
2017-06-27 23:54:24 +02:00
// IsTrue returns a bool indicating whether the value is true according to Liquid semantics.
func IsTrue(value interface{}) bool {
return value != nil && value != false
}
2017-06-28 20:41:46 +02:00
// Length returns the length of a string or array. In keeping with Liquid semantics,
// and contra Go, it does not return the size of a map.
func Length(value interface{}) int {
ref := reflect.ValueOf(value)
switch ref.Kind() {
2017-06-28 23:18:48 +02:00
case reflect.Array, reflect.Slice, reflect.String:
return ref.Len()
default:
2017-06-28 20:41:46 +02:00
return 0
}
}