-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwriter.go
51 lines (46 loc) · 910 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
42
43
44
45
46
47
48
49
50
51
package cdb
import (
"fmt"
"io"
)
// Writer provides a simple interface for creating CDBs by wrapping the Make
// function.
//
// Not threadsafe.
type Writer struct {
pipeWriter *io.PipeWriter
doneCh chan error
makeErr error
}
func NewWriter(ws io.WriteSeeker) *Writer {
pipeReader, pipeWriter := io.Pipe()
w := &Writer{
pipeWriter: pipeWriter,
doneCh: make(chan error, 1),
}
go func() {
defer pipeReader.Close()
w.doneCh <- Make(ws, pipeReader)
}()
return w
}
func (w *Writer) Write(key, val []byte) error {
select {
case err := <-w.doneCh:
w.makeErr = err
default:
}
if w.makeErr != nil {
return w.makeErr
}
_, err := fmt.Fprintf(w.pipeWriter, "+%v,%v:%s->%s\n", len(key), len(val), key, val)
return err
}
func (w *Writer) Close() error {
if w.makeErr != nil {
return w.makeErr
}
w.pipeWriter.Write([]byte("\n"))
w.pipeWriter.Close()
return <-w.doneCh
}