reader.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // The `fwd` package provides a buffered reader
  2. // and writer. Each has methods that help improve
  3. // the encoding/decoding performance of some binary
  4. // protocols.
  5. //
  6. // The `fwd.Writer` and `fwd.Reader` type provide similar
  7. // functionality to their counterparts in `bufio`, plus
  8. // a few extra utility methods that simplify read-ahead
  9. // and write-ahead. I wrote this package to improve serialization
  10. // performance for http://github.com/tinylib/msgp,
  11. // where it provided about a 2x speedup over `bufio` for certain
  12. // workloads. However, care must be taken to understand the semantics of the
  13. // extra methods provided by this package, as they allow
  14. // the user to access and manipulate the buffer memory
  15. // directly.
  16. //
  17. // The extra methods for `fwd.Reader` are `Peek`, `Skip`
  18. // and `Next`. `(*fwd.Reader).Peek`, unlike `(*bufio.Reader).Peek`,
  19. // will re-allocate the read buffer in order to accommodate arbitrarily
  20. // large read-ahead. `(*fwd.Reader).Skip` skips the next `n` bytes
  21. // in the stream, and uses the `io.Seeker` interface if the underlying
  22. // stream implements it. `(*fwd.Reader).Next` returns a slice pointing
  23. // to the next `n` bytes in the read buffer (like `Peek`), but also
  24. // increments the read position. This allows users to process streams
  25. // in arbitrary block sizes without having to manage appropriately-sized
  26. // slices. Additionally, obviating the need to copy the data from the
  27. // buffer to another location in memory can improve performance dramatically
  28. // in CPU-bound applications.
  29. //
  30. // `fwd.Writer` only has one extra method, which is `(*fwd.Writer).Next`, which
  31. // returns a slice pointing to the next `n` bytes of the writer, and increments
  32. // the write position by the length of the returned slice. This allows users
  33. // to write directly to the end of the buffer.
  34. //
  35. package fwd
  36. import (
  37. "io"
  38. "os"
  39. )
  40. const (
  41. // DefaultReaderSize is the default size of the read buffer
  42. DefaultReaderSize = 2048
  43. // minimum read buffer; straight from bufio
  44. minReaderSize = 16
  45. )
  46. // NewReader returns a new *Reader that reads from 'r'
  47. func NewReader(r io.Reader) *Reader {
  48. return NewReaderSize(r, DefaultReaderSize)
  49. }
  50. // NewReaderSize returns a new *Reader that
  51. // reads from 'r' and has a buffer size 'n'.
  52. func NewReaderSize(r io.Reader, n int) *Reader {
  53. buf := make([]byte, 0, max(n, minReaderSize))
  54. return NewReaderBuf(r, buf)
  55. }
  56. // NewReaderBuf returns a new *Reader that
  57. // reads from 'r' and uses 'buf' as a buffer.
  58. // 'buf' is not used when has smaller capacity than 16,
  59. // custom buffer is allocated instead.
  60. func NewReaderBuf(r io.Reader, buf []byte) *Reader {
  61. if cap(buf) < minReaderSize {
  62. buf = make([]byte, 0, minReaderSize)
  63. }
  64. buf = buf[:0]
  65. rd := &Reader{
  66. r: r,
  67. data: buf,
  68. }
  69. if s, ok := r.(io.Seeker); ok {
  70. rd.rs = s
  71. }
  72. return rd
  73. }
  74. // Reader is a buffered look-ahead reader
  75. type Reader struct {
  76. r io.Reader // underlying reader
  77. // data[n:len(data)] is buffered data; data[len(data):cap(data)] is free buffer space
  78. data []byte // data
  79. n int // read offset
  80. state error // last read error
  81. // if the reader past to NewReader was
  82. // also an io.Seeker, this is non-nil
  83. rs io.Seeker
  84. }
  85. // Reset resets the underlying reader
  86. // and the read buffer.
  87. func (r *Reader) Reset(rd io.Reader) {
  88. r.r = rd
  89. r.data = r.data[0:0]
  90. r.n = 0
  91. r.state = nil
  92. if s, ok := rd.(io.Seeker); ok {
  93. r.rs = s
  94. } else {
  95. r.rs = nil
  96. }
  97. }
  98. // more() does one read on the underlying reader
  99. func (r *Reader) more() {
  100. // move data backwards so that
  101. // the read offset is 0; this way
  102. // we can supply the maximum number of
  103. // bytes to the reader
  104. if r.n != 0 {
  105. if r.n < len(r.data) {
  106. r.data = r.data[:copy(r.data[0:], r.data[r.n:])]
  107. } else {
  108. r.data = r.data[:0]
  109. }
  110. r.n = 0
  111. }
  112. var a int
  113. a, r.state = r.r.Read(r.data[len(r.data):cap(r.data)])
  114. if a == 0 && r.state == nil {
  115. r.state = io.ErrNoProgress
  116. return
  117. } else if a > 0 && r.state == io.EOF {
  118. // discard the io.EOF if we read more than 0 bytes.
  119. // the next call to Read should return io.EOF again.
  120. r.state = nil
  121. }
  122. r.data = r.data[:len(r.data)+a]
  123. }
  124. // pop error
  125. func (r *Reader) err() (e error) {
  126. e, r.state = r.state, nil
  127. return
  128. }
  129. // pop error; EOF -> io.ErrUnexpectedEOF
  130. func (r *Reader) noEOF() (e error) {
  131. e, r.state = r.state, nil
  132. if e == io.EOF {
  133. e = io.ErrUnexpectedEOF
  134. }
  135. return
  136. }
  137. // buffered bytes
  138. func (r *Reader) buffered() int { return len(r.data) - r.n }
  139. // Buffered returns the number of bytes currently in the buffer
  140. func (r *Reader) Buffered() int { return len(r.data) - r.n }
  141. // BufferSize returns the total size of the buffer
  142. func (r *Reader) BufferSize() int { return cap(r.data) }
  143. // Peek returns the next 'n' buffered bytes,
  144. // reading from the underlying reader if necessary.
  145. // It will only return a slice shorter than 'n' bytes
  146. // if it also returns an error. Peek does not advance
  147. // the reader. EOF errors are *not* returned as
  148. // io.ErrUnexpectedEOF.
  149. func (r *Reader) Peek(n int) ([]byte, error) {
  150. // in the degenerate case,
  151. // we may need to realloc
  152. // (the caller asked for more
  153. // bytes than the size of the buffer)
  154. if cap(r.data) < n {
  155. old := r.data[r.n:]
  156. r.data = make([]byte, n+r.buffered())
  157. r.data = r.data[:copy(r.data, old)]
  158. r.n = 0
  159. }
  160. // keep filling until
  161. // we hit an error or
  162. // read enough bytes
  163. for r.buffered() < n && r.state == nil {
  164. r.more()
  165. }
  166. // we must have hit an error
  167. if r.buffered() < n {
  168. return r.data[r.n:], r.err()
  169. }
  170. return r.data[r.n : r.n+n], nil
  171. }
  172. // discard(n) discards up to 'n' buffered bytes, and
  173. // and returns the number of bytes discarded
  174. func (r *Reader) discard(n int) int {
  175. inbuf := r.buffered()
  176. if inbuf <= n {
  177. r.n = 0
  178. r.data = r.data[:0]
  179. return inbuf
  180. }
  181. r.n += n
  182. return n
  183. }
  184. // Skip moves the reader forward 'n' bytes.
  185. // Returns the number of bytes skipped and any
  186. // errors encountered. It is analogous to Seek(n, 1).
  187. // If the underlying reader implements io.Seeker, then
  188. // that method will be used to skip forward.
  189. //
  190. // If the reader encounters
  191. // an EOF before skipping 'n' bytes, it
  192. // returns io.ErrUnexpectedEOF. If the
  193. // underlying reader implements io.Seeker, then
  194. // those rules apply instead. (Many implementations
  195. // will not return `io.EOF` until the next call
  196. // to Read.)
  197. func (r *Reader) Skip(n int) (int, error) {
  198. if n < 0 {
  199. return 0, os.ErrInvalid
  200. }
  201. // discard some or all of the current buffer
  202. skipped := r.discard(n)
  203. // if we can Seek() through the remaining bytes, do that
  204. if n > skipped && r.rs != nil {
  205. nn, err := r.rs.Seek(int64(n-skipped), 1)
  206. return int(nn) + skipped, err
  207. }
  208. // otherwise, keep filling the buffer
  209. // and discarding it up to 'n'
  210. for skipped < n && r.state == nil {
  211. r.more()
  212. skipped += r.discard(n - skipped)
  213. }
  214. return skipped, r.noEOF()
  215. }
  216. // Next returns the next 'n' bytes in the stream.
  217. // Unlike Peek, Next advances the reader position.
  218. // The returned bytes point to the same
  219. // data as the buffer, so the slice is
  220. // only valid until the next reader method call.
  221. // An EOF is considered an unexpected error.
  222. // If an the returned slice is less than the
  223. // length asked for, an error will be returned,
  224. // and the reader position will not be incremented.
  225. func (r *Reader) Next(n int) ([]byte, error) {
  226. // in case the buffer is too small
  227. if cap(r.data) < n {
  228. old := r.data[r.n:]
  229. r.data = make([]byte, n+r.buffered())
  230. r.data = r.data[:copy(r.data, old)]
  231. r.n = 0
  232. }
  233. // fill at least 'n' bytes
  234. for r.buffered() < n && r.state == nil {
  235. r.more()
  236. }
  237. if r.buffered() < n {
  238. return r.data[r.n:], r.noEOF()
  239. }
  240. out := r.data[r.n : r.n+n]
  241. r.n += n
  242. return out, nil
  243. }
  244. // Read implements `io.Reader`
  245. func (r *Reader) Read(b []byte) (int, error) {
  246. // if we have data in the buffer, just
  247. // return that.
  248. if r.buffered() != 0 {
  249. x := copy(b, r.data[r.n:])
  250. r.n += x
  251. return x, nil
  252. }
  253. var n int
  254. // we have no buffered data; determine
  255. // whether or not to buffer or call
  256. // the underlying reader directly
  257. if len(b) >= cap(r.data) {
  258. n, r.state = r.r.Read(b)
  259. } else {
  260. r.more()
  261. n = copy(b, r.data)
  262. r.n = n
  263. }
  264. if n == 0 {
  265. return 0, r.err()
  266. }
  267. return n, nil
  268. }
  269. // ReadFull attempts to read len(b) bytes into
  270. // 'b'. It returns the number of bytes read into
  271. // 'b', and an error if it does not return len(b).
  272. // EOF is considered an unexpected error.
  273. func (r *Reader) ReadFull(b []byte) (int, error) {
  274. var n int // read into b
  275. var nn int // scratch
  276. l := len(b)
  277. // either read buffered data,
  278. // or read directly for the underlying
  279. // buffer, or fetch more buffered data.
  280. for n < l && r.state == nil {
  281. if r.buffered() != 0 {
  282. nn = copy(b[n:], r.data[r.n:])
  283. n += nn
  284. r.n += nn
  285. } else if l-n > cap(r.data) {
  286. nn, r.state = r.r.Read(b[n:])
  287. n += nn
  288. } else {
  289. r.more()
  290. }
  291. }
  292. if n < l {
  293. return n, r.noEOF()
  294. }
  295. return n, nil
  296. }
  297. // ReadByte implements `io.ByteReader`
  298. func (r *Reader) ReadByte() (byte, error) {
  299. for r.buffered() < 1 && r.state == nil {
  300. r.more()
  301. }
  302. if r.buffered() < 1 {
  303. return 0, r.err()
  304. }
  305. b := r.data[r.n]
  306. r.n++
  307. return b, nil
  308. }
  309. // WriteTo implements `io.WriterTo`
  310. func (r *Reader) WriteTo(w io.Writer) (int64, error) {
  311. var (
  312. i int64
  313. ii int
  314. err error
  315. )
  316. // first, clear buffer
  317. if r.buffered() > 0 {
  318. ii, err = w.Write(r.data[r.n:])
  319. i += int64(ii)
  320. if err != nil {
  321. return i, err
  322. }
  323. r.data = r.data[0:0]
  324. r.n = 0
  325. }
  326. for r.state == nil {
  327. // here we just do
  328. // 1:1 reads and writes
  329. r.more()
  330. if r.buffered() > 0 {
  331. ii, err = w.Write(r.data)
  332. i += int64(ii)
  333. if err != nil {
  334. return i, err
  335. }
  336. r.data = r.data[0:0]
  337. r.n = 0
  338. }
  339. }
  340. if r.state != io.EOF {
  341. return i, r.err()
  342. }
  343. return i, nil
  344. }
  345. func max(a int, b int) int {
  346. if a < b {
  347. return b
  348. }
  349. return a
  350. }