-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoding.go
66 lines (56 loc) · 1.56 KB
/
encoding.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
package engineio
import (
"encoding/base64"
"errors"
"fmt"
"unicode"
)
// ErrEmptyPacket is returned when the input is empty.
var ErrEmptyPacket = errors.New("empty packet")
// BinaryMarker is the marker for binary packets.
const BinaryMarker = 'b'
// EncodePacket encodes a packet into bytes.
func EncodePacket(packet Packet) []byte {
// binary is true if the data contains non-ASCII characters.
var binary bool
for _, r := range string(packet.Data) {
if r > unicode.MaxASCII || !unicode.IsPrint(r) {
binary = true
}
}
switch {
// The packet is a binary packet.
case binary:
return append(
[]byte{BinaryMarker},
[]byte(base64.StdEncoding.EncodeToString(packet.Data))...,
)
// The packet is a text packet.
default:
return append(
[]byte{packet.Type.Byte()},
packet.Data...,
)
}
}
// DecodePacket decodes a packet from a string.
func DecodePacket(input []byte) (Packet, error) {
switch {
// The input is empty.
case len(input) == 0:
return Packet{}, ErrEmptyPacket
// The input is a binary packet. This must be a message packet.
case input[0] == BinaryMarker:
data, err := base64.StdEncoding.DecodeString(string(input[1:]))
if err != nil {
return Packet{}, fmt.Errorf("decode base64: %w", err)
}
return Packet{Type: PacketMessage, Data: data}, nil
// The input is a single byte packet, this indicates no data.
case len(input) == 1:
return Packet{Type: PacketTypeFromByte(input[0]), Data: []byte{}}, nil
// The input is a packet with data.
default:
return Packet{Type: PacketTypeFromByte(input[0]), Data: input[1:]}, nil
}
}