writer.go 873 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package bytes
  2. // Writer writer.
  3. type Writer struct {
  4. n int
  5. buf []byte
  6. }
  7. // NewWriterSize new a writer with size.
  8. func NewWriterSize(n int) *Writer {
  9. return &Writer{buf: make([]byte, n)}
  10. }
  11. // Len buff len.
  12. func (w *Writer) Len() int {
  13. return w.n
  14. }
  15. // Size buff cap.
  16. func (w *Writer) Size() int {
  17. return len(w.buf)
  18. }
  19. // Reset reset the buff.
  20. func (w *Writer) Reset() {
  21. w.n = 0
  22. }
  23. // Buffer return buff.
  24. func (w *Writer) Buffer() []byte {
  25. return w.buf[:w.n]
  26. }
  27. // Peek peek a buf.
  28. func (w *Writer) Peek(n int) []byte {
  29. var buf []byte
  30. w.grow(n)
  31. buf = w.buf[w.n : w.n+n]
  32. w.n += n
  33. return buf
  34. }
  35. // Write write a buff.
  36. func (w *Writer) Write(p []byte) {
  37. w.grow(len(p))
  38. w.n += copy(w.buf[w.n:], p)
  39. }
  40. func (w *Writer) grow(n int) {
  41. var buf []byte
  42. if w.n+n < len(w.buf) {
  43. return
  44. }
  45. buf = make([]byte, 2*len(w.buf)+n)
  46. copy(buf, w.buf[:w.n])
  47. w.buf = buf
  48. }