github.com/MontFerret/ferret@v0.18.0/pkg/runtime/values/binary.go (about) 1 package values 2 3 import ( 4 "hash/fnv" 5 "io" 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 Binary []byte 14 15 func NewBinary(values []byte) Binary { 16 return Binary(values) 17 } 18 19 func NewBinaryFrom(stream io.Reader) (Binary, error) { 20 values, err := io.ReadAll(stream) 21 22 if err != nil { 23 return nil, err 24 } 25 26 return values, nil 27 } 28 29 func (b Binary) MarshalJSON() ([]byte, error) { 30 return jettison.MarshalOpts([]byte(b), 31 jettison.NoStringEscaping(), 32 jettison.NoCompact(), 33 ) 34 } 35 36 func (b Binary) Type() core.Type { 37 return types.Binary 38 } 39 40 func (b Binary) String() string { 41 return string(b) 42 } 43 44 func (b Binary) Compare(other core.Value) int64 { 45 if other.Type() == types.Binary { 46 // TODO: Lame comparison, need to think more about it 47 b2 := other.(*Binary) 48 49 if b2.Length() == b.Length() { 50 return 0 51 } 52 53 if b.Length() > b2.Length() { 54 return 1 55 } 56 57 return -1 58 } 59 60 return types.Compare(types.Binary, other.Type()) 61 } 62 63 func (b Binary) Unwrap() interface{} { 64 return []byte(b) 65 } 66 67 func (b Binary) Hash() uint64 { 68 h := fnv.New64a() 69 70 h.Write([]byte(b.Type().String())) 71 h.Write([]byte(":")) 72 h.Write(b) 73 74 return h.Sum64() 75 } 76 77 func (b Binary) Copy() core.Value { 78 c := make([]byte, len(b)) 79 80 copy(c, b) 81 82 return NewBinary(c) 83 } 84 85 func (b Binary) Length() Int { 86 return NewInt(len(b)) 87 }