1package msgio
2
3import (
4	"encoding/binary"
5	"io"
6)
7
8// NBO is NetworkByteOrder
9var NBO = binary.BigEndian
10
11// WriteLen writes a length to the given writer.
12func WriteLen(w io.Writer, l int) error {
13	ul := uint32(l)
14	return binary.Write(w, NBO, &ul)
15}
16
17// ReadLen reads a length from the given reader.
18// if buf is non-nil, it reuses the buffer. Ex:
19//    l, err := ReadLen(r, nil)
20//    _, err := ReadLen(r, buf)
21func ReadLen(r io.Reader, buf []byte) (int, error) {
22	if len(buf) < 4 {
23		buf = make([]byte, 4)
24	}
25	buf = buf[:4]
26
27	if _, err := io.ReadFull(r, buf); err != nil {
28		return 0, err
29	}
30
31	n := int(NBO.Uint32(buf))
32	return n, nil
33}
34