buffer.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package core
  2. import "strconv"
  3. const _size = 1024 // by default, create 1 KiB buffers
  4. // NewBuffer is new buffer
  5. func NewBuffer(_size int) *Buffer {
  6. return &Buffer{bs: make([]byte, 0, _size)}
  7. }
  8. // Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so
  9. // the only way to construct one is via a Pool.
  10. type Buffer struct {
  11. bs []byte
  12. pool Pool
  13. }
  14. // AppendByte writes a single byte to the Buffer.
  15. func (b *Buffer) AppendByte(v byte) {
  16. b.bs = append(b.bs, v)
  17. }
  18. // AppendString writes a string to the Buffer.
  19. func (b *Buffer) AppendString(s string) {
  20. b.bs = append(b.bs, s...)
  21. }
  22. // AppendInt appends an integer to the underlying buffer (assuming base 10).
  23. func (b *Buffer) AppendInt(i int64) {
  24. b.bs = strconv.AppendInt(b.bs, i, 10)
  25. }
  26. // AppendUint appends an unsigned integer to the underlying buffer (assuming
  27. // base 10).
  28. func (b *Buffer) AppendUint(i uint64) {
  29. b.bs = strconv.AppendUint(b.bs, i, 10)
  30. }
  31. // AppendBool appends a bool to the underlying buffer.
  32. func (b *Buffer) AppendBool(v bool) {
  33. b.bs = strconv.AppendBool(b.bs, v)
  34. }
  35. // AppendFloat appends a float to the underlying buffer. It doesn't quote NaN
  36. // or +/- Inf.
  37. func (b *Buffer) AppendFloat(f float64, bitSize int) {
  38. b.bs = strconv.AppendFloat(b.bs, f, 'f', -1, bitSize)
  39. }
  40. // Len returns the length of the underlying byte slice.
  41. func (b *Buffer) Len() int {
  42. return len(b.bs)
  43. }
  44. // Cap returns the capacity of the underlying byte slice.
  45. func (b *Buffer) Cap() int {
  46. return cap(b.bs)
  47. }
  48. // Bytes returns a mutable reference to the underlying byte slice.
  49. func (b *Buffer) Bytes() []byte {
  50. return b.bs
  51. }
  52. // String returns a string copy of the underlying byte slice.
  53. func (b *Buffer) String() string {
  54. return string(b.bs)
  55. }
  56. // Reset resets the underlying byte slice. Subsequent writes re-use the slice's
  57. // backing array.
  58. func (b *Buffer) Reset() {
  59. b.bs = b.bs[:0]
  60. }
  61. // Write implements io.Writer.
  62. func (b *Buffer) Write(bs []byte) (int, error) {
  63. b.bs = append(b.bs, bs...)
  64. return len(bs), nil
  65. }
  66. // TrimNewline trims any final "\n" byte from the end of the buffer.
  67. func (b *Buffer) TrimNewline() {
  68. if i := len(b.bs) - 1; i >= 0 {
  69. if b.bs[i] == '\n' {
  70. b.bs = b.bs[:i]
  71. }
  72. }
  73. }
  74. // Free returns the Buffer to its Pool.
  75. //
  76. // Callers must not retain references to the Buffer after calling Free.
  77. func (b *Buffer) Free() {
  78. b.pool.put(b)
  79. }