2021-06-20 23:57:41 +08:00
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
func WriteBytes(w io.Writer, buf []byte) (int, error) {
|
|
|
|
out := bytes.NewBuffer(nil)
|
2022-08-29 01:02:53 +08:00
|
|
|
if err := binary.Write(out, binary.BigEndian, int64(len(buf))); err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2021-06-20 23:57:41 +08:00
|
|
|
out.Write(buf)
|
|
|
|
return w.Write(out.Bytes())
|
|
|
|
}
|
|
|
|
|
|
|
|
func ReadBytes(r io.Reader) ([]byte, error) {
|
|
|
|
var length int64
|
2021-06-21 19:27:26 +08:00
|
|
|
if err := binary.Read(r, binary.BigEndian, &length); err != nil {
|
2021-06-20 23:57:41 +08:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
buffer := make([]byte, length)
|
2021-06-21 19:27:26 +08:00
|
|
|
n, err := io.ReadFull(r, buffer)
|
2021-06-20 23:57:41 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if int64(n) != length {
|
|
|
|
return nil, errors.New("invalid length")
|
|
|
|
}
|
|
|
|
return buffer, nil
|
|
|
|
}
|