forked from colinmarc/sequencefile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter_helper.go
72 lines (61 loc) · 1.39 KB
/
writer_helper.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
package sequencefile
import (
"encoding/binary"
"io"
)
const syncMarker = -1
// A Writer wrapper that:
// - Stores any error that occurs, and stops writing.
// - Keeps track of how many bytes have been written.
// - Closes the wrapped writer, if it's close-able.
type writerHelper struct {
w io.Writer
bytes int
err error
}
// Explicitly set an error on the helper. This is important if partial data may
// have been written, which should cause subsequent writes to return errors.
func (w *writerHelper) setErr(err error) {
if w.err == nil {
w.err = err
}
}
func (w *writerHelper) Write(buf []byte) (n int, err error) {
if w.err == nil {
n, w.err = w.w.Write(buf)
w.bytes += n
}
return n, w.err
}
func (w *writerHelper) Close() error {
cw, ok := w.w.(io.WriteCloser)
if ok {
return cw.Close()
}
return nil
}
func (w *writerHelper) write(buf []byte) error {
_, err := w.Write(buf)
return err
}
func (w *writerHelper) writeString(s string) error {
WriteVInt(w, int64(len(s)))
return w.write([]byte(s))
}
func (w *writerHelper) writeBool(b bool) error {
if b {
return w.write([]byte{1})
}
return w.write([]byte{0})
}
func (w *writerHelper) writeInt32(i int32) error {
var bs [4]byte
binary.BigEndian.PutUint32(bs[:], uint32(i))
return w.write(bs[:])
}
func (w *writerHelper) writeSync(sync []byte) error {
w.writeInt32(syncMarker)
w.write(sync)
w.bytes = 0
return w.err
}