From cd5fa05a188ec5cdd01d1c7f8c145b791bd14a7d Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Mon, 22 Sep 2014 22:05:48 -0400 Subject: [PATCH] blob: document, clean up ChanPeeker Change-Id: I7c721f1e3fb81011cf2911be8889dcb9abc66dd5 --- pkg/blob/chanpeek.go | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/pkg/blob/chanpeek.go b/pkg/blob/chanpeek.go index b08f389c5..f327b372a 100644 --- a/pkg/blob/chanpeek.go +++ b/pkg/blob/chanpeek.go @@ -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()