1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/common/loader/type.go

51 lines
1.1 KiB
Go
Raw Normal View History

2016-10-16 08:22:21 -04:00
package loader
import (
"errors"
"reflect"
"github.com/golang/protobuf/proto"
)
func NewTypedSettings(message proto.Message) *TypedSettings {
if message == nil {
return nil
}
settings, _ := proto.Marshal(message)
return &TypedSettings{
Type: GetType(message),
Settings: settings,
}
}
func GetType(message proto.Message) string {
return proto.MessageName(message)
}
func GetInstance(messageType string) (interface{}, error) {
2016-10-17 08:35:13 -04:00
mType := proto.MessageType(messageType).Elem()
2016-10-16 08:22:21 -04:00
if mType == nil {
return nil, errors.New("Unknown type: " + messageType)
}
return reflect.New(mType).Interface(), nil
}
func (this *TypedSettings) Load(message proto.Message) error {
targetType := GetType(message)
if targetType != this.Type {
return errors.New("Have type " + this.Type + ", but retrieved for " + targetType)
}
return proto.Unmarshal(this.Settings, message)
}
func (this *TypedSettings) GetInstance() (interface{}, error) {
instance, err := GetInstance(this.Type)
if err != nil {
return nil, err
}
if err := proto.Unmarshal(this.Settings, instance.(proto.Message)); err != nil {
return nil, err
}
return instance, nil
}