-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatland.go
75 lines (58 loc) · 1.27 KB
/
flatland.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
package flatland
import (
"bufio"
"errors"
"io"
)
var (
ErrInvalidRecordLength = errors.New("record is invalid length for template")
)
// A Reader reads records from a fixed width encoded file using a given struct
// as a template
type Reader struct {
*bufio.Scanner
Template [][]int
empty bool
eor bool
}
// NewReader returns a new Reader that reads from r
func NewReader(r io.Reader, template [][]int) *Reader {
return &Reader{bufio.NewScanner(r), template, false, false}
}
func (r *Reader) ScanAll() ([][]string, error) {
var objs [][]string
for r.Scan() {
obj, err := r.ParseRecord()
if err != nil {
return nil, err
}
objs = append(objs, obj)
}
return objs, nil
}
func (r *Reader) ScanLine() ([]string, error) {
r.Scan()
obj, err := r.ParseRecord()
if err != nil {
return nil, err
}
return obj, nil
}
func (r *Reader) EmptyLine() bool {
return r.empty && r.eor
}
func (r *Reader) EndOfRecord() bool {
return r.eor
}
func (r *Reader) ParseRecord() ([]string, error) {
line := r.Text()
record := []string{}
for _, coords := range r.Template {
if len(line) < coords[0] || len(line) < coords[1] {
return nil, ErrInvalidRecordLength
}
value := line[coords[0]-1 : coords[1]]
record = append(record, value)
}
return record, nil
}