Home Download Docs Code Community
     1	/*
     2	Copyright 2011 The Perkeep Authors
     3	
     4	Licensed under the Apache License, Version 2.0 (the "License");
     5	you may not use this file except in compliance with the License.
     6	You may obtain a copy of the License at
     7	
     8	     http://www.apache.org/licenses/LICENSE-2.0
     9	
    10	Unless required by applicable law or agreed to in writing, software
    11	distributed under the License is distributed on an "AS IS" BASIS,
    12	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13	See the License for the specific language governing permissions and
    14	limitations under the License.
    15	*/
    16	
    17	package blob
    18	
    19	// ChanPeeker wraps a channel receiving SizedRefs and adds a 1 element
    20	// buffer on it, with Peek and Take methods.
    21	type ChanPeeker struct {
    22		Ch <-chan SizedRef
    23	
    24		// Invariant after a call to Peek: either peekok or closed.
    25		closed bool
    26		peekok bool // whether peek is valid
    27		peek   SizedRef
    28	}
    29	
    30	// MustPeek returns the next SizedRef or panics if none is available.
    31	func (cp *ChanPeeker) MustPeek() SizedRef {
    32		sr, ok := cp.Peek()
    33		if !ok {
    34			panic("No Peek value available")
    35		}
    36		return sr
    37	}
    38	
    39	// Peek returns the next SizedRef and whether one was available.
    40	func (cp *ChanPeeker) Peek() (sr SizedRef, ok bool) {
    41		if cp.closed {
    42			return
    43		}
    44		if cp.peekok {
    45			return cp.peek, true
    46		}
    47		v, ok := <-cp.Ch
    48		if !ok {
    49			cp.closed = true
    50			return
    51		}
    52		cp.peek = v
    53		cp.peekok = true
    54		return cp.peek, true
    55	}
    56	
    57	// Closed reports true if no more SizedRef values are available.
    58	func (cp *ChanPeeker) Closed() bool {
    59		cp.Peek()
    60		return cp.closed
    61	}
    62	
    63	// MustTake returns the next SizedRef, else panics if none is available.
    64	func (cp *ChanPeeker) MustTake() SizedRef {
    65		sr, ok := cp.Take()
    66		if !ok {
    67			panic("MustTake called on empty channel")
    68		}
    69		return sr
    70	}
    71	
    72	// Take returns the next SizedRef and whether one was available for the taking.
    73	func (cp *ChanPeeker) Take() (sr SizedRef, ok bool) {
    74		v, ok := cp.Peek()
    75		if !ok {
    76			return
    77		}
    78		cp.peekok = false
    79		return v, true
    80	}
    81	
    82	// ConsumeAll drains the channel of all items.
    83	func (cp *ChanPeeker) ConsumeAll() {
    84		for !cp.Closed() {
    85			cp.Take()
    86		}
    87	}
Website layout inspired by memcached.
Content by the authors.