forked from perlin-network/noise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
102 lines (76 loc) · 2.15 KB
/
codec.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
92
93
94
95
96
97
98
99
100
101
102
package noise
import (
"encoding/binary"
"fmt"
"io"
"math"
"reflect"
"sync"
)
// Serializable attributes whether or not a type has a byte representation that it may be serialized into.
type Serializable interface {
// Marshal converts this type into it's byte representation as a slice.
Marshal() []byte
}
type codec struct {
sync.RWMutex
counter uint16
ser map[reflect.Type]uint16
de map[uint16]reflect.Value
}
func newCodec() *codec {
return &codec{
ser: make(map[reflect.Type]uint16, math.MaxUint16),
de: make(map[uint16]reflect.Value, math.MaxUint16),
}
}
func (c *codec) register(ser Serializable, de interface{}) uint16 {
c.Lock()
defer c.Unlock()
t := reflect.TypeOf(ser)
d := reflect.ValueOf(de)
if opcode, registered := c.ser[t]; registered {
panic(fmt.Errorf("attempted to register type %+v which is already registered under opcode %d", t, opcode))
}
expected := reflect.FuncOf([]reflect.Type{reflect.TypeOf(([]byte)(nil))}, []reflect.Type{t, reflect.TypeOf((*error)(nil)).Elem()}, false)
if d.Type() != expected {
panic(fmt.Errorf("provided decoder for message type %+v is %s, but expected %s", t, d, expected))
}
c.ser[t] = c.counter
c.de[c.counter] = d
c.counter++
return c.counter - 1
}
func (c *codec) encode(msg Serializable) ([]byte, error) {
c.RLock()
defer c.RUnlock()
t := reflect.TypeOf(msg)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
opcode, registered := c.ser[t]
if !registered {
return nil, fmt.Errorf("opcode not registered for message type %+v", t)
}
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf[:2], opcode)
return append(buf, msg.Marshal()...), nil
}
func (c *codec) decode(data []byte) (Serializable, error) {
if len(data) < 2 {
return nil, io.ErrUnexpectedEOF
}
opcode := binary.BigEndian.Uint16(data[:2])
data = data[2:]
c.RLock()
defer c.RUnlock()
decoder, registered := c.de[opcode]
if !registered {
return nil, fmt.Errorf("opcode %d is not registered", opcode)
}
results := decoder.Call([]reflect.Value{reflect.ValueOf(data)})
if !results[1].IsNil() {
return nil, results[1].Interface().(error)
}
return results[0].Interface().(Serializable), nil
}