2019-07-03 17:39:07 +00:00
|
|
|
package cborrpc
|
|
|
|
|
|
|
|
import (
|
2019-08-29 15:43:45 +00:00
|
|
|
"encoding/hex"
|
2019-07-03 17:39:07 +00:00
|
|
|
"io"
|
|
|
|
|
|
|
|
cbor "github.com/ipfs/go-ipld-cbor"
|
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
|
|
|
}
|