2019-09-16 09:18:13 +00:00
|
|
|
package io
|
2019-09-15 11:58:19 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
)
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// ErrDrained is returned on an attempt to use an already drained write buffer.
|
2021-08-20 07:58:51 +00:00
|
|
|
var ErrDrained = errors.New("buffer already drained")
|
|
|
|
|
2019-09-15 11:58:19 +00:00
|
|
|
// BufBinWriter is an additional layer on top of BinWriter that
|
2022-04-20 18:30:09 +00:00
|
|
|
// automatically creates a buffer to write into that you can get after all
|
2019-09-15 11:58:19 +00:00
|
|
|
// writes via Bytes().
|
|
|
|
type BufBinWriter struct {
|
|
|
|
*BinWriter
|
2021-08-20 08:38:42 +00:00
|
|
|
buf bytes.Buffer
|
2019-09-15 11:58:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBufBinWriter makes a BufBinWriter with an empty byte buffer.
|
|
|
|
func NewBufBinWriter() *BufBinWriter {
|
2021-08-20 08:38:42 +00:00
|
|
|
b := new(BufBinWriter)
|
|
|
|
b.BinWriter = NewBinWriterFromIO(&b.buf)
|
|
|
|
return b
|
2019-09-15 11:58:19 +00:00
|
|
|
}
|
|
|
|
|
2019-11-22 10:06:32 +00:00
|
|
|
// Len returns the number of bytes of the unread portion of the buffer.
|
|
|
|
func (bw *BufBinWriter) Len() int {
|
|
|
|
return bw.buf.Len()
|
|
|
|
}
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// Bytes returns the resulting buffer and makes future writes return an error.
|
2024-11-05 13:58:11 +00:00
|
|
|
// Subsequent calls to it will return nil. You can reuse this instance of
|
|
|
|
// [BufBinWriter] after [BufBinWriter.Reset].
|
2019-09-15 11:58:19 +00:00
|
|
|
func (bw *BufBinWriter) Bytes() []byte {
|
|
|
|
if bw.Err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
2021-08-20 07:58:51 +00:00
|
|
|
bw.Err = ErrDrained
|
2019-09-15 11:58:19 +00:00
|
|
|
return bw.buf.Bytes()
|
|
|
|
}
|
2019-09-16 09:18:13 +00:00
|
|
|
|
|
|
|
// Reset resets the state of the buffer, making it usable again. It can
|
2022-04-20 18:30:09 +00:00
|
|
|
// make buffer usage somewhat more efficient because you don't need to
|
|
|
|
// create it again. But beware, the buffer is gonna be the same as the one
|
2019-09-16 09:18:13 +00:00
|
|
|
// returned by Bytes(), so if you need that data after Reset() you have to copy
|
|
|
|
// it yourself.
|
|
|
|
func (bw *BufBinWriter) Reset() {
|
|
|
|
bw.Err = nil
|
|
|
|
bw.buf.Reset()
|
|
|
|
}
|