David K. Bainbridge | bd6b288 | 2021-08-26 13:31:02 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019 gRPC 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 | |
| 18 | // Package buffer provides an implementation of an unbounded buffer. |
| 19 | package buffer |
| 20 | |
| 21 | import "sync" |
| 22 | |
| 23 | // Unbounded is an implementation of an unbounded buffer which does not use |
| 24 | // extra goroutines. This is typically used for passing updates from one entity |
| 25 | // to another within gRPC. |
| 26 | // |
| 27 | // All methods on this type are thread-safe and don't block on anything except |
| 28 | // the underlying mutex used for synchronization. |
| 29 | type Unbounded struct { |
| 30 | c chan interface{} |
| 31 | mu sync.Mutex |
| 32 | backlog []interface{} |
| 33 | } |
| 34 | |
| 35 | // NewUnbounded returns a new instance of Unbounded. |
| 36 | func NewUnbounded() *Unbounded { |
| 37 | return &Unbounded{c: make(chan interface{}, 1)} |
| 38 | } |
| 39 | |
| 40 | // Put adds t to the unbounded buffer. |
| 41 | func (b *Unbounded) Put(t interface{}) { |
| 42 | b.mu.Lock() |
| 43 | if len(b.backlog) == 0 { |
| 44 | select { |
| 45 | case b.c <- t: |
| 46 | b.mu.Unlock() |
| 47 | return |
| 48 | default: |
| 49 | } |
| 50 | } |
| 51 | b.backlog = append(b.backlog, t) |
| 52 | b.mu.Unlock() |
| 53 | } |
| 54 | |
| 55 | // Load sends the earliest buffered data, if any, onto the read channel |
| 56 | // returned by Get(). Users are expected to call this every time they read a |
| 57 | // value from the read channel. |
| 58 | func (b *Unbounded) Load() { |
| 59 | b.mu.Lock() |
| 60 | if len(b.backlog) > 0 { |
| 61 | select { |
| 62 | case b.c <- b.backlog[0]: |
| 63 | b.backlog[0] = nil |
| 64 | b.backlog = b.backlog[1:] |
| 65 | default: |
| 66 | } |
| 67 | } |
| 68 | b.mu.Unlock() |
| 69 | } |
| 70 | |
| 71 | // Get returns a read channel on which values added to the buffer, via Put(), |
| 72 | // are sent on. |
| 73 | // |
| 74 | // Upon reading a value from this channel, users are expected to call Load() to |
| 75 | // send the next buffered value onto the channel if there is any. |
| 76 | func (b *Unbounded) Get() <-chan interface{} { |
| 77 | return b.c |
| 78 | } |