summaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/a-h/templ/runtime/buffer.go
blob: 63e4acd8c6bc35f89ccd8980af87cc28f84191d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package runtime

import (
	"bufio"
	"io"
	"net/http"
)

// DefaultBufferSize is the default size of buffers. It is set to 4KB by default, which is the
// same as the default buffer size of bufio.Writer.
var DefaultBufferSize = 4 * 1024 // 4KB

// Buffer is a wrapper around bufio.Writer that enables flushing and closing of
// the underlying writer.
type Buffer struct {
	Underlying io.Writer
	b          *bufio.Writer
}

// Write the contents of p into the buffer.
func (b *Buffer) Write(p []byte) (n int, err error) {
	return b.b.Write(p)
}

// Flush writes any buffered data to the underlying io.Writer and
// calls the Flush method of the underlying http.Flusher if it implements it.
func (b *Buffer) Flush() error {
	if err := b.b.Flush(); err != nil {
		return err
	}
	if f, ok := b.Underlying.(http.Flusher); ok {
		f.Flush()
	}
	return nil
}

// Close closes the buffer and the underlying io.Writer if it implements io.Closer.
func (b *Buffer) Close() error {
	if c, ok := b.Underlying.(io.Closer); ok {
		return c.Close()
	}
	return nil
}

// Reset sets the underlying io.Writer to w and resets the buffer.
func (b *Buffer) Reset(w io.Writer) {
	if b.b == nil {
		b.b = bufio.NewWriterSize(b, DefaultBufferSize)
	}
	b.Underlying = w
	b.b.Reset(w)
}

// Size returns the size of the underlying buffer in bytes.
func (b *Buffer) Size() int {
	return b.b.Size()
}

// WriteString writes the contents of s into the buffer.
func (b *Buffer) WriteString(s string) (n int, err error) {
	return b.b.WriteString(s)
}