Skip to content

bufio: ReadSlice with size argument #35738

@pascaldekloe

Description

@pascaldekloe

ReadSlice works wonderful with character termination. How to get the same performance and simplicity with size prefixes, i.e. how to read a string with 'n' bytes?

Unless there's a good solution, I'm happy to contribute an implementation of the following.

// ReadSliceSize reads n bytes of input, returning a slice pointing at the bytes
// in the buffer. The bytes stop being valid at the next read. An n value larger
// than the buffer causes an ErrBufferFull, without any I/O.
// When ReadSliceSize encounters an io.EOF after reading some data, but not all,
// then it returns all the data in the buffer with an io.ErrUnexpectedEOF.
// Because the data returned from ReadSliceSize will be overwritten by the next 
// I/O operation, most clients should use Read or WriteTo instead. ReadSliceSize 
// returns err != nil if, and only if, an error occurs before buffering n bytes.
func (r *Reader) ReadSliceSize(n int) ([]byte, error) 
// ReadString demos ReadSliceSize.
func ReadString(r *bufio.Reader) (string, error) {
        sizePrefix, err := r.ReadByte()
        if err != nil {
                return "", err
        }
        slice, err := r.ReadSliceSize(int(sizePrefix))
        if err != nil {
                return "", err
        }
        return string(slice), nil
}

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