1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-28 23:06:14 -04:00
v2fly/common/registry/registry.go

52 lines
1.7 KiB
Go
Raw Normal View History

2021-09-04 10:21:58 -04:00
package registry
import (
"github.com/v2fly/v2ray-core/v4/common/protoext"
"google.golang.org/protobuf/proto"
)
type implementationRegistry struct {
implSet map[string]*implementationSet
}
2021-09-04 14:06:49 -04:00
func (i *implementationRegistry) RegisterImplementation(name string, opt *protoext.MessageOpt, loader CustomLoader) {
2021-09-04 10:21:58 -04:00
interfaceType := opt.GetType()[0]
implSet, found := i.implSet[interfaceType]
if !found {
implSet = newImplementationSet()
i.implSet[interfaceType] = implSet
}
2021-09-04 14:06:49 -04:00
implSet.RegisterImplementation(name, opt, loader)
2021-09-04 10:21:58 -04:00
}
2021-09-04 14:06:49 -04:00
func (i *implementationRegistry) FindImplementationByAlias(interfaceType, alias string) (string, CustomLoader, error) {
2021-09-04 10:21:58 -04:00
implSet, found := i.implSet[interfaceType]
if !found {
2021-09-04 14:06:49 -04:00
return "", nil, newError("cannot find implemention unknown interface type")
2021-09-04 10:21:58 -04:00
}
return implSet.FindImplementationByAlias(alias)
}
func newImplementationRegistry() *implementationRegistry {
return &implementationRegistry{implSet: map[string]*implementationSet{}}
}
var globalImplementationRegistry = newImplementationRegistry()
2021-09-04 14:06:49 -04:00
// RegisterImplementation register an implementation of a type of interface
// loader(CustomLoader) is a private API, its interface is subject to breaking changes
func RegisterImplementation(proto proto.Message, loader CustomLoader) error {
2021-09-04 10:21:58 -04:00
msgDesc := proto.ProtoReflect().Type().Descriptor()
fullName := string(msgDesc.FullName())
msgOpts, err := protoext.GetMessageOptions(msgDesc)
if err != nil {
return newError("unable to find message options").Base(err)
}
2021-09-04 14:06:49 -04:00
globalImplementationRegistry.RegisterImplementation(fullName, msgOpts, loader)
2021-09-04 10:21:58 -04:00
return nil
}
2021-09-04 14:06:49 -04:00
func FindImplementationByAlias(interfaceType, alias string) (string, CustomLoader, error) {
2021-09-04 10:21:58 -04:00
return globalImplementationRegistry.FindImplementationByAlias(interfaceType, alias)
}