-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerators.go
98 lines (83 loc) · 2.46 KB
/
generators.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
88
89
90
91
92
93
94
95
96
97
98
package main
// -----------------------------------------------------------------------------
// Imports
// -----------------------------------------------------------------------------
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
)
// -----------------------------------------------------------------------------
// ReportGenerator
// -----------------------------------------------------------------------------
type ReportGenerator interface {
Generate(fp *os.File) (Report, error)
}
// -----------------------------------------------------------------------------
// ReportGeneratorNaive
// -----------------------------------------------------------------------------
type ReportGeneratorNaive struct {
}
func (self ReportGeneratorNaive) Generate(fp *os.File) (Report, error) {
byteValue, err := ioutil.ReadAll(fp)
if err != nil {
return nil, err
}
Checkpoint("json readed")
var transactions []Transaction
err = json.Unmarshal(byteValue, &transactions)
if err != nil {
return nil, err
}
Checkpoint("json parsed")
report := make(Report)
for i := 0; i < len(transactions); i++ {
report.Update(transactions[i])
}
return report, nil
}
// -----------------------------------------------------------------------------
// ReportGeneratorStream
// -----------------------------------------------------------------------------
type ReportGeneratorStream struct {
}
func (self ReportGeneratorStream) Generate(fp *os.File) (Report, error) {
report := make(Report)
decoder := json.NewDecoder(fp)
token, err := decoder.Token()
if err != nil {
return nil, err
}
if delim, ok := token.(json.Delim); !ok || delim != '[' {
return nil, errors.New("expected [")
}
for decoder.More() {
transaction := Transaction{}
err := decoder.Decode(&transaction)
if err != nil {
return nil, err
}
report.Update(transaction)
}
token, err = decoder.Token()
if err != nil {
return nil, err
}
if delim, ok := token.(json.Delim); !ok || delim != ']' {
return nil, errors.New("expected ]")
}
return report, nil
}
// -----------------------------------------------------------------------------
// CreateReportGenerator
// -----------------------------------------------------------------------------
func CreateReportGenerator(algorithm string) (ReportGenerator, error) {
if "naive" == algorithm {
return new(ReportGeneratorNaive), nil
}
if "stream" == algorithm {
return new(ReportGeneratorStream), nil
}
return nil, errors.New("unknown algorithm: " + algorithm)
}