reader.go 9.5 KB

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