-
Notifications
You must be signed in to change notification settings - Fork 19
/
write_context.go
73 lines (59 loc) · 1.56 KB
/
write_context.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 wire
import (
"encoding/binary"
"fmt"
"io"
"reflect"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
// WriteContext holds state of a wharf wire format writer
type WriteContext struct {
writer io.Writer
varintBuffer []byte
}
// NewWriteContext builds a new WriteContext that writes to a given writer
func NewWriteContext(writer io.Writer) *WriteContext {
return &WriteContext{writer, make([]byte, 8)}
}
// Writer returns writer a WriteContext writes to
func (w *WriteContext) Writer() io.Writer {
return w.writer
}
// Close closes the underlying writer if it implements io.Closer
func (w *WriteContext) Close() error {
if c, ok := w.writer.(io.Closer); ok {
err := c.Close()
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
// WriteMagic writes a 32-bit magic integer to identify the file's type
func (w *WriteContext) WriteMagic(magic int32) error {
return binary.Write(w.writer, Endianness, magic)
}
// WriteMessage serializes a protobuf message and writes it to the stream
func (w *WriteContext) WriteMessage(msg proto.Message) error {
if DebugWire {
fmt.Printf("<< %s %+v\n", reflect.TypeOf(msg).Elem().Name(), msg)
}
buf, err := proto.Marshal(msg)
if err != nil {
return errors.WithStack(err)
}
vibuflen := binary.PutUvarint(w.varintBuffer, uint64(len(buf)))
if err != nil {
return errors.WithStack(err)
}
_, err = w.writer.Write(w.varintBuffer[:vibuflen])
if err != nil {
return errors.WithStack(err)
}
_, err = w.writer.Write(buf)
if err != nil {
return errors.WithStack(err)
}
return nil
}