mirror of https://github.com/perkeep/perkeep.git
blob: document, clean up ChanPeeker
Change-Id: I7c721f1e3fb81011cf2911be8889dcb9abc66dd5
This commit is contained in:
parent
79db18d64d
commit
cd5fa05a18
|
@ -16,15 +16,18 @@ limitations under the License.
|
|||
|
||||
package blob
|
||||
|
||||
// TODO: use Generics if/when available
|
||||
// ChanPeeker wraps a channel receiving SizedRefs and adds a 1 element
|
||||
// buffer on it, with Peek and Take methods.
|
||||
type ChanPeeker struct {
|
||||
Ch <-chan SizedRef
|
||||
|
||||
// A channel should either have a peek value or be closed:
|
||||
peek *SizedRef
|
||||
// Invariant after a call to Peek: either peekok or closed.
|
||||
closed bool
|
||||
peekok bool // whether peek is valid
|
||||
peek SizedRef
|
||||
}
|
||||
|
||||
// MustPeek returns the next SizedRef or panics if none is available.
|
||||
func (cp *ChanPeeker) MustPeek() SizedRef {
|
||||
sr, ok := cp.Peek()
|
||||
if !ok {
|
||||
|
@ -33,27 +36,31 @@ func (cp *ChanPeeker) MustPeek() SizedRef {
|
|||
return sr
|
||||
}
|
||||
|
||||
// Peek returns the next SizedRef and whether one was available.
|
||||
func (cp *ChanPeeker) Peek() (sr SizedRef, ok bool) {
|
||||
if cp.closed {
|
||||
return
|
||||
}
|
||||
if cp.peek != nil {
|
||||
return *cp.peek, true
|
||||
if cp.peekok {
|
||||
return cp.peek, true
|
||||
}
|
||||
v, ok := <-cp.Ch
|
||||
if !ok {
|
||||
cp.closed = true
|
||||
return
|
||||
}
|
||||
cp.peek = &v
|
||||
return *cp.peek, true
|
||||
cp.peek = v
|
||||
cp.peekok = true
|
||||
return cp.peek, true
|
||||
}
|
||||
|
||||
// Closed reports true if no more SizedRef values are available.
|
||||
func (cp *ChanPeeker) Closed() bool {
|
||||
cp.Peek()
|
||||
return cp.closed
|
||||
}
|
||||
|
||||
// MustTake returns the next SizedRef, else panics if none is available.
|
||||
func (cp *ChanPeeker) MustTake() SizedRef {
|
||||
sr, ok := cp.Take()
|
||||
if !ok {
|
||||
|
@ -62,15 +69,17 @@ func (cp *ChanPeeker) MustTake() SizedRef {
|
|||
return sr
|
||||
}
|
||||
|
||||
// Take returns the next SizedRef and whether one was available for the taking.
|
||||
func (cp *ChanPeeker) Take() (sr SizedRef, ok bool) {
|
||||
v, ok := cp.Peek()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cp.peek = nil
|
||||
cp.peekok = false
|
||||
return v, true
|
||||
}
|
||||
|
||||
// ConsumeAll drains the channel of all items.
|
||||
func (cp *ChanPeeker) ConsumeAll() {
|
||||
for !cp.Closed() {
|
||||
cp.Take()
|
||||
|
|
Loading…
Reference in New Issue