open-nomad/helper/gated-writer/writer.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

46 lines
737 B
Go
Raw Normal View History

2015-08-23 23:57:54 +00:00
package gatedwriter
2015-08-16 20:54:49 +00:00
import (
"io"
"sync"
)
2015-08-23 23:57:54 +00:00
// Writer is an io.Writer implementation that buffers all of its
2015-08-16 20:54:49 +00:00
// data into an internal buffer until it is told to let data through.
2015-08-23 23:57:54 +00:00
type Writer struct {
2015-08-16 20:54:49 +00:00
Writer io.Writer
buf [][]byte
flush bool
lock sync.RWMutex
}
2015-08-23 23:57:54 +00:00
// Flush tells the Writer to flush any buffered data and to stop
2015-08-16 20:54:49 +00:00
// buffering.
2015-08-23 23:57:54 +00:00
func (w *Writer) Flush() {
2015-08-16 20:54:49 +00:00
w.lock.Lock()
defer w.lock.Unlock()
2015-08-16 20:54:49 +00:00
w.flush = true
for _, p := range w.buf {
_, _ = w.Writer.Write(p)
2015-08-16 20:54:49 +00:00
}
2015-08-16 20:54:49 +00:00
w.buf = nil
}
2015-08-23 23:57:54 +00:00
func (w *Writer) Write(p []byte) (n int, err error) {
w.lock.Lock()
defer w.lock.Unlock()
2015-08-16 20:54:49 +00:00
if w.flush {
return w.Writer.Write(p)
}
p2 := make([]byte, len(p))
copy(p2, p)
w.buf = append(w.buf, p2)
return len(p), nil
}