Skip to content

proposal: bytes, strings: add ReadBytes(byte) ([]byte, error), ReadString(byte) (string, error) to Reader #13889

@hirochachacha

Description

@hirochachacha

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.

  1. it still need to keep data variable.
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions