Alejandro Mery
5 months ago
2 changed files with 74 additions and 3 deletions
@ -0,0 +1,72 @@
|
||||
package tools |
||||
|
||||
import ( |
||||
"bytes" |
||||
"fmt" |
||||
"io" |
||||
) |
||||
|
||||
// LazyBuffer is a [bytes.Buffer] that minimizes counting and error checks.
|
||||
type LazyBuffer bytes.Buffer |
||||
|
||||
// Sys returns the underlying [bytes.Buffer].
|
||||
func (buf *LazyBuffer) Sys() *bytes.Buffer { |
||||
if buf == nil { |
||||
return nil |
||||
} |
||||
return (*bytes.Buffer)(buf) |
||||
} |
||||
|
||||
// Len tells the size in bytes of the currently stored data.
|
||||
func (buf *LazyBuffer) Len() int { return buf.Sys().Len() } |
||||
|
||||
// String returns the stored data as string.
|
||||
func (buf *LazyBuffer) String() string { return buf.Sys().String() } |
||||
|
||||
// Bytes returns the stored data as a bytes slice.
|
||||
func (buf *LazyBuffer) Bytes() []byte { return buf.Sys().Bytes() } |
||||
|
||||
// Write implements the standard io.Writer interface.
|
||||
func (buf *LazyBuffer) Write(b []byte) (int, error) { return buf.Sys().Write(b) } |
||||
|
||||
// WriteTo implements the standard WriteTo() interface.
|
||||
func (buf *LazyBuffer) WriteTo(out io.Writer) (int64, error) { return buf.Sys().WriteTo(out) } |
||||
|
||||
// Print appends the [fmt.Print] equivalent to the buffer.
|
||||
func (buf *LazyBuffer) Print(a ...any) error { |
||||
_, err := fmt.Fprint(buf.Sys(), a...) |
||||
return err |
||||
} |
||||
|
||||
// Println appends the [fmt.Println] equivalent to the buffer.
|
||||
func (buf *LazyBuffer) Println(a ...any) error { |
||||
_, err := fmt.Fprintln(buf.Sys(), a...) |
||||
return err |
||||
} |
||||
|
||||
// Printf appends the [fmt.Printf] equivalent to the buffer.
|
||||
func (buf *LazyBuffer) Printf(format string, a ...any) error { |
||||
_, err := fmt.Fprintf(buf.Sys(), format, a...) |
||||
return err |
||||
} |
||||
|
||||
// WriteRunes appends the given runes as UTF-8 characters to the buffer.
|
||||
func (buf *LazyBuffer) WriteRunes(runes ...rune) { |
||||
for _, r := range runes { |
||||
_, _ = buf.Sys().WriteRune(r) |
||||
} |
||||
} |
||||
|
||||
// WriteBytes writes the given byte arrays to the buffer.
|
||||
func (buf *LazyBuffer) WriteBytes(s ...[]byte) { |
||||
for _, b := range s { |
||||
_, _ = buf.Sys().Write(b) |
||||
} |
||||
} |
||||
|
||||
// WriteStrings writes the given strings as UTF-8 to the buffer.
|
||||
func (buf *LazyBuffer) WriteStrings(strings ...string) { |
||||
for _, s := range strings { |
||||
_, _ = buf.Sys().WriteString(s) |
||||
} |
||||
} |
Loading…
Reference in new issue