1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-02 22:21:19 +00:00

cleanup serial package

This commit is contained in:
Darien Raymond 2018-11-13 22:46:01 +01:00
parent eeb588ffa0
commit c5ccbe6b63
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
4 changed files with 16 additions and 6 deletions

View File

@ -5,6 +5,7 @@ import (
"io"
)
// ReadUint16 reads first two bytes from the reader, and then coverts them to an uint16 value.
func ReadUint16(reader io.Reader) (uint16, error) {
var b [2]byte
if _, err := io.ReadFull(reader, b[:]); err != nil {
@ -13,18 +14,21 @@ func ReadUint16(reader io.Reader) (uint16, error) {
return binary.BigEndian.Uint16(b[:]), nil
}
// WriteUint16 writes an uint16 value into writer.
func WriteUint16(writer io.Writer, value uint16) (int, error) {
var b [2]byte
binary.BigEndian.PutUint16(b[:], value)
return writer.Write(b[:])
}
// WriteUint32 writes an uint32 value into writer.
func WriteUint32(writer io.Writer, value uint32) (int, error) {
var b [4]byte
binary.BigEndian.PutUint32(b[:], value)
return writer.Write(b[:])
}
// WriteUint64 writes an uint64 value into writer.
func WriteUint64(writer io.Writer, value uint64) (int, error) {
var b [8]byte
binary.BigEndian.PutUint64(b[:], value)

View File

@ -25,6 +25,7 @@ func ToString(v interface{}) string {
}
}
// Concat concatenates all input into a single string.
func Concat(v ...interface{}) string {
builder := strings.Builder{}
for _, value := range v {
@ -32,9 +33,3 @@ func Concat(v ...interface{}) string {
}
return builder.String()
}
func WriteString(s string) func([]byte) (int, error) {
return func(b []byte) (int, error) {
return copy(b, []byte(s)), nil
}
}

View File

@ -7,6 +7,7 @@ import (
"github.com/golang/protobuf/proto"
)
// ToTypeMessage converts a proto Message into TypedMessage.
func ToTypedMessage(message proto.Message) *TypedMessage {
if message == nil {
return nil
@ -18,10 +19,12 @@ func ToTypedMessage(message proto.Message) *TypedMessage {
}
}
// GetMessageType returns the name of this proto Message.
func GetMessageType(message proto.Message) string {
return proto.MessageName(message)
}
// GetInstance creates a new instance of the message with messageType.
func GetInstance(messageType string) (interface{}, error) {
mType := proto.MessageType(messageType)
if mType == nil || mType.Elem() == nil {
@ -30,6 +33,7 @@ func GetInstance(messageType string) (interface{}, error) {
return reflect.New(mType.Elem()).Interface(), nil
}
// GetInstance converts current TypedMessage into a proto Message.
func (v *TypedMessage) GetInstance() (proto.Message, error) {
instance, err := GetInstance(v.Type)
if err != nil {

View File

@ -14,3 +14,10 @@ func TestGetInstance(t *testing.T) {
assert(p, IsNil)
assert(err, IsNotNil)
}
func TestConvertingNilMessage(t *testing.T) {
x := ToTypedMessage(nil)
if x != nil {
t.Error("expect nil, but actually not")
}
}