-
Notifications
You must be signed in to change notification settings - Fork 8
/
io.go
73 lines (66 loc) · 1.36 KB
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package monte
import (
"encoding/binary"
"errors"
"fmt"
"github.com/lithdew/bytesutil"
"io"
"net"
)
type BufferedConn interface {
net.Conn
Flush() error
}
func Read(dst []byte, r io.Reader) ([]byte, error) {
_, err := io.ReadFull(r, dst[:])
if err != nil {
return nil, err
}
return dst, nil
}
func Write(w io.Writer, buf []byte) error {
n, err := w.Write(buf)
if n != len(buf) {
return io.ErrShortWrite
}
return err
}
func ReadSized(dst []byte, r io.Reader, max int) ([]byte, error) {
dst = bytesutil.ExtendSlice(dst, 4)
_, err := io.ReadFull(r, dst[:])
if err != nil {
return nil, err
}
n := bytesutil.Uint32BE(dst[:])
if int(n) > max {
return nil, fmt.Errorf("max is %d bytes, got %d bytes", max, n)
}
dst = bytesutil.ExtendSlice(dst, int(n))
_, err = io.ReadFull(r, dst[:])
if err != nil {
return nil, err
}
return dst, nil
}
func WriteSized(w io.Writer, buf []byte) error {
buf = bytesutil.ExtendSlice(buf, len(buf)+4)
binary.BigEndian.PutUint32(buf[len(buf)-4:], uint32(len(buf))-4)
_, err := w.Write(buf[len(buf)-4:])
if err == nil {
_, err = w.Write(buf[:len(buf)-4])
}
return err
}
func IsEOF(err error) bool {
if errors.Is(err, io.EOF) {
return true
}
var netErr *net.OpError
if !errors.As(err, &netErr) {
return false
}
if netErr.Err.Error() == "use of closed network connection" {
return true
}
return false
}