Skip to content

Bound Input Before You Parse

The Course
•
24 min study

A program that reads input from someone else must decide how much it is willing to read. Without a limit, one enormous line or an endless stream can use all the memory there is. A good limit is stated in the documentation, enforced before any parsing happens, and tested exactly at its edge, because "about 200 bytes" is not a promise anyone can check. The ledger accepts lines of at most 200 bytes and at most 1000 commands, and rejects the whole input if either limit is broken.

bufio.Scanner already has a limit: by default it refuses lines longer than 64 KiB, and scanner.Err() then returns bufio.ErrTooLong. scanner.Buffer(buf, max) sets your own maximum. There is a catch, though, and it is the reason this lesson exists.

Predict and run

The maximum is 8 bytes. Each input line below has 8 characters before its newline. Which lines are read?

Predict, then run Go
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(strings.NewReader("tent:123\ndrill:12\nhat:1"))
	scanner.Buffer(make([]byte, 0, 8), 8)
	for scanner.Scan() {
		fmt.Printf("read %q\n", scanner.Text())
	}
	fmt.Println("error:", scanner.Err())
}
Check your prediction
Text
error: bufio.Scanner: token too long

Nothing was read. A scanner only returns a line that is shorter than its buffer, whether or not the line ends with a newline. With room for 8 bytes, the longest line it accepts has 7. The rule is simple once you know it, but nothing in the method name suggests it, and "a maximum of 8" sounds like it should accept 8. Change both 8s to 9 and run again: now both 8-character lines are read, and so is hat:1.

Make the limit exact

So to accept lines of up to maxLine bytes, give the buffer maxLine+1, and state the limit once as a constant. The scanner's own ErrTooLong then enforces the rule exactly, and the function only translates it into an error that names the line. Since it reads lines in order, the line that was too long is always the one after the last line it returned.

An exact line limit Go
package main

import (
	"bufio"
	"errors"
	"fmt"
	"strings"
)

const maxLine = 8

var errTooLong = errors.New("line is longer than 8 bytes")

func readLines(input string) ([]string, error) {
	scanner := bufio.NewScanner(strings.NewReader(input))
	scanner.Buffer(make([]byte, 0, maxLine+1), maxLine+1)
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		if errors.Is(err, bufio.ErrTooLong) {
			return nil, fmt.Errorf("line %d: %w", len(lines)+1, errTooLong)
		}
		return nil, err
	}
	return lines, nil
}

func main() {
	for _, input := range []string{"tent:123\ndrill:12", "tent:123\nlantern:1", "tent:123\nlantern:12\nhat:1"} {
		fmt.Println(readLines(input))
	}
}
Text
[tent:123 drill:12] <nil>
[] line 2: line is longer than 8 bytes
[] line 2: line is longer than 8 bytes

The second input ends with a 9-byte line and no newline; the third has a 10-byte line followed by one. Both are rejected at line 2, so the rule does not depend on how the input ends. Note that len counts bytes, not characters: 短編 is 6 bytes long, so a limit in bytes is also a limit on memory.

The initial buffer counts too

Buffer takes two sizes: the slice you pass is where the scanner starts, and the maximum is how far it may grow. The real limit is the larger of the two. Pass a roomy 64-byte slice with a maximum of 9, and the scanner never needs to grow, so it reads a 9-byte line it was supposed to refuse.

A larger starting buffer raises the limit Go
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(strings.NewReader("lantern:1\n"))
	scanner.Buffer(make([]byte, 0, 64), 9)
	for scanner.Scan() {
		fmt.Printf("read %q\n", scanner.Text())
	}
	fmt.Println("error:", scanner.Err())
}
Text
read "lantern:1"
error: <nil>

The project's first draft made exactly this mistake. It started with a 256-byte buffer, so a separate length check was quietly doing all the work. Using the same size for both arguments makes the buffer enforce the limit by itself.

Count limits and all-or-nothing input

A second limit bounds the number of lines. It is checked with the count of lines already accepted, and the boundary is just as easy to get wrong: len(lines) == max must reject the next line, so exactly max lines pass. The ledger reads every line before it applies any command. That costs memory, which the two limits keep bounded, but it means input that breaks a limit is rejected as a whole, and a half-applied input never happens. A program that must handle unlimited streams would instead process each line as it arrives and give up all-or-nothing input.

Test the limit and one past it

For every limit, write one check exactly at the limit and one just past it, with and without a final newline. In the project, checkLimits does this for the 200-byte line and the 1000-command input, and the course's mutation tests prove that moving either boundary by one is caught.

Practice

Exercise

Your turn

Write readCommands(input string, maxLines int) ([]string, error). Skip blank lines, which do not count toward the limit. Return errTooMany, wrapped with the line number, when a non-blank line would be number maxLines + 1. Check a limit of 2 with three inputs: two commands with a blank line between them, the same plus a trailing blank line, and three commands.

The output should be:

Text
[report report] <nil>
[report report] <nil>
[] line 3: too many commands
Your working space Go
package main

func main() {
	// Write readCommands, then check the three inputs.
}
Hint 1: the idea

Check the count when a non-blank line arrives, before appending it. Blank lines never reach the check.

Hint 2: a first step

After trimming, write if len(commands) == maxLines and return the error. Keep a separate counter for the line number, so the message points at the original line.

Worked solution
Run the solution Go
package main

import (
	"bufio"
	"errors"
	"fmt"
	"strings"
)

var errTooMany = errors.New("too many commands")

func readCommands(input string, maxLines int) ([]string, error) {
	scanner := bufio.NewScanner(strings.NewReader(input))
	var commands []string
	for number := 1; scanner.Scan(); number++ {
		text := strings.TrimSpace(scanner.Text())
		if text == "" {
			continue
		}
		if len(commands) == maxLines {
			return nil, fmt.Errorf("line %d: %w", number, errTooMany)
		}
		commands = append(commands, text)
	}
	return commands, scanner.Err()
}

func main() {
	fmt.Println(readCommands("report\n\nreport", 2))
	fmt.Println(readCommands("report\n\nreport\n\n", 2))
	fmt.Println(readCommands("report\nreport\nreport", 2))
}
Text
[report report] <nil>
[report report] <nil>
[] line 3: too many commands

Exactly two commands pass with or without trailing blank lines, and the third is rejected with its own line number. Writing len(commands) > maxLines instead would let a third command through, which is the mutation the project's checks are built to catch.

Was this article helpful?

Your response is saved on this device.