/
chunking.go
64 lines (48 loc) · 1.11 KB
/
chunking.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
package stream
import (
"fmt"
"math"
)
type (
Chunk [][]byte
Chunks []Chunk
)
func BuildChunks(batch []WritableMessage, size int) (Chunks, error) {
numOfChunks := int(math.Ceil(float64(len(batch)) / float64(size)))
errors := make([]error, 0)
chunks := make(Chunks, numOfChunks)
for i := 0; i < numOfChunks; i++ {
chunks[i] = make(Chunk, 0, size)
}
j := 0
for i := 0; i < len(batch); i++ {
bytes, err := batch[i].MarshalToBytes()
if err != nil {
errors = append(errors, err)
continue
}
chunks[j] = append(chunks[j], bytes)
if len(chunks[j]) == size {
j++
}
}
var err error
if len(errors) > 0 {
err = fmt.Errorf("there were %v errors on chunking and marshalling the messages", len(errors))
}
return chunks, err
}
func ByteChunkToStrings(chunk Chunk) []string {
strings := make([]string, len(chunk))
for i := 0; i < len(chunk); i++ {
strings[i] = string(chunk[i])
}
return strings
}
func ByteChunkToInterfaces(chunk Chunk) []interface{} {
interfaces := make([]interface{}, len(chunk))
for i := 0; i < len(chunk); i++ {
interfaces[i] = chunk[i]
}
return interfaces
}