lotus/lib/cborutil/rpc.go

81 lines
1.5 KiB
Go
Raw Normal View History

2019-11-07 14:11:39 +00:00
package cborutil
2019-07-03 17:39:07 +00:00
import (
"bytes"
"encoding/hex"
2019-07-03 17:39:07 +00:00
"io"
"math"
2019-07-03 17:39:07 +00:00
cbor "github.com/ipfs/go-ipld-cbor"
ipld "github.com/ipfs/go-ipld-format"
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
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 {
// 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
}
if Debug {
log.Infof("> %s", hex.EncodeToString(data))
}
2019-07-03 17:39:07 +00:00
_, err = w.Write(data)
return err
}
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
}
func Dump(obj interface{}) ([]byte, error) {
var out bytes.Buffer
if err := WriteCborRPC(&out, obj); err != nil {
return nil, err
}
return out.Bytes(), nil
}
// 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
}