1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-18 15:27:06 -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 (
"reflect"
"github.com/golang/protobuf/proto"
2016-12-04 03:10:47 -05:00
"v2ray.com/core/common/errors"
2016-10-16 08:22:21 -04:00
)
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
}
2016-11-27 15:39:09 -05:00
func (v *TypedSettings) Load(message proto.Message) error {
2016-10-16 08:22:21 -04:00
targetType := GetType(message)
2016-11-27 15:39:09 -05:00
if targetType != v.Type {
return errors.New("Have type " + v.Type + ", but retrieved for " + targetType)
2016-10-16 08:22:21 -04:00
}
2016-11-27 15:39:09 -05:00
return proto.Unmarshal(v.Settings, message)
2016-10-16 08:22:21 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *TypedSettings) GetInstance() (interface{}, error) {
instance, err := GetInstance(v.Type)
2016-10-16 08:22:21 -04:00
if err != nil {
return nil, err
}
2016-11-27 15:39:09 -05:00
if err := proto.Unmarshal(v.Settings, instance.(proto.Message)); err != nil {
2016-10-16 08:22:21 -04:00
return nil, err
}
return instance, nil
}