implementation_set.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package registry
  2. import (
  3. "github.com/golang/protobuf/proto"
  4. "github.com/v2fly/v2ray-core/v4/common/protoext"
  5. )
  6. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  7. type implementationSet struct {
  8. AliasLookup map[string]*implementation
  9. }
  10. type CustomLoader func(data []byte, loader LoadByAlias) (proto.Message, error)
  11. type implementation struct {
  12. FullName string
  13. Alias []string
  14. Loader CustomLoader
  15. }
  16. func (i *implementationSet) RegisterImplementation(name string, opt *protoext.MessageOpt, loader CustomLoader) {
  17. alias := opt.GetShortName()
  18. impl := &implementation{
  19. FullName: name,
  20. Alias: alias,
  21. }
  22. for _, aliasName := range alias {
  23. i.AliasLookup[aliasName] = impl
  24. }
  25. }
  26. func (i *implementationSet) findImplementationByAlias(alias string) (string, CustomLoader, error) {
  27. impl, found := i.AliasLookup[alias]
  28. if found {
  29. return impl.FullName, impl.Loader, nil
  30. }
  31. return "", nil, newError("cannot find implementation by alias: ", alias)
  32. }
  33. func newImplementationSet() *implementationSet {
  34. return &implementationSet{AliasLookup: map[string]*implementation{}}
  35. }