1package rpc
2
3import (
4 "bufio"
5 "bytes"
6 "encoding/binary"
7 "errors"
8 "io"
9)
10
11func WriteBytes(w io.Writer, buf []byte) (int, error) {
12 out := bytes.NewBuffer(nil)
13 binary.Write(out, binary.BigEndian, int64(len(buf)))
14 out.Write(buf)
15 return w.Write(out.Bytes())
16}
17
18func ReadBytes(r io.Reader) ([]byte, error) {
19 // To compatible with UDP connection, use bufio reader here to avoid lost conent.
20 rd := bufio.NewReader(r)
21
22 var length int64
23 if err := binary.Read(rd, binary.BigEndian, &length); err != nil {
24 return nil, err
25 }
26 buffer := make([]byte, length)
27 n, err := io.ReadFull(rd, buffer)
28 if err != nil {
29 return nil, err
30 }
31 if int64(n) != length {
32 return nil, errors.New("invalid length")
33 }
34 return buffer, nil
35}
36