2019-11-07 14:11:39 +00:00
|
|
|
package cborutil
|
2019-07-03 17:39:07 +00:00
|
|
|
|
|
|
|
import (
|
2019-10-22 17:34:59 +00:00
|
|
|
"bytes"
|
2019-08-29 15:43:45 +00:00
|
|
|
"encoding/hex"
|
2019-07-03 17:39:07 +00:00
|
|
|
"io"
|
2019-10-22 19:29:05 +00:00
|
|
|
"math"
|
2019-07-03 17:39:07 +00:00
|
|
|
|
|
|
|
cbor "github.com/ipfs/go-ipld-cbor"
|
2019-10-22 19:29:05 +00:00
|
|
|
ipld "github.com/ipfs/go-ipld-format"
|
2019-08-29 15:43:45 +00:00
|
|
|
logging "github.com/ipfs/go-log"
|
2019-08-22 01:29:19 +00:00
|
|
|
cbg "github.com/whyrusleeping/cbor-gen"
|
2019-07-03 17:39:07 +00:00
|
|
|
)
|
2019-07-03 17:41:54 +00:00
|
|
|
|
2019-08-29 15:43:45 +00:00
|
|
|
var log = logging.Logger("cborrrpc")
|
|
|
|
|
|
|
|
const Debug = false
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
if Debug {
|
|
|
|
log.Warn("CBOR-RPC Debugging enabled")
|
|
|
|
}
|
|
|
|
}
|
2019-07-03 17:39:07 +00:00
|
|
|
|
|
|
|
func WriteCborRPC(w io.Writer, obj interface{}) error {
|
2019-08-22 01:29:19 +00:00
|
|
|
if m, ok := obj.(cbg.CBORMarshaler); ok {
|
2019-08-29 15:43:45 +00:00
|
|
|
// TODO: impl debug
|
2019-08-22 01:29:19 +00:00
|
|
|
return m.MarshalCBOR(w)
|
|
|
|
}
|
2019-07-03 17:39:07 +00:00
|
|
|
data, err := cbor.DumpObject(obj)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-29 15:43:45 +00:00
|
|
|
if Debug {
|
|
|
|
log.Infof("> %s", hex.EncodeToString(data))
|
|
|
|
}
|
|
|
|
|
2019-07-03 17:39:07 +00:00
|
|
|
_, err = w.Write(data)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-04 14:47:46 +00:00
|
|
|
func ReadCborRPC(r io.Reader, out interface{}) error {
|
2019-08-22 01:29:19 +00:00
|
|
|
if um, ok := out.(cbg.CBORUnmarshaler); ok {
|
|
|
|
return um.UnmarshalCBOR(r)
|
|
|
|
}
|
2019-07-26 00:49:27 +00:00
|
|
|
return cbor.DecodeReader(r, out)
|
2019-07-03 17:41:54 +00:00
|
|
|
}
|
2019-10-22 17:34:59 +00:00
|
|
|
|
|
|
|
func Dump(obj interface{}) ([]byte, error) {
|
|
|
|
var out bytes.Buffer
|
|
|
|
if err := WriteCborRPC(&out, obj); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return out.Bytes(), nil
|
|
|
|
}
|
2019-10-22 19:29:05 +00:00
|
|
|
|
|
|
|
// TODO: this is a bit ugly, and this package is not exactly the best place
|
|
|
|
func AsIpld(obj interface{}) (ipld.Node, error) {
|
|
|
|
if m, ok := obj.(cbg.CBORMarshaler); ok {
|
|
|
|
b, err := Dump(m)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return cbor.Decode(b, math.MaxUint64, -1)
|
|
|
|
}
|
|
|
|
return cbor.WrapObject(obj, math.MaxUint64, -1)
|
|
|
|
}
|
2019-11-07 13:29:43 +00:00
|
|
|
|
|
|
|
func Equals(a cbg.CBORMarshaler, b cbg.CBORMarshaler) (bool, error) {
|
|
|
|
ab, err := Dump(a)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
bb, err := Dump(b)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return bytes.Equal(ab, bb), nil
|
|
|
|
}
|