-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.go
47 lines (39 loc) · 1.04 KB
/
serial.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
package serial
import (
"encoding/binary"
"io"
"unsafe"
"v2ray.com/core/common/stack"
)
// ReadUint16 reads first two bytes from the reader, and then coverts them to an uint16 value.
//go:nosplit
func ReadUint16(reader io.Reader) (uint16, error) {
var b stack.TwoBytes
s := b[:]
p := uintptr(unsafe.Pointer(&s))
v := (*[]byte)(unsafe.Pointer(p))
if _, err := io.ReadFull(reader, *v); err != nil {
return 0, err
}
return binary.BigEndian.Uint16(*v), nil
}
// WriteUint16 writes an uint16 value into writer.
//go:nosplit
func WriteUint16(writer io.Writer, value uint16) (int, error) {
var b stack.TwoBytes
s := b[:]
p := uintptr(unsafe.Pointer(&s))
v := (*[]byte)(unsafe.Pointer(p))
binary.BigEndian.PutUint16(*v, value)
return writer.Write(*v)
}
// WriteUint64 writes an uint64 value into writer.
//go:nosplit
func WriteUint64(writer io.Writer, value uint64) (int, error) {
var b stack.EightBytes
s := b[:]
p := uintptr(unsafe.Pointer(&s))
v := (*[]byte)(unsafe.Pointer(p))
binary.BigEndian.PutUint64(*v, value)
return writer.Write(*v)
}