github.com/cosmos/cosmos-proto@v1.0.0-beta.3/features/fastreflection/which_oneof.go (about) 1 package fastreflection 2 3 import ( 4 "github.com/cosmos/cosmos-proto/generator" 5 "google.golang.org/protobuf/compiler/protogen" 6 ) 7 8 type whichOneofGen struct { 9 *generator.GeneratedFile 10 typeName string 11 message *protogen.Message 12 } 13 14 func (g *whichOneofGen) generate() { 15 g.genComment() 16 g.genFunc() 17 } 18 19 func (g *whichOneofGen) genComment() { 20 g.P("// WhichOneof reports which field within the oneof is populated,") 21 g.P("// returning nil if none are populated.") 22 g.P("// It panics if the oneof descriptor does not belong to this message.") 23 } 24 25 func (g *whichOneofGen) genFunc() { 26 g.P("func (x *", g.typeName, ") WhichOneof(d ", protoreflectPkg.Ident("OneofDescriptor"), ") ", protoreflectPkg.Ident("FieldDescriptor"), " {") 27 g.P("switch d.FullName() {") 28 for _, oneof := range g.message.Oneofs { 29 g.P("case \"", oneof.Desc.FullName(), "\": ") 30 g.genOneof(oneof) 31 } 32 g.P("default: ") 33 g.P("panic(", fmtPkg.Ident("Errorf"), "(\"%s is not a oneof field in ", g.message.Desc.FullName(), "\", d.FullName()))") 34 g.P("}") 35 36 // this part is unreachable 37 g.P("panic(\"unreachable\")") 38 g.P("}") 39 g.P() 40 } 41 42 func (g *whichOneofGen) genOneof(oneof *protogen.Oneof) { 43 // if none is populated then return nil 44 g.P("if x.", oneof.GoName, " == nil {") 45 g.P("return nil") 46 g.P("}") 47 // switch the type 48 g.P("switch x.", oneof.GoName, ".(type) {") 49 for _, field := range oneof.Fields { 50 g.P("case *", g.QualifiedGoIdent(field.GoIdent), ":") 51 g.P("return x.Descriptor().Fields().ByName(\"", field.Desc.Name(), "\")") 52 } 53 g.P("}") 54 }