-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrwc.go
87 lines (67 loc) · 1.27 KB
/
rwc.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
// SPDX-FileCopyrightText: 2021 Henry Bubert
//
// SPDX-License-Identifier: MIT
package muxrpc
import (
"errors"
"fmt"
"io"
)
const ChunkSize = 65536
func NewSinkWriter(sink *ByteSink) io.WriteCloser {
return &sinkWriter{sink}
}
type sinkWriter struct {
sink *ByteSink
}
func (w *sinkWriter) Write(data []byte) (int, error) {
var written int
for len(data) > 0 {
var block []byte
if len(data) > ChunkSize {
block = data[:ChunkSize]
} else {
block = data
}
_, err := w.sink.Write(block)
if err != nil {
return written, err
}
data = data[len(block):]
written += len(block)
}
return written, nil
}
func (w *sinkWriter) Close() error {
return w.sink.Close()
}
func NewSourceReader(src *ByteSource) io.Reader {
return &srcReader{
src: src,
}
}
type srcReader struct {
src *ByteSource
buf []byte
}
func (r *srcReader) Read(data []byte) (int, error) {
if len(r.buf) > 0 {
n := copy(data, r.buf)
r.buf = r.buf[n:]
return n, nil
}
more := r.src.Next(r.src.streamCtx)
if !more {
err := r.src.Err()
if err == nil || errors.Is(err, io.EOF) {
return 0, io.EOF
}
return 0, fmt.Errorf("muxrpc: error getting next block: %w", err)
}
var err error
r.buf, err = r.src.Bytes()
if err != nil {
return 0, err
}
return r.Read(data)
}