-
Notifications
You must be signed in to change notification settings - Fork 3
/
stream.go
91 lines (73 loc) · 1.61 KB
/
stream.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
package star
import (
"github.com/pion/datachannel"
"io"
"math"
"net"
"time"
)
const wrapperBufferSize = math.MaxUint16
type stream struct {
id string
dataChannel datachannel.ReadWriteCloser
address net.Addr
buffer []byte
bufferStart int
bufferEnd int
}
var _ net.Conn = new(stream)
func newStream(dataChannel datachannel.ReadWriteCloser, address net.Addr) *stream {
return &stream{
id: createRandomID("stream"),
dataChannel: dataChannel,
address: address,
buffer: make([]byte, wrapperBufferSize),
}
}
func (s *stream) Read(p []byte) (int, error) {
var err error
if s.bufferEnd == 0 {
n := 0
n, err = s.dataChannel.Read(s.buffer)
if err != nil {
logger.Errorf("Error occurred while reading from data channel: %v", err)
err = io.EOF
}
s.bufferEnd = n
}
n := 0
if s.bufferEnd-s.bufferStart > 0 {
n = copy(p, s.buffer[s.bufferStart:s.bufferEnd])
s.bufferStart += n
if s.bufferStart >= s.bufferEnd {
s.bufferStart = 0
s.bufferEnd = 0
}
}
return n, err
}
func (s *stream) Write(p []byte) (int, error) {
if len(p) > wrapperBufferSize {
return s.dataChannel.Write(p[:wrapperBufferSize])
}
return s.dataChannel.Write(p)
}
func (s *stream) Close() error {
logger.Warningf("%s: Close stream", s.id)
return s.dataChannel.Close()
}
func (s *stream) LocalAddr() net.Addr {
return s.address
}
func (s *stream) RemoteAddr() net.Addr {
return s.address
}
func (s *stream) SetDeadline(time.Time) error {
return nil
}
func (s *stream) SetReadDeadline(time.Time) error {
return nil
}
func (s *stream) SetWriteDeadline(time.Time) error {
return nil
}