1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 17:27:50 -04:00
v2fly/common/serial/serial.go

45 lines
1.0 KiB
Go
Raw Normal View History

2018-11-03 08:03:02 -04:00
package serial
2018-11-02 10:01:33 -04:00
import (
"encoding/binary"
"io"
2018-11-15 10:29:40 -05:00
"unsafe"
"v2ray.com/core/common/stack"
2018-11-02 10:01:33 -04:00
)
2018-11-13 16:46:01 -05:00
// ReadUint16 reads first two bytes from the reader, and then coverts them to an uint16 value.
2018-11-02 10:47:58 -04:00
func ReadUint16(reader io.Reader) (uint16, error) {
2018-11-15 10:29:40 -05:00
var b stack.TwoBytes
s := b[:]
p := uintptr(unsafe.Pointer(&s))
v := (*[]byte)(unsafe.Pointer(p))
if _, err := io.ReadFull(reader, *v); err != nil {
2018-11-02 10:47:58 -04:00
return 0, err
}
2018-11-15 10:29:40 -05:00
return binary.BigEndian.Uint16(*v), nil
2018-11-02 10:47:58 -04:00
}
2018-11-13 16:46:01 -05:00
// WriteUint16 writes an uint16 value into writer.
2018-11-02 10:01:33 -04:00
func WriteUint16(writer io.Writer, value uint16) (int, error) {
2018-11-15 10:29:40 -05:00
var b stack.TwoBytes
s := b[:]
p := uintptr(unsafe.Pointer(&s))
v := (*[]byte)(unsafe.Pointer(p))
2018-11-02 13:20:02 -04:00
2018-11-15 10:29:40 -05:00
binary.BigEndian.PutUint16(*v, value)
return writer.Write(*v)
2018-11-02 13:20:02 -04:00
}
2018-11-13 16:46:01 -05:00
// WriteUint64 writes an uint64 value into writer.
2018-11-02 13:20:02 -04:00
func WriteUint64(writer io.Writer, value uint64) (int, error) {
2018-11-15 10:29:40 -05:00
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)
2018-11-02 13:20:02 -04:00
}