Browse Source

Expand proto.RegisterType mapping to record both directions (name <-> reflect.Type),
and add two functions to access the mapping.

David Symonds 10 years ago
parent
commit
d3d78384b8
1 changed files with 15 additions and 4 deletions
  1. 15 4
      proto/properties.go

+ 15 - 4
proto/properties.go

@@ -812,16 +812,27 @@ func EnumValueMap(enumType string) map[string]int32 {
 }
 
 // A registry of all linked message types.
-// The key is a fully-qualified proto name ("pkg.Message").
-var protoTypes = make(map[string]reflect.Type)
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+	protoTypes    = make(map[string]reflect.Type)
+	revProtoTypes = make(map[reflect.Type]string)
+)
 
 // RegisterType is called from generated code and maps from the fully qualified
 // proto name to the type (pointer to struct) of the protocol buffer.
-func RegisterType(x interface{}, name string) {
+func RegisterType(x Message, name string) {
 	if _, ok := protoTypes[name]; ok {
 		// TODO: Some day, make this a panic.
 		log.Printf("proto: duplicate proto type registered: %s", name)
 		return
 	}
-	protoTypes[name] = reflect.TypeOf(x)
+	t := reflect.TypeOf(x)
+	protoTypes[name] = t
+	revProtoTypes[t] = name
 }
+
+// MessageName returns the fully-qualified proto name for the given message type.
+func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] }
+
+// MessageType returns the message type (pointer to struct) for a named message.
+func MessageType(name string) reflect.Type { return protoTypes[name] }