interface.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package yu_proto_old
  2. import (
  3. "encoding"
  4. )
  5. var generators = newInterfaceRegistry()
  6. // InterfaceMarshaler is used to differentiate implementations of an
  7. // interface when encoding/decoding
  8. type InterfaceMarshaler interface {
  9. encoding.BinaryMarshaler
  10. MarshalID() [8]byte
  11. }
  12. // InterfaceGeneratorFunc generates an instance of the implementation
  13. // of an interface
  14. type InterfaceGeneratorFunc func() interface{}
  15. // GeneratorID is the key used to map the generator functions
  16. type GeneratorID [8]byte
  17. type generatorRegistry struct {
  18. generators map[GeneratorID]InterfaceGeneratorFunc
  19. }
  20. func newInterfaceRegistry() *generatorRegistry {
  21. return &generatorRegistry{
  22. generators: make(map[GeneratorID]InterfaceGeneratorFunc),
  23. }
  24. }
  25. // register gets the type tag and map it to the generator function
  26. func (ir *generatorRegistry) register(g InterfaceGeneratorFunc) {
  27. val, ok := g().(InterfaceMarshaler)
  28. if !ok {
  29. panic("Implementation of the interface must fulfilled InterfaceMarshaler")
  30. }
  31. key := val.MarshalID()
  32. ir.generators[key] = g
  33. }
  34. // get returns the generator associated with the tag
  35. func (ir *generatorRegistry) get(key GeneratorID) InterfaceGeneratorFunc {
  36. g, _ := ir.generators[key]
  37. return g
  38. }
  39. // RegisterInterface registers the generator to be used to decode
  40. // the type generated by the function
  41. func RegisterInterface(f InterfaceGeneratorFunc) {
  42. generators.register(f)
  43. }