buffer.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.
  4. package ssh
  5. import (
  6. "io"
  7. "sync"
  8. )
  9. // buffer provides a linked list buffer for data exchange
  10. // between producer and consumer. Theoretically the buffer is
  11. // of unlimited capacity as it does no allocation of its own.
  12. type buffer struct {
  13. // protects concurrent access to head, tail and closed
  14. *sync.Cond
  15. head *element // the buffer that will be read first
  16. tail *element // the buffer that will be read last
  17. closed bool
  18. }
  19. // An element represents a single link in a linked list.
  20. type element struct {
  21. buf []byte
  22. next *element
  23. }
  24. // newBuffer returns an empty buffer that is not closed.
  25. func newBuffer() *buffer {
  26. e := new(element)
  27. b := &buffer{
  28. Cond: newCond(),
  29. head: e,
  30. tail: e,
  31. }
  32. return b
  33. }
  34. // write makes buf available for Read to receive.
  35. // buf must not be modified after the call to write.
  36. func (b *buffer) write(buf []byte) {
  37. b.Cond.L.Lock()
  38. e := &element{buf: buf}
  39. b.tail.next = e
  40. b.tail = e
  41. b.Cond.Signal()
  42. b.Cond.L.Unlock()
  43. }
  44. // eof closes the buffer. Reads from the buffer once all
  45. // the data has been consumed will receive io.EOF.
  46. func (b *buffer) eof() {
  47. b.Cond.L.Lock()
  48. b.closed = true
  49. b.Cond.Signal()
  50. b.Cond.L.Unlock()
  51. }
  52. // Read reads data from the internal buffer in buf. Reads will block
  53. // if no data is available, or until the buffer is closed.
  54. func (b *buffer) Read(buf []byte) (n int, err error) {
  55. b.Cond.L.Lock()
  56. defer b.Cond.L.Unlock()
  57. for len(buf) > 0 {
  58. // if there is data in b.head, copy it
  59. if len(b.head.buf) > 0 {
  60. r := copy(buf, b.head.buf)
  61. buf, b.head.buf = buf[r:], b.head.buf[r:]
  62. n += r
  63. continue
  64. }
  65. // if there is a next buffer, make it the head
  66. if len(b.head.buf) == 0 && b.head != b.tail {
  67. b.head = b.head.next
  68. continue
  69. }
  70. // if at least one byte has been copied, return
  71. if n > 0 {
  72. break
  73. }
  74. // if nothing was read, and there is nothing outstanding
  75. // check to see if the buffer is closed.
  76. if b.closed {
  77. err = io.EOF
  78. break
  79. }
  80. // out of buffers, wait for producer
  81. b.Cond.Wait()
  82. }
  83. return
  84. }