github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/pkg/blob/chanpeek.go (about) 1 /* 2 Copyright 2011 Google Inc. 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 // TODO: use Generics if/when available 20 type ChanPeeker struct { 21 Ch <-chan SizedRef 22 23 // A channel should either have a peek value or be closed: 24 peek *SizedRef 25 closed bool 26 } 27 28 func (cp *ChanPeeker) MustPeek() SizedRef { 29 sr, ok := cp.Peek() 30 if !ok { 31 panic("No Peek value available") 32 } 33 return sr 34 } 35 36 func (cp *ChanPeeker) Peek() (sr SizedRef, ok bool) { 37 if cp.closed { 38 return 39 } 40 if cp.peek != nil { 41 return *cp.peek, true 42 } 43 v, ok := <-cp.Ch 44 if !ok { 45 cp.closed = true 46 return 47 } 48 cp.peek = &v 49 return *cp.peek, true 50 } 51 52 func (cp *ChanPeeker) Closed() bool { 53 cp.Peek() 54 return cp.closed 55 } 56 57 func (cp *ChanPeeker) MustTake() SizedRef { 58 sr, ok := cp.Take() 59 if !ok { 60 panic("MustTake called on empty channel") 61 } 62 return sr 63 } 64 65 func (cp *ChanPeeker) Take() (sr SizedRef, ok bool) { 66 v, ok := cp.Peek() 67 if !ok { 68 return 69 } 70 cp.peek = nil 71 return v, true 72 } 73 74 func (cp *ChanPeeker) ConsumeAll() { 75 for !cp.Closed() { 76 cp.Take() 77 } 78 }