1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
12 // buffer provides a linked list buffer for data exchange
13 // between producer and consumer. Theoretically the buffer is
14 // of unlimited capacity as it does no allocation of its own.
16 // protects concurrent access to head, tail and closed
19 head *element // the buffer that will be read first
20 tail *element // the buffer that will be read last
25 // An element represents a single link in a linked list.
31 // newBuffer returns an empty buffer that is not closed.
32 func newBuffer() *buffer {
42 // write makes buf available for Read to receive.
43 // buf must not be modified after the call to write.
44 func (b *buffer) write(buf []byte) {
46 e := &element{buf: buf}
53 // eof closes the buffer. Reads from the buffer once all
54 // the data has been consumed will receive os.EOF.
55 func (b *buffer) eof() error {
63 // Read reads data from the internal buffer in buf. Reads will block
64 // if no data is available, or until the buffer is closed.
65 func (b *buffer) Read(buf []byte) (n int, err error) {
67 defer b.Cond.L.Unlock()
70 // if there is data in b.head, copy it
71 if len(b.head.buf) > 0 {
72 r := copy(buf, b.head.buf)
73 buf, b.head.buf = buf[r:], b.head.buf[r:]
77 // if there is a next buffer, make it the head
78 if len(b.head.buf) == 0 && b.head != b.tail {
83 // if at least one byte has been copied, return
88 // if nothing was read, and there is nothing outstanding
89 // check to see if the buffer is closed.
94 // out of buffers, wait for producer