-
Notifications
You must be signed in to change notification settings - Fork 1
/
upgrade.go
58 lines (49 loc) · 1.18 KB
/
upgrade.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
// Copyright (c) 2019 Meng Huang ([email protected])
// This package is licensed under a MIT license that can be found in the LICENSE file.
package rpc
import "errors"
const (
upgradeSize = 1
noRequest = 0x1
noResponse = 0x1
heartbeat = 0x1
openStream = 0x1
streaming = 0x2
closeStream = 0x3
)
type upgrade struct {
NoRequest byte //1bit
NoResponse byte //1bit
Heartbeat byte //1bit
Stream byte //2bit
}
func (u *upgrade) Reset() {
*u = upgrade{}
}
func (u *upgrade) IsZero() bool {
return u.NoRequest+u.NoResponse+u.Heartbeat+u.Stream == 0
}
func (u *upgrade) Marshal(buf []byte) ([]byte, error) {
var size uint64 = upgradeSize
if uint64(cap(buf)) >= size {
buf = buf[:size]
} else {
buf = make([]byte, size)
}
var offset uint64
buf[0] = u.NoRequest<<7 + u.NoResponse<<6 + u.Heartbeat<<5 + u.Stream<<3
offset++
return buf[:offset], nil
}
func (u *upgrade) Unmarshal(data []byte) (uint64, error) {
var offset uint64
if uint64(len(data)) < offset+1 {
return 0, errors.New("data is too short")
}
u.NoRequest = data[0] >> 7 & 0x1
u.NoResponse = data[0] >> 6 & 0x1
u.Heartbeat = data[0] >> 5 & 0x1
u.Stream = data[0] >> 3 & 0x3
offset++
return offset, nil
}