Skip to content

bufio: can improve bufio.Scanner and bufio.Reader for bytes.Reader and strings.Reader #11655

@mei-rune

Description

@mei-rune

bufio.Scanner and bufio.Reader will copy all bytes from io.Reader to internal buffer, copy is unnecessary while io.Reader is bytes.Reader or strings.Reader.

now code is

        // NewScanner returns a new Scanner to read from r.
        // The split function defaults to ScanLines.
        func NewScanner(r io.Reader) *Scanner {
            return &Scanner{
                r:            r,
                split:        ScanLines,
                maxTokenSize: MaxScanTokenSize,
                buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
            }
        }

improve code is

        type eofReader struct {}
        func (r *eofReader) Read(p []byte) (n int64, e error) {
                return 0, io.EOF
        }
        var  eof_reader = &eofReader {}
        // NewScanner returns a new Scanner to read from r.
        // The split function defaults to ScanLines.
        func NewScanner(r io.Reader) *Scanner {
            if br, ok := r.(bytes.Reader); ok {
                     return &Scanner{
                        r:            eof_reader,
                        split:        ScanLines,
                        maxTokenSize: MaxScanTokenSize,
                        buf:          br.Bytes(),    // bytes.Reader should add Bytes() method for this.
                    }
            }
            return &Scanner{
                r:            r,
                split:        ScanLines,
                maxTokenSize: MaxScanTokenSize,
                buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
            }
        }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions