Support piping data in

This allows using someone else's data to compare runtimes, behavior, etc. without having to recompile. Since it's patched into the function that all days use to read, it's incompatible with running all days, which I feel is a reasonable compromise and behavior expectation.

The Mode() check is how the internet says you can test if you should even try to look at stdin, and the Size() check ensures that there's actually data to be read instead of just an open stdin handle (running in VSCode with a debugger seems to keep the stdin handle open, for example, so it passes the Mode() check and then hangs when trying to read since there's nothing to actually read).
This commit is contained in:
2022-06-10 09:38:50 -05:00
parent c9cfffcc1c
commit 731e991f1f

View File

@ -3,18 +3,33 @@ package utilities
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io"
"os"
"strconv" "strconv"
"parnic.com/aoc2019/inputs" "parnic.com/aoc2019/inputs"
) )
func getData(filename string, lineHandler func(line string)) { func getData(filename string, lineHandler func(line string)) {
file, err := inputs.Sets.Open(fmt.Sprintf("%s.txt", filename)) var err error
// version that doesn't use embedded files: stdinStat, err := os.Stdin.Stat()
// file, err := os.Open(fmt.Sprintf("inputs/%s.txt", filename))
if err != nil { if err != nil {
panic(err) panic(err)
} }
var file io.ReadCloser
if (stdinStat.Mode()&os.ModeCharDevice) == 0 && stdinStat.Size() > 0 {
file = os.Stdin
} else {
file, err = inputs.Sets.Open(fmt.Sprintf("%s.txt", filename))
// version that doesn't use embedded files:
// file, err := os.Open(fmt.Sprintf("inputs/%s.txt", filename))
if err != nil {
panic(err)
}
}
defer file.Close() defer file.Close()
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)