-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwriter.go
41 lines (31 loc) · 838 Bytes
/
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
package protobuf
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"github.com/christianalexander/kvdb/stores"
proto "github.com/golang/protobuf/proto"
)
type protoWriter struct {
writer io.Writer
}
func NewWriter(writer io.Writer) stores.Writer {
return protoWriter{writer}
}
func (w protoWriter) Write(ctx context.Context, record stores.Record) error {
protoRecord := RecordToProto(record)
out, err := proto.Marshal(protoRecord)
if err != nil {
return fmt.Errorf("failed to marshal record %s: %v", record, err)
}
lBuf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(lBuf, uint64(len(out)))
mr := io.MultiReader(bytes.NewBuffer(lBuf[:n]), bytes.NewBuffer(out))
_, err = io.Copy(w.writer, mr)
if err != nil {
return fmt.Errorf("failed to write record to log: %v", err)
}
return nil
}