reader_writer.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package pool
  2. import (
  3. "errors"
  4. "io"
  5. )
  6. // RWAccount is a function which will be called after every read
  7. // from the RW.
  8. //
  9. // It may return an error which will be passed back to the user.
  10. type RWAccount func(n int) error
  11. // RW contains the state for the read/writer
  12. type RW struct {
  13. pool *Pool // pool to get pages from
  14. pages [][]byte // backing store
  15. size int // size written
  16. out int // offset we are reading from
  17. lastOffset int // size in last page
  18. account RWAccount // account for a read
  19. reads int // count how many times the data has been read
  20. accountOn int // only account on or after this read
  21. }
  22. var (
  23. errInvalidWhence = errors.New("pool.RW Seek: invalid whence")
  24. errNegativeSeek = errors.New("pool.RW Seek: negative position")
  25. errSeekPastEnd = errors.New("pool.RW Seek: attempt to seek past end of data")
  26. )
  27. // NewRW returns a reader / writer which is backed from pages from the
  28. // pool passed in.
  29. //
  30. // Data can be stored in it by calling Write and read from it by
  31. // calling Read.
  32. //
  33. // When writing it only appends data. Seek only applies to reading.
  34. func NewRW(pool *Pool) *RW {
  35. return &RW{
  36. pool: pool,
  37. pages: make([][]byte, 0, 16),
  38. }
  39. }
  40. // SetAccounting should be provided with a function which will be
  41. // called after every read from the RW.
  42. //
  43. // It may return an error which will be passed back to the user.
  44. func (rw *RW) SetAccounting(account RWAccount) *RW {
  45. rw.account = account
  46. return rw
  47. }
  48. // DelayAccountinger enables an accounting delay
  49. type DelayAccountinger interface {
  50. // DelayAccounting makes sure the accounting function only
  51. // gets called on the i-th or later read of the data from this
  52. // point (counting from 1).
  53. //
  54. // This is useful so that we don't account initial reads of
  55. // the data e.g. when calculating hashes.
  56. //
  57. // Set this to 0 to account everything.
  58. DelayAccounting(i int)
  59. }
  60. // DelayAccounting makes sure the accounting function only gets called
  61. // on the i-th or later read of the data from this point (counting
  62. // from 1).
  63. //
  64. // This is useful so that we don't account initial reads of the data
  65. // e.g. when calculating hashes.
  66. //
  67. // Set this to 0 to account everything.
  68. func (rw *RW) DelayAccounting(i int) {
  69. rw.accountOn = i
  70. rw.reads = 0
  71. }
  72. // Returns the page and offset of i for reading.
  73. //
  74. // Ensure there are pages before calling this.
  75. func (rw *RW) readPage(i int) (page []byte) {
  76. // Count a read of the data if we read the first page
  77. if i == 0 {
  78. rw.reads++
  79. }
  80. pageNumber := i / rw.pool.bufferSize
  81. offset := i % rw.pool.bufferSize
  82. page = rw.pages[pageNumber]
  83. // Clip the last page to the amount written
  84. if pageNumber == len(rw.pages)-1 {
  85. page = page[:rw.lastOffset]
  86. }
  87. return page[offset:]
  88. }
  89. // account for n bytes being read
  90. func (rw *RW) accountRead(n int) error {
  91. if rw.account == nil {
  92. return nil
  93. }
  94. // Don't start accounting until we've reached this many reads
  95. //
  96. // rw.reads will be 1 the first time this is called
  97. // rw.accountOn 2 means start accounting on the 2nd read through
  98. if rw.reads >= rw.accountOn {
  99. return rw.account(n)
  100. }
  101. return nil
  102. }
  103. // Read reads up to len(p) bytes into p. It returns the number of
  104. // bytes read (0 <= n <= len(p)) and any error encountered. If some
  105. // data is available but not len(p) bytes, Read returns what is
  106. // available instead of waiting for more.
  107. func (rw *RW) Read(p []byte) (n int, err error) {
  108. var (
  109. nn int
  110. page []byte
  111. )
  112. for len(p) > 0 {
  113. if rw.out >= rw.size {
  114. return n, io.EOF
  115. }
  116. page = rw.readPage(rw.out)
  117. nn = copy(p, page)
  118. p = p[nn:]
  119. n += nn
  120. rw.out += nn
  121. err = rw.accountRead(nn)
  122. if err != nil {
  123. return n, err
  124. }
  125. }
  126. return n, nil
  127. }
  128. // WriteTo writes data to w until there's no more data to write or
  129. // when an error occurs. The return value n is the number of bytes
  130. // written. Any error encountered during the write is also returned.
  131. //
  132. // The Copy function uses WriteTo if available. This avoids an
  133. // allocation and a copy.
  134. func (rw *RW) WriteTo(w io.Writer) (n int64, err error) {
  135. var (
  136. nn int
  137. page []byte
  138. )
  139. for rw.out < rw.size {
  140. page = rw.readPage(rw.out)
  141. nn, err = w.Write(page)
  142. n += int64(nn)
  143. rw.out += nn
  144. if err != nil {
  145. return n, err
  146. }
  147. err = rw.accountRead(nn)
  148. if err != nil {
  149. return n, err
  150. }
  151. }
  152. return n, nil
  153. }
  154. // Get the page we are writing to
  155. func (rw *RW) writePage() (page []byte) {
  156. if len(rw.pages) > 0 && rw.lastOffset < rw.pool.bufferSize {
  157. return rw.pages[len(rw.pages)-1][rw.lastOffset:]
  158. }
  159. page = rw.pool.Get()
  160. rw.pages = append(rw.pages, page)
  161. rw.lastOffset = 0
  162. return page
  163. }
  164. // Write writes len(p) bytes from p to the underlying data stream. It returns
  165. // the number of bytes written len(p). It cannot return an error.
  166. func (rw *RW) Write(p []byte) (n int, err error) {
  167. var (
  168. nn int
  169. page []byte
  170. )
  171. for len(p) > 0 {
  172. page = rw.writePage()
  173. nn = copy(page, p)
  174. p = p[nn:]
  175. n += nn
  176. rw.size += nn
  177. rw.lastOffset += nn
  178. }
  179. return n, nil
  180. }
  181. // ReadFrom reads data from r until EOF or error. The return value n is the
  182. // number of bytes read. Any error except EOF encountered during the read is
  183. // also returned.
  184. //
  185. // The Copy function uses ReadFrom if available. This avoids an
  186. // allocation and a copy.
  187. func (rw *RW) ReadFrom(r io.Reader) (n int64, err error) {
  188. var (
  189. nn int
  190. page []byte
  191. )
  192. for err == nil {
  193. page = rw.writePage()
  194. nn, err = r.Read(page)
  195. n += int64(nn)
  196. rw.size += nn
  197. rw.lastOffset += nn
  198. }
  199. if err == io.EOF {
  200. err = nil
  201. }
  202. return n, err
  203. }
  204. // Seek sets the offset for the next Read (not Write - this is always
  205. // appended) to offset, interpreted according to whence: SeekStart
  206. // means relative to the start of the file, SeekCurrent means relative
  207. // to the current offset, and SeekEnd means relative to the end (for
  208. // example, offset = -2 specifies the penultimate byte of the file).
  209. // Seek returns the new offset relative to the start of the file or an
  210. // error, if any.
  211. //
  212. // Seeking to an offset before the start of the file is an error. Seeking
  213. // beyond the end of the written data is an error.
  214. func (rw *RW) Seek(offset int64, whence int) (int64, error) {
  215. var abs int64
  216. size := int64(rw.size)
  217. switch whence {
  218. case io.SeekStart:
  219. abs = offset
  220. case io.SeekCurrent:
  221. abs = int64(rw.out) + offset
  222. case io.SeekEnd:
  223. abs = size + offset
  224. default:
  225. return 0, errInvalidWhence
  226. }
  227. if abs < 0 {
  228. return 0, errNegativeSeek
  229. }
  230. if abs > size {
  231. return offset - (abs - size), errSeekPastEnd
  232. }
  233. rw.out = int(abs)
  234. return abs, nil
  235. }
  236. // Close the buffer returning memory to the pool
  237. func (rw *RW) Close() error {
  238. for _, page := range rw.pages {
  239. rw.pool.Put(page)
  240. }
  241. rw.pages = nil
  242. return nil
  243. }
  244. // Size returns the number of bytes in the buffer
  245. func (rw *RW) Size() int64 {
  246. return int64(rw.size)
  247. }
  248. // Check interfaces
  249. var (
  250. _ io.Reader = (*RW)(nil)
  251. _ io.ReaderFrom = (*RW)(nil)
  252. _ io.Writer = (*RW)(nil)
  253. _ io.WriterTo = (*RW)(nil)
  254. _ io.Seeker = (*RW)(nil)
  255. _ io.Closer = (*RW)(nil)
  256. _ DelayAccountinger = (*RW)(nil)
  257. )