-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_chunker.go
67 lines (52 loc) · 1.21 KB
/
write_chunker.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
package main
import "io"
/*
Used by WriteChunker to optionally transform chunks before
sending them on to the underlying io.Writer.
*/
type CustomWriFunc func(io.Writer, []byte) (int, error)
/*
Wraps an io.Writer interface to buffer/flush in chunks that are
`chunkSize` bytes long. Optional `CustomWriFunc` in struct
allows for additional []byte processing before sending each
chunk to the underlying writer. Currently used for encoding to
Kitty terminal's image format.
*/
type WriteChunker struct {
chunk []byte
writer io.Writer
ix int
CustomWriFunc
}
func NewWriteChunker(iWri io.Writer, chunkSize int) WriteChunker {
if chunkSize < 1 {
panic("invalid chunk size")
}
return WriteChunker{
chunk: make([]byte, chunkSize),
writer: iWri,
}
}
func (pC *WriteChunker) Flush() (E error) {
tmp := pC.chunk[:pC.ix]
if pC.CustomWriFunc != nil {
_, E = pC.CustomWriFunc(pC.writer, tmp)
} else {
_, E = pC.writer.Write(tmp)
}
pC.ix = 0
return
}
func (pC *WriteChunker) Write(src []byte) (int, error) {
chunkSize := len(pC.chunk)
for _, bt := range src {
pC.chunk[pC.ix] = bt
pC.ix++
if pC.ix >= chunkSize {
if e := pC.Flush(); e != nil {
return 0, e
}
}
}
return len(src), nil
}