buffer.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package runtime
  2. import (
  3. "bufio"
  4. "io"
  5. "net/http"
  6. )
  7. // DefaultBufferSize is the default size of buffers. It is set to 4KB by default, which is the
  8. // same as the default buffer size of bufio.Writer.
  9. var DefaultBufferSize = 4 * 1024 // 4KB
  10. // Buffer is a wrapper around bufio.Writer that enables flushing and closing of
  11. // the underlying writer.
  12. type Buffer struct {
  13. Underlying io.Writer
  14. b *bufio.Writer
  15. }
  16. // Write the contents of p into the buffer.
  17. func (b *Buffer) Write(p []byte) (n int, err error) {
  18. return b.b.Write(p)
  19. }
  20. // Flush writes any buffered data to the underlying io.Writer and
  21. // calls the Flush method of the underlying http.Flusher if it implements it.
  22. func (b *Buffer) Flush() error {
  23. if err := b.b.Flush(); err != nil {
  24. return err
  25. }
  26. if f, ok := b.Underlying.(http.Flusher); ok {
  27. f.Flush()
  28. }
  29. return nil
  30. }
  31. // Close closes the buffer and the underlying io.Writer if it implements io.Closer.
  32. func (b *Buffer) Close() error {
  33. if c, ok := b.Underlying.(io.Closer); ok {
  34. return c.Close()
  35. }
  36. return nil
  37. }
  38. // Reset sets the underlying io.Writer to w and resets the buffer.
  39. func (b *Buffer) Reset(w io.Writer) {
  40. if b.b == nil {
  41. b.b = bufio.NewWriterSize(b, DefaultBufferSize)
  42. }
  43. b.Underlying = w
  44. b.b.Reset(w)
  45. }
  46. // Size returns the size of the underlying buffer in bytes.
  47. func (b *Buffer) Size() int {
  48. return b.b.Size()
  49. }
  50. // WriteString writes the contents of s into the buffer.
  51. func (b *Buffer) WriteString(s string) (n int, err error) {
  52. return b.b.WriteString(s)
  53. }