buffer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright 2009 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 v1
  5. // Simple byte buffer for marshaling data.
  6. import (
  7. "bytes"
  8. "encoding/json"
  9. "errors"
  10. "io"
  11. "unicode/utf8"
  12. )
  13. type grower interface {
  14. Grow(n int)
  15. }
  16. type truncater interface {
  17. Truncate(n int)
  18. Reset()
  19. }
  20. type bytesReader interface {
  21. Bytes() []byte
  22. String() string
  23. }
  24. type runeWriter interface {
  25. WriteRune(r rune) (n int, err error)
  26. }
  27. type stringWriter interface {
  28. WriteString(s string) (n int, err error)
  29. }
  30. type lener interface {
  31. Len() int
  32. }
  33. type rewinder interface {
  34. Rewind(n int) (err error)
  35. }
  36. type encoder interface {
  37. Encode(interface{}) error
  38. }
  39. // TODO(pquerna): continue to reduce these interfaces
  40. type EncodingBuffer interface {
  41. io.Writer
  42. io.WriterTo
  43. io.ByteWriter
  44. stringWriter
  45. truncater
  46. grower
  47. rewinder
  48. encoder
  49. }
  50. type DecodingBuffer interface {
  51. io.ReadWriter
  52. io.ByteWriter
  53. stringWriter
  54. runeWriter
  55. truncater
  56. grower
  57. bytesReader
  58. lener
  59. }
  60. // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
  61. // The zero value for Buffer is an empty buffer ready to use.
  62. type Buffer struct {
  63. buf []byte // contents are the bytes buf[off : len(buf)]
  64. off int // read at &buf[off], write at &buf[len(buf)]
  65. runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
  66. encoder *json.Encoder
  67. skipTrailingByte bool
  68. }
  69. // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
  70. var ErrTooLarge = errors.New("fflib.v1.Buffer: too large")
  71. // Bytes returns a slice of the contents of the unread portion of the buffer;
  72. // len(b.Bytes()) == b.Len(). If the caller changes the contents of the
  73. // returned slice, the contents of the buffer will change provided there
  74. // are no intervening method calls on the Buffer.
  75. func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
  76. // String returns the contents of the unread portion of the buffer
  77. // as a string. If the Buffer is a nil pointer, it returns "<nil>".
  78. func (b *Buffer) String() string {
  79. if b == nil {
  80. // Special case, useful in debugging.
  81. return "<nil>"
  82. }
  83. return string(b.buf[b.off:])
  84. }
  85. // Len returns the number of bytes of the unread portion of the buffer;
  86. // b.Len() == len(b.Bytes()).
  87. func (b *Buffer) Len() int { return len(b.buf) - b.off }
  88. // Truncate discards all but the first n unread bytes from the buffer.
  89. // It panics if n is negative or greater than the length of the buffer.
  90. func (b *Buffer) Truncate(n int) {
  91. if n == 0 {
  92. b.off = 0
  93. b.buf = b.buf[0:0]
  94. } else {
  95. b.buf = b.buf[0 : b.off+n]
  96. }
  97. }
  98. // Reset resets the buffer so it has no content.
  99. // b.Reset() is the same as b.Truncate(0).
  100. func (b *Buffer) Reset() { b.Truncate(0) }
  101. // grow grows the buffer to guarantee space for n more bytes.
  102. // It returns the index where bytes should be written.
  103. // If the buffer can't grow it will panic with ErrTooLarge.
  104. func (b *Buffer) grow(n int) int {
  105. // If we have no buffer, get one from the pool
  106. m := b.Len()
  107. if m == 0 {
  108. if b.buf == nil {
  109. b.buf = makeSlice(2 * n)
  110. b.off = 0
  111. } else if b.off != 0 {
  112. // If buffer is empty, reset to recover space.
  113. b.Truncate(0)
  114. }
  115. }
  116. if len(b.buf)+n > cap(b.buf) {
  117. var buf []byte
  118. if m+n <= cap(b.buf)/2 {
  119. // We can slide things down instead of allocating a new
  120. // slice. We only need m+n <= cap(b.buf) to slide, but
  121. // we instead let capacity get twice as large so we
  122. // don't spend all our time copying.
  123. copy(b.buf[:], b.buf[b.off:])
  124. buf = b.buf[:m]
  125. } else {
  126. // not enough space anywhere
  127. buf = makeSlice(2*cap(b.buf) + n)
  128. copy(buf, b.buf[b.off:])
  129. }
  130. Pool(b.buf)
  131. b.buf = buf
  132. b.off = 0
  133. }
  134. b.buf = b.buf[0 : b.off+m+n]
  135. return b.off + m
  136. }
  137. // Grow grows the buffer's capacity, if necessary, to guarantee space for
  138. // another n bytes. After Grow(n), at least n bytes can be written to the
  139. // buffer without another allocation.
  140. // If n is negative, Grow will panic.
  141. // If the buffer can't grow it will panic with ErrTooLarge.
  142. func (b *Buffer) Grow(n int) {
  143. if n < 0 {
  144. panic("bytes.Buffer.Grow: negative count")
  145. }
  146. m := b.grow(n)
  147. b.buf = b.buf[0:m]
  148. }
  149. // Write appends the contents of p to the buffer, growing the buffer as
  150. // needed. The return value n is the length of p; err is always nil. If the
  151. // buffer becomes too large, Write will panic with ErrTooLarge.
  152. func (b *Buffer) Write(p []byte) (n int, err error) {
  153. if b.skipTrailingByte {
  154. p = p[:len(p)-1]
  155. }
  156. m := b.grow(len(p))
  157. return copy(b.buf[m:], p), nil
  158. }
  159. // WriteString appends the contents of s to the buffer, growing the buffer as
  160. // needed. The return value n is the length of s; err is always nil. If the
  161. // buffer becomes too large, WriteString will panic with ErrTooLarge.
  162. func (b *Buffer) WriteString(s string) (n int, err error) {
  163. m := b.grow(len(s))
  164. return copy(b.buf[m:], s), nil
  165. }
  166. // MinRead is the minimum slice size passed to a Read call by
  167. // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond
  168. // what is required to hold the contents of r, ReadFrom will not grow the
  169. // underlying buffer.
  170. const minRead = 512
  171. // ReadFrom reads data from r until EOF and appends it to the buffer, growing
  172. // the buffer as needed. The return value n is the number of bytes read. Any
  173. // error except io.EOF encountered during the read is also returned. If the
  174. // buffer becomes too large, ReadFrom will panic with ErrTooLarge.
  175. func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
  176. // If buffer is empty, reset to recover space.
  177. if b.off >= len(b.buf) {
  178. b.Truncate(0)
  179. }
  180. for {
  181. if free := cap(b.buf) - len(b.buf); free < minRead {
  182. // not enough space at end
  183. newBuf := b.buf
  184. if b.off+free < minRead {
  185. // not enough space using beginning of buffer;
  186. // double buffer capacity
  187. newBuf = makeSlice(2*cap(b.buf) + minRead)
  188. }
  189. copy(newBuf, b.buf[b.off:])
  190. Pool(b.buf)
  191. b.buf = newBuf[:len(b.buf)-b.off]
  192. b.off = 0
  193. }
  194. m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
  195. b.buf = b.buf[0 : len(b.buf)+m]
  196. n += int64(m)
  197. if e == io.EOF {
  198. break
  199. }
  200. if e != nil {
  201. return n, e
  202. }
  203. }
  204. return n, nil // err is EOF, so return nil explicitly
  205. }
  206. // WriteTo writes data to w until the buffer is drained or an error occurs.
  207. // The return value n is the number of bytes written; it always fits into an
  208. // int, but it is int64 to match the io.WriterTo interface. Any error
  209. // encountered during the write is also returned.
  210. func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
  211. if b.off < len(b.buf) {
  212. nBytes := b.Len()
  213. m, e := w.Write(b.buf[b.off:])
  214. if m > nBytes {
  215. panic("bytes.Buffer.WriteTo: invalid Write count")
  216. }
  217. b.off += m
  218. n = int64(m)
  219. if e != nil {
  220. return n, e
  221. }
  222. // all bytes should have been written, by definition of
  223. // Write method in io.Writer
  224. if m != nBytes {
  225. return n, io.ErrShortWrite
  226. }
  227. }
  228. // Buffer is now empty; reset.
  229. b.Truncate(0)
  230. return
  231. }
  232. // WriteByte appends the byte c to the buffer, growing the buffer as needed.
  233. // The returned error is always nil, but is included to match bufio.Writer's
  234. // WriteByte. If the buffer becomes too large, WriteByte will panic with
  235. // ErrTooLarge.
  236. func (b *Buffer) WriteByte(c byte) error {
  237. m := b.grow(1)
  238. b.buf[m] = c
  239. return nil
  240. }
  241. func (b *Buffer) Rewind(n int) error {
  242. b.buf = b.buf[:len(b.buf)-n]
  243. return nil
  244. }
  245. func (b *Buffer) Encode(v interface{}) error {
  246. if b.encoder == nil {
  247. b.encoder = json.NewEncoder(b)
  248. }
  249. b.skipTrailingByte = true
  250. err := b.encoder.Encode(v)
  251. b.skipTrailingByte = false
  252. return err
  253. }
  254. // WriteRune appends the UTF-8 encoding of Unicode code point r to the
  255. // buffer, returning its length and an error, which is always nil but is
  256. // included to match bufio.Writer's WriteRune. The buffer is grown as needed;
  257. // if it becomes too large, WriteRune will panic with ErrTooLarge.
  258. func (b *Buffer) WriteRune(r rune) (n int, err error) {
  259. if r < utf8.RuneSelf {
  260. b.WriteByte(byte(r))
  261. return 1, nil
  262. }
  263. n = utf8.EncodeRune(b.runeBytes[0:], r)
  264. b.Write(b.runeBytes[0:n])
  265. return n, nil
  266. }
  267. // Read reads the next len(p) bytes from the buffer or until the buffer
  268. // is drained. The return value n is the number of bytes read. If the
  269. // buffer has no data to return, err is io.EOF (unless len(p) is zero);
  270. // otherwise it is nil.
  271. func (b *Buffer) Read(p []byte) (n int, err error) {
  272. if b.off >= len(b.buf) {
  273. // Buffer is empty, reset to recover space.
  274. b.Truncate(0)
  275. if len(p) == 0 {
  276. return
  277. }
  278. return 0, io.EOF
  279. }
  280. n = copy(p, b.buf[b.off:])
  281. b.off += n
  282. return
  283. }
  284. // Next returns a slice containing the next n bytes from the buffer,
  285. // advancing the buffer as if the bytes had been returned by Read.
  286. // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
  287. // The slice is only valid until the next call to a read or write method.
  288. func (b *Buffer) Next(n int) []byte {
  289. m := b.Len()
  290. if n > m {
  291. n = m
  292. }
  293. data := b.buf[b.off : b.off+n]
  294. b.off += n
  295. return data
  296. }
  297. // ReadByte reads and returns the next byte from the buffer.
  298. // If no byte is available, it returns error io.EOF.
  299. func (b *Buffer) ReadByte() (c byte, err error) {
  300. if b.off >= len(b.buf) {
  301. // Buffer is empty, reset to recover space.
  302. b.Truncate(0)
  303. return 0, io.EOF
  304. }
  305. c = b.buf[b.off]
  306. b.off++
  307. return c, nil
  308. }
  309. // ReadRune reads and returns the next UTF-8-encoded
  310. // Unicode code point from the buffer.
  311. // If no bytes are available, the error returned is io.EOF.
  312. // If the bytes are an erroneous UTF-8 encoding, it
  313. // consumes one byte and returns U+FFFD, 1.
  314. func (b *Buffer) ReadRune() (r rune, size int, err error) {
  315. if b.off >= len(b.buf) {
  316. // Buffer is empty, reset to recover space.
  317. b.Truncate(0)
  318. return 0, 0, io.EOF
  319. }
  320. c := b.buf[b.off]
  321. if c < utf8.RuneSelf {
  322. b.off++
  323. return rune(c), 1, nil
  324. }
  325. r, n := utf8.DecodeRune(b.buf[b.off:])
  326. b.off += n
  327. return r, n, nil
  328. }
  329. // ReadBytes reads until the first occurrence of delim in the input,
  330. // returning a slice containing the data up to and including the delimiter.
  331. // If ReadBytes encounters an error before finding a delimiter,
  332. // it returns the data read before the error and the error itself (often io.EOF).
  333. // ReadBytes returns err != nil if and only if the returned data does not end in
  334. // delim.
  335. func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
  336. slice, err := b.readSlice(delim)
  337. // return a copy of slice. The buffer's backing array may
  338. // be overwritten by later calls.
  339. line = append(line, slice...)
  340. return
  341. }
  342. // readSlice is like ReadBytes but returns a reference to internal buffer data.
  343. func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
  344. i := bytes.IndexByte(b.buf[b.off:], delim)
  345. end := b.off + i + 1
  346. if i < 0 {
  347. end = len(b.buf)
  348. err = io.EOF
  349. }
  350. line = b.buf[b.off:end]
  351. b.off = end
  352. return line, err
  353. }
  354. // ReadString reads until the first occurrence of delim in the input,
  355. // returning a string containing the data up to and including the delimiter.
  356. // If ReadString encounters an error before finding a delimiter,
  357. // it returns the data read before the error and the error itself (often io.EOF).
  358. // ReadString returns err != nil if and only if the returned data does not end
  359. // in delim.
  360. func (b *Buffer) ReadString(delim byte) (line string, err error) {
  361. slice, err := b.readSlice(delim)
  362. return string(slice), err
  363. }
  364. // NewBuffer creates and initializes a new Buffer using buf as its initial
  365. // contents. It is intended to prepare a Buffer to read existing data. It
  366. // can also be used to size the internal buffer for writing. To do that,
  367. // buf should have the desired capacity but a length of zero.
  368. //
  369. // In most cases, new(Buffer) (or just declaring a Buffer variable) is
  370. // sufficient to initialize a Buffer.
  371. func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
  372. // NewBufferString creates and initializes a new Buffer using string s as its
  373. // initial contents. It is intended to prepare a buffer to read an existing
  374. // string.
  375. //
  376. // In most cases, new(Buffer) (or just declaring a Buffer variable) is
  377. // sufficient to initialize a Buffer.
  378. func NewBufferString(s string) *Buffer {
  379. return &Buffer{buf: []byte(s)}
  380. }