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
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2018-10-12 17:58:08 +02:00
|
|
|
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
2018-09-18 22:42:38 +02:00
|
|
|
)
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
type Binary []byte
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func NewBinary(values []byte) Binary {
|
|
|
|
return Binary(values)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func NewBinaryFrom(stream io.Reader) (Binary, error) {
|
2018-09-18 22:42:38 +02:00
|
|
|
values, err := ioutil.ReadAll(stream)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
return Binary(values), nil
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal([]byte(b))
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Type() core.Type {
|
2018-09-18 22:42:38 +02:00
|
|
|
return core.BinaryType
|
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) String() string {
|
|
|
|
return string(b)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Compare(other core.Value) int {
|
2018-09-18 22:42:38 +02:00
|
|
|
// TODO: Lame comparison, need to think more about it
|
|
|
|
switch other.Type() {
|
|
|
|
case core.BooleanType:
|
|
|
|
b2 := other.(*Binary)
|
|
|
|
|
|
|
|
if b2.Length() == b.Length() {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
if b.Length() > b2.Length() {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
return -1
|
|
|
|
default:
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Unwrap() interface{} {
|
|
|
|
return []byte(b)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Hash() uint64 {
|
2018-10-05 21:17:22 +02:00
|
|
|
h := fnv.New64a()
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-05 21:17:22 +02:00
|
|
|
h.Write([]byte(b.Type().String()))
|
|
|
|
h.Write([]byte(":"))
|
2018-12-22 06:14:41 +02:00
|
|
|
h.Write(b)
|
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-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Copy() core.Value {
|
|
|
|
c := make([]byte, len(b))
|
2018-09-27 17:53:26 +02:00
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
copy(c, b)
|
2018-09-27 17:53:26 +02:00
|
|
|
|
|
|
|
return NewBinary(c)
|
|
|
|
}
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
func (b Binary) Length() Int {
|
|
|
|
return NewInt(len(b))
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|