One of the use-cases of byte.Reader is parsing a binary format.
There are some formats use an unpredictable length structure such as NUL-terminated string.
Unfortunately, current API set doesn't treat it well.
For example:
br := byte.NewReader(data)
func decodeCString(br *bytes.Reader, data []byte) string {
rest := data[br.Size()-br.Len():]
i := bytes.IndexByte(rest, 0x0)
if i == -1 {
panic("invalid")
}
br.Seek(i+1, 1)
return string(rest[:i])
}
I think decodeCString has 2 problems.
- it still need to keep
data variable.
- it manually update internal state by
.Size, .Len and .Seek.
I want to write it like this:
func decodeCString(br *bytes.Reader) string {
bs, err := br.ReadBytes(0x0)
if err != nil {
panic("invalid")
}
return string(bs[:len(bs)-1])
}
I know some people prefer bytes.Buffer because of convenience, even if data is read only.
I want to discourage such a situation.
Same things are also applicable to strings.Reader.
Thank you.
hiro