registry.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package registry
  2. import (
  3. "github.com/v2fly/v2ray-core/v4/common/protoext"
  4. "google.golang.org/protobuf/proto"
  5. )
  6. type implementationRegistry struct {
  7. implSet map[string]*implementationSet
  8. }
  9. func (i *implementationRegistry) RegisterImplementation(name string, opt *protoext.MessageOpt) {
  10. interfaceType := opt.GetType()[0]
  11. implSet, found := i.implSet[interfaceType]
  12. if !found {
  13. implSet = newImplementationSet()
  14. i.implSet[interfaceType] = implSet
  15. }
  16. implSet.RegisterImplementation(name, opt)
  17. }
  18. func (i *implementationRegistry) FindImplementationByAlias(interfaceType, alias string) (string, error) {
  19. implSet, found := i.implSet[interfaceType]
  20. if !found {
  21. return "", newError("cannot find implemention unknown interface type")
  22. }
  23. return implSet.FindImplementationByAlias(alias)
  24. }
  25. func newImplementationRegistry() *implementationRegistry {
  26. return &implementationRegistry{implSet: map[string]*implementationSet{}}
  27. }
  28. var globalImplementationRegistry = newImplementationRegistry()
  29. func RegisterImplementation(proto proto.Message) error {
  30. msgDesc := proto.ProtoReflect().Type().Descriptor()
  31. fullName := string(msgDesc.FullName())
  32. msgOpts, err := protoext.GetMessageOptions(msgDesc)
  33. if err != nil {
  34. return newError("unable to find message options").Base(err)
  35. }
  36. globalImplementationRegistry.RegisterImplementation(fullName, msgOpts)
  37. return nil
  38. }
  39. func FindImplementationByAlias(interfaceType, alias string) (string, error) {
  40. return globalImplementationRegistry.FindImplementationByAlias(interfaceType, alias)
  41. }