-
Notifications
You must be signed in to change notification settings - Fork 45
/
typed_stream.go
74 lines (61 loc) · 1.37 KB
/
typed_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
package muxado
import (
"encoding/binary"
"net"
)
var order = binary.BigEndian
type StreamType uint32
type TypedStream interface {
Stream
StreamType() StreamType
}
type TypedStreamSession interface {
Session
OpenTypedStream(stype StreamType) (Stream, error)
AcceptTypedStream() (TypedStream, error)
}
func NewTypedStreamSession(s Session) TypedStreamSession {
return &typedStreamSession{s}
}
type typedStreamSession struct {
Session
}
func (s *typedStreamSession) Accept() (net.Conn, error) {
return s.AcceptStream()
}
func (s *typedStreamSession) AcceptStream() (Stream, error) {
return s.AcceptTypedStream()
}
func (s *typedStreamSession) AcceptTypedStream() (TypedStream, error) {
str, err := s.Session.AcceptStream()
if err != nil {
return nil, err
}
var stype [4]byte
_, err = str.Read(stype[:])
if err != nil {
str.Close()
return nil, err
}
return &typedStream{str, StreamType(order.Uint32(stype[:]))}, nil
}
func (s *typedStreamSession) OpenTypedStream(st StreamType) (Stream, error) {
str, err := s.Session.OpenStream()
if err != nil {
return nil, err
}
var stype [4]byte
order.PutUint32(stype[:], uint32(st))
_, err = str.Write(stype[:])
if err != nil {
return nil, err
}
return &typedStream{str, st}, nil
}
type typedStream struct {
Stream
streamType StreamType
}
func (s *typedStream) StreamType() StreamType {
return s.streamType
}