-
Notifications
You must be signed in to change notification settings - Fork 2
/
segment_writer.go
57 lines (48 loc) · 1.23 KB
/
segment_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
package segv1
import (
"bufio"
"io"
"github.com/linxGnu/pqueue/common"
"github.com/linxGnu/pqueue/entry"
"github.com/hashicorp/go-multierror"
)
var segmentEnding = []byte{0, 0, 0, 0, 0, 0, 0, 0}
type segmentWriter struct {
w *bufio.Writer
underlying io.WriteCloser
entryFormat common.EntryFormat
}
func newSegmentWriter(w io.WriteCloser, entryFormat common.EntryFormat) *segmentWriter {
return &segmentWriter{
w: bufio.NewWriter(w),
underlying: w,
entryFormat: entryFormat,
}
}
func (s *segmentWriter) Close() (err error) {
_, err = s.w.Write(segmentEnding)
err = multierror.Append(err, s.w.Flush(), s.underlying.Close()).ErrorOrNil()
return
}
// WriteEntry to underlying writer.
func (s *segmentWriter) WriteEntry(e entry.Entry) (common.ErrCode, error) {
_, err := e.Marshal(s.w, s.entryFormat)
if err == nil {
err = s.w.Flush()
}
if err == nil {
return common.NoError, nil
}
return common.SegmentCorrupted, err
}
// WriteEntry to underlying writer.
func (s *segmentWriter) WriteBatch(b entry.Batch) (common.ErrCode, error) {
_, err := b.Marshal(s.w, s.entryFormat)
if err == nil {
err = s.w.Flush()
}
if err == nil {
return common.NoError, nil
}
return common.SegmentCorrupted, err
}