forked from gopwn/pwn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
io.go
90 lines (72 loc) · 2.05 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Some useful io utils, because io/ioutil is not enough
package pwn
import (
"context"
"errors"
"io"
)
// ErrMaxLen indecates that the max length was reached for ReadTill.
var ErrMaxLen = errors.New("max length reached")
// ErrNilReader indecates that a nil reader was supplied.
var ErrNilReader = errors.New("nil reader")
// MaxLenDefault is the max length default for the ReadTill function.
const MaxLenDefault = 256
// ReadByte reads one byte from r and returns it,
// if it fails it will return io.ErrUnexpectedEOF.
func ReadByte(r io.Reader) (byte, error) {
var buf [1]byte
// read into buf
_, err := io.ReadFull(r, buf[:])
return buf[0], err
}
// ReadTill reads till 'delim' (non inclusive) and returns bytes read and possible error.
// if maxLen is <= 0 it will use MaxLenDefault.
func ReadTill(r io.Reader, maxLen int, delim byte) ([]byte, error) {
return ReadTillContext(r, maxLen, delim, context.Background())
}
// this function's params are very long, i don't want to create a struct
// just for it though, should not be too long when calling it
// ReadTill reads till 'delim' (non inclusive) or ctx.Done()
// and returns bytes read and possible error.
// if maxLen is <= 0 it will use MaxLenDefault.
func ReadTillContext(r io.Reader, maxLen int, delim byte,
ctx context.Context) (ret []byte, err error) {
if maxLen <= 0 {
maxLen = MaxLenDefault
}
if r == nil {
return ret, ErrNilReader
}
for {
select {
case <-ctx.Done():
return ret, err
default:
}
// read one byte
b, err := ReadByte(r)
if err != nil {
return ret, err
}
// if the byte is equal to delim stop reading
if b == delim {
break
}
// append the byte to ret
ret = append(ret, b)
if len(ret) >= maxLen {
return ret, ErrMaxLen
}
}
return ret, nil
}
// WriteLine writes a line to the writer
// it will panic if it ToBytes fails to convert t to []byte
func WriteLine(w io.Writer, t interface{}) error {
// convert t to bytes
b := Bytes(t)
// add the newline, we are "WriteLine" after all!
b = append(b, '\n')
_, err := w.Write(b)
return err
}