99var (
1010 // ErrTimeout indicates an operation has timed out.
1111 ErrTimeout = errors .New ("operation timed-out" )
12+ // ErrClosed indicates the buffer is closed and can no longer be used.
13+ ErrClosed = errors .New ("buffer is closed" )
1214)
1315
1416type (
@@ -23,9 +25,15 @@ type (
2325 }
2426)
2527
26- // Push appends an item to the end of the buffer. It times out if it cannot be
27- // performed in a timely fashion.
28+ // Push appends an item to the end of the buffer.
29+ //
30+ // It returns an ErrTimeout if if cannot be performed in a timely fashion, and
31+ // an ErrClosed if the buffer has been closed.
2832func (buffer * Buffer ) Push (item interface {}) error {
33+ if buffer .closed () {
34+ return ErrClosed
35+ }
36+
2937 select {
3038 case buffer .dataCh <- item :
3139 return nil
@@ -34,9 +42,15 @@ func (buffer *Buffer) Push(item interface{}) error {
3442 }
3543}
3644
37- // Flush outputs the buffer to a permanent destination. It times out if it cannot be
38- // performed in a timely fashion.
45+ // Flush outputs the buffer to a permanent destination.
46+ //
47+ // It returns an ErrTimeout if if cannot be performed in a timely fashion, and
48+ // an ErrClosed if the buffer has been closed.
3949func (buffer * Buffer ) Flush () error {
50+ if buffer .closed () {
51+ return ErrClosed
52+ }
53+
4054 select {
4155 case buffer .flushCh <- struct {}{}:
4256 return nil
@@ -45,9 +59,19 @@ func (buffer *Buffer) Flush() error {
4559 }
4660}
4761
48- // Close flushes the buffer and prevents it from being further used. If it succeeds,
49- // the buffer cannot be used after it has been closed as all further operations will panic.
62+ // Close flushes the buffer and prevents it from being further used.
63+ //
64+ // It returns an ErrTimeout if if cannot be performed in a timely fashion, and
65+ // an ErrClosed if the buffer has already been closed.
66+ //
67+ // An ErrTimeout can either mean that a flush could not be triggered, or it can
68+ // mean that a flush was triggered but it has not finished yet. In any case it is
69+ // safe to call Close again.
5070func (buffer * Buffer ) Close () error {
71+ if buffer .closed () {
72+ return ErrClosed
73+ }
74+
5175 select {
5276 case buffer .closeCh <- struct {}{}:
5377 // noop
@@ -66,6 +90,15 @@ func (buffer *Buffer) Close() error {
6690 }
6791}
6892
93+ func (buffer Buffer ) closed () bool {
94+ select {
95+ case <- buffer .doneCh :
96+ return true
97+ default :
98+ return false
99+ }
100+ }
101+
69102func (buffer * Buffer ) consume () {
70103 count := 0
71104 items := make ([]interface {}, buffer .options .Size )
0 commit comments