Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bufio: ReadSlice with size argument #35738

Closed
pascaldekloe opened this issue Nov 21, 2019 · 1 comment
Closed

bufio: ReadSlice with size argument #35738

pascaldekloe opened this issue Nov 21, 2019 · 1 comment

Comments

@pascaldekloe
Copy link
Contributor

pascaldekloe commented Nov 21, 2019

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
}
@pascaldekloe pascaldekloe changed the title bufio: Reader bufio: ReadSlice with size argument Nov 21, 2019
@pascaldekloe
Copy link
Contributor Author

Usecase already covered with Peek and Discard. Thanks anonymous! 🙂

@golang golang locked and limited conversation to collaborators Nov 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants