/
file_parser.go
87 lines (83 loc) · 1.73 KB
/
file_parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package file_parser
import (
"bufio"
"bytes"
"errors"
"io"
"strconv"
"strings"
)
func ParseData(r io.Reader) ([]string, error) {
s := bufio.NewScanner(r)
if !s.Scan() {
return nil, errors.New("empty")
}
countStr := s.Text()
count, err := strconv.Atoi(countStr)
if err != nil {
return nil, err
}
out := make([]string, 0, count)
for i := 0; i < count; i++ {
hasLine := s.Scan()
if !hasLine {
return nil, errors.New("too few lines")
}
line := s.Text()
out = append(out, line)
}
return out, nil
}
// ParseDataFixed has the fixes for the problems
// found by fuzzing ParseData. Copy the specified lines to
// ParseData to see the fuzzing tests pass.
func ParseDataFixed(r io.Reader) ([]string, error) {
// first line is number of lines
s := bufio.NewScanner(r)
if !s.Scan() {
return nil, errors.New("empty")
}
countStr := s.Text()
count, err := strconv.Atoi(countStr)
if err != nil {
return nil, err
}
// test 1 fix start
if count > 1000 {
return nil, errors.New("too many")
}
// test 1 fix end
// test 2 fix start
if count < 0 {
return nil, errors.New("no negative numbers")
}
// test 2 fix end
out := make([]string, 0, count)
// each following line is an entry in the slice
for i := 0; i < count; i++ {
hasLine := s.Scan()
if !hasLine {
return nil, errors.New("too few lines")
}
line := s.Text()
// test 3 fix start
line = strings.TrimSpace(line)
if len(line) == 0 {
return nil, errors.New("blank line")
}
// test 3 fix end
out = append(out, line)
}
// return the slice
return out, nil
}
func ToData(s []string) []byte {
var b bytes.Buffer
b.WriteString(strconv.Itoa(len(s)))
b.WriteRune('\n')
for _, v := range s {
b.WriteString(v)
b.WriteRune('\n')
}
return b.Bytes()
}