1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/values/boolean.go

114 lines
1.6 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package values
import (
"encoding/json"
2018-10-05 21:17:22 +02:00
"hash/fnv"
2018-09-18 22:42:38 +02:00
"strings"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
2018-09-18 22:42:38 +02:00
)
type Boolean bool
const (
False = Boolean(false)
True = Boolean(true)
)
2018-09-18 22:42:38 +02:00
func NewBoolean(input bool) Boolean {
return Boolean(input)
}
func ParseBoolean(input interface{}) (Boolean, error) {
b, ok := input.(bool)
if ok {
if b {
return True, nil
}
return False, nil
}
s, ok := input.(string)
if ok {
s := strings.ToLower(s)
if s == "true" {
return True, nil
}
if s == "false" {
return False, nil
}
}
2018-10-28 07:45:26 +02:00
return False, core.Error(core.ErrInvalidType, "expected 'bool'")
2018-09-18 22:42:38 +02:00
}
func MustParseBoolean(input interface{}) Boolean {
2018-09-18 22:42:38 +02:00
res, err := ParseBoolean(input)
if err != nil {
panic(err)
}
return res
}
func (t Boolean) MarshalJSON() ([]byte, error) {
return json.Marshal(bool(t))
}
func (t Boolean) Type() core.Type {
return types.Boolean
2018-09-18 22:42:38 +02:00
}
func (t Boolean) String() string {
if t {
return "true"
}
return "false"
}
func (t Boolean) Compare(other core.Value) int64 {
2018-09-18 22:42:38 +02:00
raw := bool(t)
if types.Boolean.Equals(other.Type()) {
2018-09-18 22:42:38 +02:00
i := other.Unwrap().(bool)
if raw == i {
return 0
}
if raw == false && i == true {
return -1
}
return +1
}
return types.Compare(types.Boolean, other.Type())
2018-09-18 22:42:38 +02:00
}
func (t Boolean) Unwrap() interface{} {
return bool(t)
}
2018-10-05 21:17:22 +02:00
func (t Boolean) Hash() uint64 {
h := fnv.New64a()
2018-09-18 22:42:38 +02:00
2018-10-05 21:17:22 +02:00
h.Write([]byte(t.Type().String()))
h.Write([]byte(":"))
h.Write([]byte(t.String()))
2018-09-18 22:42:38 +02:00
2018-10-05 21:17:22 +02:00
return h.Sum64()
2018-09-18 22:42:38 +02:00
}
2018-09-27 17:53:26 +02:00
func (t Boolean) Copy() core.Value {
2018-09-27 17:53:26 +02:00
return t
}