-
Notifications
You must be signed in to change notification settings - Fork 2
/
sink.go
95 lines (82 loc) · 1.71 KB
/
sink.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
package dilithium
import (
"bytes"
"github.com/pkg/errors"
"io"
"sync"
)
type Sink interface {
Accept(data []byte) error
Close()
}
func NewReadSinkAdapter(profile WestworldAlgorithm) Sink {
result := &ReadSinkAdapter{
reads: make(chan *RxRead, profile.Profile().ReadsQueueSize),
}
result.rawReadPool.New = func() interface{} {
return make([]byte, profile.Profile().PoolBufferSize)
}
return result
}
type ReadSinkAdapter struct {
reads chan *RxRead
readBuffer bytes.Buffer
rawReadPool sync.Pool
}
func (self *ReadSinkAdapter) Accept(data []byte) error {
buf := self.rawReadPool.Get().([]byte)
n := copy(buf, data)
self.reads <- &RxRead{buf, n, false}
return nil
}
func (self *ReadSinkAdapter) Close() {
// TODO: Add timeout
self.reads <- &RxRead{nil, 0, true}
}
func (self *ReadSinkAdapter) Read(p []byte) (int, error) {
preread:
for {
select {
case read, ok := <-self.reads:
if !ok {
return 0, io.EOF
}
if !read.Eof {
n, err := self.readBuffer.Write(read.Buf[:read.Size])
if err != nil {
return 0, errors.Wrap(err, "buffer")
}
if n != read.Size {
return 0, errors.New("short buffer")
}
} else {
close(self.reads)
return 0, io.EOF
}
default:
break preread
}
}
if self.readBuffer.Len() > 0 {
return self.readBuffer.Read(p)
} else {
read, ok := <-self.reads
if !ok {
return 0, io.EOF
}
if !read.Eof {
n, err := self.readBuffer.Write(read.Buf[:read.Size])
if err != nil {
return 0, errors.Wrap(err, "buffer")
}
if n != read.Size {
return 0, errors.Wrap(err, "short buffer")
}
self.rawReadPool.Put(read.Buf)
return self.readBuffer.Read(p)
} else {
close(self.reads)
return 0, io.EOF
}
}
}