-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
63 lines (54 loc) · 1.05 KB
/
writer.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
package metago
import (
"bufio"
"io"
)
type Writer struct {
*bufio.Writer
p PersistenceClass
}
func NewWriter(w io.Writer, p PersistenceClass) *Writer {
return &Writer{Writer: bufio.NewWriter(w), p: p}
}
type Writable interface {
WriteTo(w *Writer) error
PersistenceClass() PersistenceClass
}
func (w *Writer) WriteObj(obj Writable) error {
if w.p == PersistenceClassPersistent && obj.PersistenceClass() != PersistenceClassPersistent {
return nil
}
if w.p == PersistenceClassNonPersistent && obj.PersistenceClass() == PersistenceClassEphemeral {
return nil
}
return obj.WriteTo(w)
}
func (w *Writer) WriteUVarint(v uint64) int {
i := 0
for v >= 0x80 {
w.WriteByte(byte(v) | 0x80)
v >>= 7
i++
}
w.WriteByte(byte(v))
return i + 1
}
func (w *Writer) WriteVarint(v int64) int {
uv := uint64(v) << 1
if v < 0 {
uv = ^uv
}
return w.WriteUVarint(uv)
}
func (w *Writer) WriteBool(v bool) int {
if v {
w.WriteByte(1)
} else {
w.WriteByte(0)
}
return 1
}
func (w *Writer) WriteString(v string) int {
c, _ := w.Write([]byte(v))
return c
}