-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
87 lines (68 loc) · 2.04 KB
/
export.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 hibp
import (
"bufio"
"bytes"
"fmt"
"io"
)
// The upstream Have-I-Been-Pwned API uses CRLF as line separator - so we are stuck with it,
// although it does not feel right.
var lineSeparator = []byte("\r\n")
func export(from, to int64, store storage, w io.Writer) error {
for i := from; i < to; i++ {
err := func() error {
rangePrefix := toRangeString(i)
dataReader, err := store.LoadData(rangePrefix)
if err != nil {
return fmt.Errorf("loading data for range %q: %w", rangePrefix, err)
}
defer dataReader.Close()
lines, err := io.ReadAll(dataReader)
if err != nil {
return fmt.Errorf("reading data for range %q: %w", rangePrefix, err)
}
prefixedLines, err := prefixLines(lines, rangePrefix)
if err != nil {
return fmt.Errorf("prefixing lines for range %q: %w", rangePrefix, err)
}
if _, err := w.Write(prefixedLines); err != nil {
return fmt.Errorf("writing data for range %q: %w", rangePrefix, err)
}
if i+1 < to {
if _, err := w.Write(lineSeparator); err != nil {
return fmt.Errorf("writing line separator to export writer: %w", err)
}
}
return nil
}()
if err != nil {
return err
}
}
if closer, ok := w.(io.Closer); ok {
return closer.Close()
}
return nil
}
func prefixLines(in []byte, prefix string) ([]byte, error) {
firstLine := true
// Actually, we know that the size will be: len(in) + rows * len(prefix)
// But we do not know the number of rows - so starting from len(in) seems to be a good choice.
out := bytes.NewBuffer(make([]byte, 0, len(in)))
scanner := bufio.NewScanner(bytes.NewReader(in))
for scanner.Scan() {
if !firstLine {
if _, err := out.Write(lineSeparator); err != nil {
return nil, fmt.Errorf("adding line separator: %w", err)
}
}
firstLine = false
if _, err := out.Write([]byte(prefix)); err != nil {
return nil, fmt.Errorf("adding prefix: %w", err)
}
if _, err := out.Write(scanner.Bytes()); err != nil {
return nil, fmt.Errorf("adding suffix and counter: %w", err)
}
}
return out.Bytes(), nil
}