-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.go
More file actions
43 lines (38 loc) · 1.01 KB
/
writer.go
File metadata and controls
43 lines (38 loc) · 1.01 KB
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
package nbt
import "io"
// offsetWriter is a wrapper around an io.Writer which keeps track of the amount of bytes written, so that it
// may be used in errors.
type offsetWriter struct {
io.Writer
off int64
// WriteByte is a function implemented by offsetWriter if the io.Writer does not implement it itself.
WriteByte func(byte) error
}
// newOffsetWriter creates a new offsetWriter wrapping the given io.Writer.
func newOffsetWriter(w io.Writer) *offsetWriter {
ow := &offsetWriter{Writer: w}
if bw, ok := w.(io.ByteWriter); ok {
ow.WriteByte = func(b byte) error {
err := bw.WriteByte(b)
if err == nil {
ow.off++
}
return err
}
} else {
ow.WriteByte = func(b byte) error {
_, err := w.Write([]byte{b})
if err == nil {
ow.off++
}
return err
}
}
return ow
}
// Write writes a byte slice to the underlying io.Writer. It increases the byte offset by exactly n.
func (w *offsetWriter) Write(b []byte) (n int, err error) {
n, err = w.Writer.Write(b)
w.off += int64(n)
return
}