-
Notifications
You must be signed in to change notification settings - Fork 3
/
composed.go
108 lines (96 loc) · 2.43 KB
/
composed.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
99
100
101
102
103
104
105
106
107
108
package accumulators
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/go-sif/sif"
)
// composed composes other Accumulators
type composed struct {
accs []sif.Accumulator
}
// Accumulate adds a row to all contained Accumulators
func (c *composed) Accumulate(row sif.Row) error {
for _, a := range c.accs {
err := a.Accumulate(row)
if err != nil {
return err
}
}
return nil
}
// Merge merges another Composed Accumulator into this one, merging all contained Accumulators
func (c *composed) Merge(o sif.Accumulator) error {
compa, ok := o.(*composed)
if !ok {
return fmt.Errorf("incoming accumulator is not a Composed Accumulator")
}
for i, a := range c.accs {
err := a.Merge(compa.accs[i])
if err != nil {
return err
}
}
return nil
}
// ToBytes serializes this Accumulator
func (c *composed) ToBytes() ([]byte, error) {
result := make([][]byte, len(c.accs))
for i, a := range c.accs {
buff, err := a.ToBytes()
if err != nil {
return nil, err
}
result[i] = buff
}
buff := new(bytes.Buffer)
e := gob.NewEncoder(buff)
err := e.Encode(result)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
// FromBytes produce a new Accumulator from serialized data
func (c *composed) FromBytes(buff []byte) (sif.Accumulator, error) {
var deser [][]byte
d := gob.NewDecoder(bytes.NewBuffer(buff))
err := d.Decode(&deser)
if err != nil {
return nil, err
}
newAcs := make([]sif.Accumulator, len(c.accs))
for i, b := range deser {
a, err := c.accs[i].FromBytes(b)
if err != nil {
return nil, err
}
newAcs[i] = a
}
return &composed{accs: newAcs}, nil
}
// Value returns the contained Accumulators, so that their results may be accessed
func (c *composed) Value() []sif.Accumulator {
return c.accs
}
type composedFactory struct {
faccs []sif.AccumulatorFactory
}
func (f *composedFactory) New() sif.Accumulator {
accs := make([]sif.Accumulator, 0, len(f.faccs))
for _, facc := range f.faccs {
accs = append(accs, facc.New())
}
return &composed{accs}
}
func (f *composedFactory) Value(acc sif.Accumulator) ([]sif.Accumulator, error) {
tacc, ok := acc.(sif.GenericAccumulator[[]sif.Accumulator])
if !ok {
return nil, fmt.Errorf("provided accumulator was not a Composed accumulator")
}
return tacc.Value(), nil
}
// Compose returns a new Composed AccumulatorFactory
func Compose(faccs ...sif.AccumulatorFactory) sif.GenericAccumulatorFactory[[]sif.Accumulator] {
return &composedFactory{faccs}
}