github.com/MontFerret/ferret@v0.18.0/pkg/runtime/values/boolean.go (about) 1 package values 2 3 import ( 4 "hash/fnv" 5 "strings" 6 7 "github.com/wI2L/jettison" 8 9 "github.com/MontFerret/ferret/pkg/runtime/core" 10 "github.com/MontFerret/ferret/pkg/runtime/values/types" 11 ) 12 13 type Boolean bool 14 15 const ( 16 False = Boolean(false) 17 True = Boolean(true) 18 ) 19 20 func NewBoolean(input bool) Boolean { 21 return Boolean(input) 22 } 23 24 func ParseBoolean(input interface{}) (Boolean, error) { 25 b, ok := input.(bool) 26 27 if ok { 28 if b { 29 return True, nil 30 } 31 32 return False, nil 33 } 34 35 s, ok := input.(string) 36 37 if ok { 38 return Boolean(strings.ToLower(s) == "true"), nil 39 } 40 41 return False, core.Error(core.ErrInvalidType, "expected 'bool'") 42 } 43 44 func MustParseBoolean(input interface{}) Boolean { 45 res, err := ParseBoolean(input) 46 47 if err != nil { 48 panic(err) 49 } 50 51 return res 52 } 53 54 func (t Boolean) MarshalJSON() ([]byte, error) { 55 return jettison.MarshalOpts(bool(t), jettison.NoHTMLEscaping()) 56 } 57 58 func (t Boolean) Type() core.Type { 59 return types.Boolean 60 } 61 62 func (t Boolean) String() string { 63 if t { 64 return "true" 65 } 66 67 return "false" 68 } 69 70 func (t Boolean) Compare(other core.Value) int64 { 71 raw := bool(t) 72 73 if types.Boolean.Equals(other.Type()) { 74 i := other.Unwrap().(bool) 75 76 if raw == i { 77 return 0 78 } 79 80 if !raw && i { 81 return -1 82 } 83 84 return +1 85 } 86 87 return types.Compare(types.Boolean, other.Type()) 88 } 89 90 func (t Boolean) Unwrap() interface{} { 91 return bool(t) 92 } 93 94 func (t Boolean) Hash() uint64 { 95 h := fnv.New64a() 96 97 h.Write([]byte(t.Type().String())) 98 h.Write([]byte(":")) 99 h.Write([]byte(t.String())) 100 101 return h.Sum64() 102 } 103 104 func (t Boolean) Copy() core.Value { 105 return t 106 }