open-vault/internalshared/gatedwriter/writer.go

44 lines
750 B
Go
Raw Normal View History

2015-04-04 19:06:41 +00:00
package gatedwriter
import (
"bytes"
2015-04-04 19:06:41 +00:00
"io"
"sync"
)
// Writer is an io.Writer implementation that buffers all of its
// data into an internal buffer until it is told to let data through.
type Writer struct {
writer io.Writer
2015-04-04 19:06:41 +00:00
buf bytes.Buffer
2015-04-04 19:06:41 +00:00
flush bool
lock sync.Mutex
}
func NewWriter(underlying io.Writer) *Writer {
return &Writer{writer: underlying}
2015-04-04 19:06:41 +00:00
}
// Flush tells the Writer to flush any buffered data and to stop
// buffering.
2020-01-23 19:24:13 +00:00
func (w *Writer) Flush() error {
2015-04-04 19:06:41 +00:00
w.lock.Lock()
defer w.lock.Unlock()
2015-04-04 19:06:41 +00:00
w.flush = true
2020-01-23 19:24:13 +00:00
_, err := w.buf.WriteTo(w.writer)
return err
2015-04-04 19:06:41 +00:00
}
func (w *Writer) Write(p []byte) (n int, err error) {
w.lock.Lock()
defer w.lock.Unlock()
2015-04-04 19:06:41 +00:00
if w.flush {
return w.writer.Write(p)
2015-04-04 19:06:41 +00:00
}
return w.buf.Write(p)
2015-04-04 19:06:41 +00:00
}