You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rbuf.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package unsnap
  2. // copyright (c) 2014, Jason E. Aten
  3. // license: MIT
  4. // Some text from the Golang standard library doc is adapted and
  5. // reproduced in fragments below to document the expected behaviors
  6. // of the interface functions Read()/Write()/ReadFrom()/WriteTo() that
  7. // are implemented here. Those descriptions (see
  8. // http://golang.org/pkg/io/#Reader for example) are
  9. // copyright 2010 The Go Authors.
  10. import "io"
  11. // FixedSizeRingBuf:
  12. //
  13. // a fixed-size circular ring buffer. Yes, just what is says.
  14. //
  15. // We keep a pair of ping/pong buffers so that we can linearize
  16. // the circular buffer into a contiguous slice if need be.
  17. //
  18. // For efficiency, a FixedSizeRingBuf may be vastly preferred to
  19. // a bytes.Buffer. The ReadWithoutAdvance(), Advance(), and Adopt()
  20. // methods are all non-standard methods written for speed.
  21. //
  22. // For an I/O heavy application, I have replaced bytes.Buffer with
  23. // FixedSizeRingBuf and seen memory consumption go from 8GB to 25MB.
  24. // Yes, that is a 300x reduction in memory footprint. Everything ran
  25. // faster too.
  26. //
  27. // Note that Bytes(), while inescapable at times, is expensive: avoid
  28. // it if possible. Instead it is better to use the FixedSizeRingBuf.Readable
  29. // member to get the number of bytes available. Bytes() is expensive because
  30. // it may copy the back and then the front of a wrapped buffer A[Use]
  31. // into A[1-Use] in order to get a contiguous slice. If possible use ContigLen()
  32. // first to get the size that can be read without copying, Read() that
  33. // amount, and then Read() a second time -- to avoid the copy.
  34. type FixedSizeRingBuf struct {
  35. A [2][]byte // a pair of ping/pong buffers. Only one is active.
  36. Use int // which A buffer is in active use, 0 or 1
  37. N int // MaxViewInBytes, the size of A[0] and A[1] in bytes.
  38. Beg int // start of data in A[Use]
  39. Readable int // number of bytes available to read in A[Use]
  40. OneMade bool // lazily instantiate the [1] buffer. If we never call Bytes(),
  41. // we may never need it. If OneMade is false, the Use must be = 0.
  42. }
  43. func (b *FixedSizeRingBuf) Make2ndBuffer() {
  44. if b.OneMade {
  45. return
  46. }
  47. b.A[1] = make([]byte, b.N, b.N)
  48. b.OneMade = true
  49. }
  50. // get the length of the largest read that we can provide to a contiguous slice
  51. // without an extra linearizing copy of all bytes internally.
  52. func (b *FixedSizeRingBuf) ContigLen() int {
  53. extent := b.Beg + b.Readable
  54. firstContigLen := intMin(extent, b.N) - b.Beg
  55. return firstContigLen
  56. }
  57. func NewFixedSizeRingBuf(maxViewInBytes int) *FixedSizeRingBuf {
  58. n := maxViewInBytes
  59. r := &FixedSizeRingBuf{
  60. Use: 0, // 0 or 1, whichever is actually in use at the moment.
  61. // If we are asked for Bytes() and we wrap, linearize into the other.
  62. N: n,
  63. Beg: 0,
  64. Readable: 0,
  65. OneMade: false,
  66. }
  67. r.A[0] = make([]byte, n, n)
  68. // r.A[1] initialized lazily now.
  69. return r
  70. }
  71. // from the standard library description of Bytes():
  72. // Bytes() returns a slice of the contents of the unread portion of the buffer.
  73. // If the caller changes the contents of the
  74. // returned slice, the contents of the buffer will change provided there
  75. // are no intervening method calls on the Buffer.
  76. //
  77. func (b *FixedSizeRingBuf) Bytes() []byte {
  78. extent := b.Beg + b.Readable
  79. if extent <= b.N {
  80. // we fit contiguously in this buffer without wrapping to the other
  81. return b.A[b.Use][b.Beg:(b.Beg + b.Readable)]
  82. }
  83. // wrap into the other buffer
  84. b.Make2ndBuffer()
  85. src := b.Use
  86. dest := 1 - b.Use
  87. n := copy(b.A[dest], b.A[src][b.Beg:])
  88. n += copy(b.A[dest][n:], b.A[src][0:(extent%b.N)])
  89. b.Use = dest
  90. b.Beg = 0
  91. return b.A[b.Use][:n]
  92. }
  93. // Read():
  94. //
  95. // from bytes.Buffer.Read(): Read reads the next len(p) bytes
  96. // from the buffer or until the buffer is drained. The return
  97. // value n is the number of bytes read. If the buffer has no data
  98. // to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.
  99. //
  100. // from the description of the Reader interface,
  101. // http://golang.org/pkg/io/#Reader
  102. //
  103. /*
  104. Reader is the interface that wraps the basic Read method.
  105. Read reads up to len(p) bytes into p. It returns the number
  106. of bytes read (0 <= n <= len(p)) and any error encountered.
  107. Even if Read returns n < len(p), it may use all of p as scratch
  108. space during the call. If some data is available but not
  109. len(p) bytes, Read conventionally returns what is available
  110. instead of waiting for more.
  111. When Read encounters an error or end-of-file condition after
  112. successfully reading n > 0 bytes, it returns the number of bytes
  113. read. It may return the (non-nil) error from the same call or
  114. return the error (and n == 0) from a subsequent call. An instance
  115. of this general case is that a Reader returning a non-zero number
  116. of bytes at the end of the input stream may return
  117. either err == EOF or err == nil. The next Read should
  118. return 0, EOF regardless.
  119. Callers should always process the n > 0 bytes returned before
  120. considering the error err. Doing so correctly handles I/O errors
  121. that happen after reading some bytes and also both of the
  122. allowed EOF behaviors.
  123. Implementations of Read are discouraged from returning a zero
  124. byte count with a nil error, and callers should treat that
  125. situation as a no-op.
  126. */
  127. //
  128. func (b *FixedSizeRingBuf) Read(p []byte) (n int, err error) {
  129. return b.ReadAndMaybeAdvance(p, true)
  130. }
  131. // if you want to Read the data and leave it in the buffer, so as
  132. // to peek ahead for example.
  133. func (b *FixedSizeRingBuf) ReadWithoutAdvance(p []byte) (n int, err error) {
  134. return b.ReadAndMaybeAdvance(p, false)
  135. }
  136. func (b *FixedSizeRingBuf) ReadAndMaybeAdvance(p []byte, doAdvance bool) (n int, err error) {
  137. if len(p) == 0 {
  138. return 0, nil
  139. }
  140. if b.Readable == 0 {
  141. return 0, io.EOF
  142. }
  143. extent := b.Beg + b.Readable
  144. if extent <= b.N {
  145. n += copy(p, b.A[b.Use][b.Beg:extent])
  146. } else {
  147. n += copy(p, b.A[b.Use][b.Beg:b.N])
  148. if n < len(p) {
  149. n += copy(p[n:], b.A[b.Use][0:(extent%b.N)])
  150. }
  151. }
  152. if doAdvance {
  153. b.Advance(n)
  154. }
  155. return
  156. }
  157. //
  158. // Write writes len(p) bytes from p to the underlying data stream.
  159. // It returns the number of bytes written from p (0 <= n <= len(p))
  160. // and any error encountered that caused the write to stop early.
  161. // Write must return a non-nil error if it returns n < len(p).
  162. //
  163. func (b *FixedSizeRingBuf) Write(p []byte) (n int, err error) {
  164. for {
  165. if len(p) == 0 {
  166. // nothing (left) to copy in; notice we shorten our
  167. // local copy p (below) as we read from it.
  168. return
  169. }
  170. writeCapacity := b.N - b.Readable
  171. if writeCapacity <= 0 {
  172. // we are all full up already.
  173. return n, io.ErrShortWrite
  174. }
  175. if len(p) > writeCapacity {
  176. err = io.ErrShortWrite
  177. // leave err set and
  178. // keep going, write what we can.
  179. }
  180. writeStart := (b.Beg + b.Readable) % b.N
  181. upperLim := intMin(writeStart+writeCapacity, b.N)
  182. k := copy(b.A[b.Use][writeStart:upperLim], p)
  183. n += k
  184. b.Readable += k
  185. p = p[k:]
  186. // we can fill from b.A[b.Use][0:something] from
  187. // p's remainder, so loop
  188. }
  189. }
  190. // WriteTo and ReadFrom avoid intermediate allocation and copies.
  191. // WriteTo writes data to w until there's no more data to write
  192. // or when an error occurs. The return value n is the number of
  193. // bytes written. Any error encountered during the write is also returned.
  194. func (b *FixedSizeRingBuf) WriteTo(w io.Writer) (n int64, err error) {
  195. if b.Readable == 0 {
  196. return 0, io.EOF
  197. }
  198. extent := b.Beg + b.Readable
  199. firstWriteLen := intMin(extent, b.N) - b.Beg
  200. secondWriteLen := b.Readable - firstWriteLen
  201. if firstWriteLen > 0 {
  202. m, e := w.Write(b.A[b.Use][b.Beg:(b.Beg + firstWriteLen)])
  203. n += int64(m)
  204. b.Advance(m)
  205. if e != nil {
  206. return n, e
  207. }
  208. // all bytes should have been written, by definition of
  209. // Write method in io.Writer
  210. if m != firstWriteLen {
  211. return n, io.ErrShortWrite
  212. }
  213. }
  214. if secondWriteLen > 0 {
  215. m, e := w.Write(b.A[b.Use][0:secondWriteLen])
  216. n += int64(m)
  217. b.Advance(m)
  218. if e != nil {
  219. return n, e
  220. }
  221. // all bytes should have been written, by definition of
  222. // Write method in io.Writer
  223. if m != secondWriteLen {
  224. return n, io.ErrShortWrite
  225. }
  226. }
  227. return n, nil
  228. }
  229. // ReadFrom() reads data from r until EOF or error. The return value n
  230. // is the number of bytes read. Any error except io.EOF encountered
  231. // during the read is also returned.
  232. func (b *FixedSizeRingBuf) ReadFrom(r io.Reader) (n int64, err error) {
  233. for {
  234. writeCapacity := b.N - b.Readable
  235. if writeCapacity <= 0 {
  236. // we are all full
  237. return n, nil
  238. }
  239. writeStart := (b.Beg + b.Readable) % b.N
  240. upperLim := intMin(writeStart+writeCapacity, b.N)
  241. m, e := r.Read(b.A[b.Use][writeStart:upperLim])
  242. n += int64(m)
  243. b.Readable += m
  244. if e == io.EOF {
  245. return n, nil
  246. }
  247. if e != nil {
  248. return n, e
  249. }
  250. }
  251. }
  252. func (b *FixedSizeRingBuf) Reset() {
  253. b.Beg = 0
  254. b.Readable = 0
  255. b.Use = 0
  256. }
  257. // Advance(): non-standard, but better than Next(),
  258. // because we don't have to unwrap our buffer and pay the cpu time
  259. // for the copy that unwrapping may need.
  260. // Useful in conjuction/after ReadWithoutAdvance() above.
  261. func (b *FixedSizeRingBuf) Advance(n int) {
  262. if n <= 0 {
  263. return
  264. }
  265. if n > b.Readable {
  266. n = b.Readable
  267. }
  268. b.Readable -= n
  269. b.Beg = (b.Beg + n) % b.N
  270. }
  271. // Adopt(): non-standard.
  272. //
  273. // For efficiency's sake, (possibly) take ownership of
  274. // already allocated slice offered in me.
  275. //
  276. // If me is large we will adopt it, and we will potentially then
  277. // write to the me buffer.
  278. // If we already have a bigger buffer, copy me into the existing
  279. // buffer instead.
  280. func (b *FixedSizeRingBuf) Adopt(me []byte) {
  281. n := len(me)
  282. if n > b.N {
  283. b.A[0] = me
  284. b.OneMade = false
  285. b.N = n
  286. b.Use = 0
  287. b.Beg = 0
  288. b.Readable = n
  289. } else {
  290. // we already have a larger buffer, reuse it.
  291. copy(b.A[0], me)
  292. b.Use = 0
  293. b.Beg = 0
  294. b.Readable = n
  295. }
  296. }
  297. func intMax(a, b int) int {
  298. if a > b {
  299. return a
  300. } else {
  301. return b
  302. }
  303. }
  304. func intMin(a, b int) int {
  305. if a < b {
  306. return a
  307. } else {
  308. return b
  309. }
  310. }
  311. // Get the (beg, end] indices of the tailing empty buffer of bytes slice that from that is free for writing.
  312. // Note: not guaranteed to be zeroed. At all.
  313. func (b *FixedSizeRingBuf) GetEndmostWritable() (beg int, end int) {
  314. extent := b.Beg + b.Readable
  315. if extent < b.N {
  316. return extent, b.N
  317. }
  318. return extent % b.N, b.Beg
  319. }
  320. // Note: not guaranteed to be zeroed.
  321. func (b *FixedSizeRingBuf) GetEndmostWritableSlice() []byte {
  322. beg, e := b.GetEndmostWritable()
  323. return b.A[b.Use][beg:e]
  324. }