func (p *plugin) checkNameSpace(message *generator.Descriptor) map[string]bool { ccTypeName := generator.CamelCaseSlice(message.TypeName()) names := make(map[string]bool) for _, field := range message.Field { fieldname := generator.CamelCase(*field.Name) if field.IsMessage() && gogoproto.IsEmbed(field) { desc := p.ObjectNamed(field.GetTypeName()) moreNames := p.checkNameSpace(desc.(*generator.Descriptor)) for another := range moreNames { if names[another] { fmt.Fprintf(os.Stderr, "ERROR: duplicate embedded fieldname %v in type %v\n", fieldname, ccTypeName) os.Exit(1) } names[another] = true } } else { if names[fieldname] { fmt.Fprintf(os.Stderr, "ERROR: duplicate embedded fieldname %v in type %v\n", fieldname, ccTypeName) os.Exit(1) } names[fieldname] = true } } return names }
func (p *plugin) Generate(file *generator.FileDescriptor) { for _, msg := range file.Messages() { for _, os := range overwriters { possible := true for _, overwriter := range os { if overwriter(file.FileDescriptorProto, msg.DescriptorProto) { possible = false } } if possible { p.checkOverwrite(msg, os) } } p.checkNameSpace(msg) for _, field := range msg.GetField() { if gogoproto.IsEmbed(field) && gogoproto.IsCustomName(field) { fmt.Fprintf(os.Stderr, "ERROR: field %v with custom name %v cannot be embedded", *field.Name, gogoproto.GetCustomName(field)) os.Exit(1) } } p.checkRepeated(msg) } for _, e := range file.GetExtension() { if gogoproto.IsEmbed(e) { fmt.Fprintf(os.Stderr, "ERROR: extended field %v cannot be embedded", generator.CamelCase(*e.Name)) os.Exit(1) } } }
// generateClientSignature returns the client-side signature for a method. func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } reqArg := ", in *" + g.typeName(method.GetInputType()) if method.GetClientStreaming() { reqArg = "" } respName := "*" + g.typeName(method.GetOutputType()) if method.GetServerStreaming() || method.GetClientStreaming() { respName = servName + "_" + generator.CamelCase(origMethName) + "Client" } return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) }
func (p *plugin) checkRepeated(message *generator.Descriptor) { ccTypeName := generator.CamelCaseSlice(message.TypeName()) for _, field := range message.Field { if !gogoproto.IsEmbed(field) { continue } if field.IsBytes() { fieldname := generator.CamelCase(*field.Name) fmt.Fprintf(os.Stderr, "ERROR: found embedded bytes field %s in message %s\n", fieldname, ccTypeName) os.Exit(1) } if !field.IsRepeated() { continue } fieldname := generator.CamelCase(*field.Name) fmt.Fprintf(os.Stderr, "ERROR: found repeated embedded field %s in message %s\n", fieldname, ccTypeName) os.Exit(1) } }
// generateServerSignature returns the server-side signature for a method. func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } var reqArgs []string ret := "error" if !method.GetServerStreaming() && !method.GetClientStreaming() { reqArgs = append(reqArgs, contextPkg+".Context") ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" } if !method.GetClientStreaming() { reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) } if method.GetServerStreaming() || method.GetClientStreaming() { reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") } return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret }
func (p *plugin) Generate(file *generator.FileDescriptor) { proto3 := gogoproto.IsProto3(file.FileDescriptorProto) for _, msg := range file.Messages() { getters := gogoproto.HasGoGetters(file.FileDescriptorProto, msg.DescriptorProto) face := gogoproto.IsFace(file.FileDescriptorProto, msg.DescriptorProto) for _, field := range msg.GetField() { if len(field.GetDefaultValue()) > 0 { if !getters { fmt.Fprintf(os.Stderr, "ERROR: field %v.%v cannot have a default value and not have a getter method", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) os.Exit(1) } if face { fmt.Fprintf(os.Stderr, "ERROR: field %v.%v cannot have a default value be in a face", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) os.Exit(1) } } if gogoproto.IsNullable(field) { continue } if len(field.GetDefaultValue()) > 0 { fmt.Fprintf(os.Stderr, "ERROR: field %v.%v cannot be non-nullable and have a default value", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) os.Exit(1) } if !field.IsMessage() && !gogoproto.IsCustomType(field) { if field.IsRepeated() { fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is a repeated non-nullable native type, nullable=false has no effect\n", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) } else if proto3 { fmt.Fprintf(os.Stderr, "ERROR: field %v.%v is a native type and in proto3 syntax with nullable=false there exists conflicting implementations when encoding zero values", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) os.Exit(1) } if field.IsBytes() { fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is a non-nullable bytes type, nullable=false has no effect\n", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name)) } } if !field.IsEnum() { continue } enum := p.ObjectNamed(field.GetTypeName()).(*generator.EnumDescriptor) if len(enum.Value) == 0 || enum.Value[0].GetNumber() != 0 { fmt.Fprintf(os.Stderr, "ERROR: field %v.%v cannot be non-nullable and be an enum type %v which does not start with zero", generator.CamelCase(*msg.Name), generator.CamelCase(*field.Name), enum.GetName()) os.Exit(1) } } } for _, e := range file.GetExtension() { if !gogoproto.IsNullable(e) { fmt.Fprintf(os.Stderr, "ERROR: extended field %v cannot be nullable %v", generator.CamelCase(e.GetName()), generator.CamelCase(*e.Name)) os.Exit(1) } } }
func (p *plugin) checkOverwrite(message *generator.Descriptor, enablers map[string]gogoproto.EnableFunc) { ccTypeName := generator.CamelCaseSlice(message.TypeName()) names := []string{} for name := range enablers { names = append(names, name) } for _, field := range message.Field { if field.IsMessage() && gogoproto.IsEmbed(field) { fieldname := generator.CamelCase(*field.Name) desc := p.ObjectNamed(field.GetTypeName()) msg := desc.(*generator.Descriptor) for errStr, enabled := range enablers { if enabled(msg.File(), msg.DescriptorProto) { fmt.Fprintf(os.Stderr, "WARNING: found non-%v %v with embedded %v %v\n", names, ccTypeName, errStr, fieldname) } } p.checkOverwrite(msg, enablers) } } }
func (p *stringer) Generate(file *generator.FileDescriptor) { proto3 := gogoproto.IsProto3(file.FileDescriptorProto) p.PluginImports = generator.NewPluginImports(p.Generator) p.atleastOne = false p.localName = generator.FileName(file) fmtPkg := p.NewImport("fmt") stringsPkg := p.NewImport("strings") reflectPkg := p.NewImport("reflect") sortKeysPkg := p.NewImport("github.com/VividCortex/protobuf/sortkeys") for _, message := range file.Messages() { if !gogoproto.IsStringer(file.FileDescriptorProto, message.DescriptorProto) { continue } if gogoproto.EnabledGoStringer(file.FileDescriptorProto, message.DescriptorProto) { panic("old string method needs to be disabled, please use gogoproto.goproto_stringer or gogoproto.goproto_stringer_all and set it to false") } if message.DescriptorProto.GetOptions().GetMapEntry() { continue } p.atleastOne = true ccTypeName := generator.CamelCaseSlice(message.TypeName()) p.P(`func (this *`, ccTypeName, `) String() string {`) p.In() p.P(`if this == nil {`) p.In() p.P(`return "nil"`) p.Out() p.P(`}`) for _, field := range message.Field { if !generator.IsMap(file.FileDescriptorProto, field) { continue } fieldname := p.GetFieldName(message, field) mapMsg := generator.GetMap(file.FileDescriptorProto, field) keyField, valueField := mapMsg.GetMapFields() keysName := `keysFor` + fieldname keygoTyp, _ := p.GoType(nil, keyField) keygoTyp = strings.Replace(keygoTyp, "*", "", 1) keyCapTyp := generator.CamelCase(keygoTyp) valuegoTyp, _ := p.GoType(nil, valueField) p.P(keysName, ` := make([]`, keygoTyp, `, 0, len(this.`, fieldname, `))`) p.P(`for k, _ := range this.`, fieldname, ` {`) p.In() p.P(keysName, ` = append(`, keysName, `, k)`) p.Out() p.P(`}`) p.P(sortKeysPkg.Use(), `.`, keyCapTyp, `s(`, keysName, `)`) mapName := `mapStringFor` + fieldname p.P(mapName, ` := "map[`, keygoTyp, `]`, valuegoTyp, `{"`) p.P(`for _, k := range `, keysName, ` {`) p.In() p.P(mapName, ` += fmt.Sprintf("%v: %v,", k, this.`, fieldname, `[k])`) p.Out() p.P(`}`) p.P(mapName, ` += "}"`) } p.P("s := ", stringsPkg.Use(), ".Join([]string{`&", ccTypeName, "{`,") for _, field := range message.Field { nullable := gogoproto.IsNullable(field) repeated := field.IsRepeated() fieldname := p.GetFieldName(message, field) if generator.IsMap(file.FileDescriptorProto, field) { mapName := `mapStringFor` + fieldname p.P("`", fieldname, ":`", ` + `, mapName, " + `,", "`,") } else if field.IsMessage() || p.IsGroup(field) { desc := p.ObjectNamed(field.GetTypeName()) msgname := p.TypeName(desc) msgnames := strings.Split(msgname, ".") typeName := msgnames[len(msgnames)-1] if nullable { p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, `), "`, typeName, `","`, msgname, `"`, ", 1) + `,", "`,") } else if repeated { p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, `), "`, typeName, `","`, msgname, `"`, ", 1),`&`,``,1) + `,", "`,") } else { p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, stringsPkg.Use(), `.Replace(this.`, fieldname, `.String(), "`, typeName, `","`, msgname, `"`, ", 1),`&`,``,1) + `,", "`,") } } else { if nullable && !repeated && !proto3 { p.P("`", fieldname, ":`", ` + valueToString`, p.localName, `(this.`, fieldname, ") + `,", "`,") } else { p.P("`", fieldname, ":`", ` + `, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, ") + `,", "`,") } } } if message.DescriptorProto.HasExtension() { if gogoproto.HasExtensionsMap(file.FileDescriptorProto, message.DescriptorProto) { p.P("`XXX_extensions:` + proto.StringFromExtensionsMap(this.XXX_extensions) + `,`,") } else { p.P("`XXX_extensions:` + proto.StringFromExtensionsBytes(this.XXX_extensions) + `,`,") } } if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) { p.P("`XXX_unrecognized:` + ", fmtPkg.Use(), `.Sprintf("%v", this.XXX_unrecognized) + `, "`,`,") } p.P("`}`,") p.P(`}`, `,""`, ")") p.P(`return s`) p.Out() p.P(`}`) } if !p.atleastOne { return } p.P(`func valueToString`, p.localName, `(v interface{}) string {`) p.In() p.P(`rv := `, reflectPkg.Use(), `.ValueOf(v)`) p.P(`if rv.IsNil() {`) p.In() p.P(`return "nil"`) p.Out() p.P(`}`) p.P(`pv := `, reflectPkg.Use(), `.Indirect(rv).Interface()`) p.P(`return `, fmtPkg.Use(), `.Sprintf("*%v", pv)`) p.Out() p.P(`}`) }
func (p *gostring) Generate(file *generator.FileDescriptor) { proto3 := gogoproto.IsProto3(file.FileDescriptorProto) p.PluginImports = generator.NewPluginImports(p.Generator) p.atleastOne = false p.localName = generator.FileName(file) fmtPkg := p.NewImport("fmt") stringsPkg := p.NewImport("strings") protoPkg := p.NewImport("github.com/VividCortex/protobuf/proto") if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) { protoPkg = p.NewImport("github.com/golang/protobuf/proto") } sortPkg := p.NewImport("sort") strconvPkg := p.NewImport("strconv") reflectPkg := p.NewImport("reflect") sortKeysPkg := p.NewImport("github.com/VividCortex/protobuf/sortkeys") for _, message := range file.Messages() { if !gogoproto.HasGoString(file.FileDescriptorProto, message.DescriptorProto) { continue } if message.DescriptorProto.GetOptions().GetMapEntry() { continue } p.atleastOne = true packageName := file.PackageName() ccTypeName := generator.CamelCaseSlice(message.TypeName()) p.P(`func (this *`, ccTypeName, `) GoString() string {`) p.In() p.P(`if this == nil {`) p.In() p.P(`return "nil"`) p.Out() p.P(`}`) outFlds := []string{} for _, field := range message.Field { nullable := gogoproto.IsNullable(field) repeated := field.IsRepeated() fieldname := p.GetFieldName(message, field) if generator.IsMap(file.FileDescriptorProto, field) { mapMsg := generator.GetMap(file.FileDescriptorProto, field) keyField, valueField := mapMsg.GetMapFields() keysName := `keysFor` + fieldname keygoTyp, _ := p.GoType(nil, keyField) keygoTyp = strings.Replace(keygoTyp, "*", "", 1) keyCapTyp := generator.CamelCase(keygoTyp) valuegoTyp, _ := p.GoType(nil, valueField) if !valueField.IsMessage() { valuegoTyp = strings.Replace(valuegoTyp, "*", "", 1) } p.P(keysName, ` := make([]`, keygoTyp, `, 0, len(this.`, fieldname, `))`) p.P(`for k, _ := range this.`, fieldname, ` {`) p.In() p.P(keysName, ` = append(`, keysName, `, k)`) p.Out() p.P(`}`) p.P(sortKeysPkg.Use(), `.`, keyCapTyp, `s(`, keysName, `)`) mapName := `mapStringFor` + fieldname p.P(mapName, ` := "map[`, keygoTyp, `]`, valuegoTyp, `{"`) p.P(`for _, k := range `, keysName, ` {`) p.In() p.P(mapName, ` += fmt.Sprintf("%#v: %#v,", k, this.`, fieldname, `[k])`) p.Out() p.P(`}`) p.P(mapName, ` += "}"`) tmp := strings.Join([]string{"`", fieldname, ":` + ", mapName}, "") outFlds = append(outFlds, tmp) } else if field.IsMessage() || p.IsGroup(field) { tmp := strings.Join([]string{"`", fieldname, ":` + "}, "") if nullable { tmp += strings.Join([]string{fmtPkg.Use(), `.Sprintf("%#v", this.`, fieldname, `)`}, "") } else if repeated { tmp += strings.Join([]string{stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%#v", this.`, fieldname, `)`, ",`&`,``,1)"}, "") } else { tmp += strings.Join([]string{stringsPkg.Use(), `.Replace(this.`, fieldname, `.GoString()`, ",`&`,``,1)"}, "") } outFlds = append(outFlds, tmp) } else { tmp := strings.Join([]string{"`", fieldname, ":` + "}, "") if field.IsEnum() { if nullable && !repeated && !proto3 { goTyp, _ := p.GoType(message, field) tmp += strings.Join([]string{`valueToGoString`, p.localName, `(this.`, fieldname, `,"`, packageName, ".", generator.GoTypeToName(goTyp), `"`, ")"}, "") } else { tmp += strings.Join([]string{fmtPkg.Use(), `.Sprintf("%#v", this.`, fieldname, ")"}, "") } } else { if nullable && !repeated && !proto3 { goTyp, _ := p.GoType(message, field) tmp += strings.Join([]string{`valueToGoString`, p.localName, `(this.`, fieldname, `,"`, generator.GoTypeToName(goTyp), `"`, ")"}, "") } else { tmp += strings.Join([]string{fmtPkg.Use(), `.Sprintf("%#v", this.`, fieldname, ")"}, "") } } outFlds = append(outFlds, tmp) } } if message.DescriptorProto.HasExtension() { if gogoproto.HasExtensionsMap(file.FileDescriptorProto, message.DescriptorProto) { outFlds = append(outFlds, strings.Join([]string{"`XXX_extensions: ` + extensionToGoString", p.localName, `(this.XXX_extensions)`}, "")) } else { outFlds = append(outFlds, strings.Join([]string{"`XXX_extensions:` + ", fmtPkg.Use(), `.Sprintf("%#v", this.XXX_extensions)`}, "")) } } if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) { outFlds = append(outFlds, strings.Join([]string{"`XXX_unrecognized:` + ", fmtPkg.Use(), `.Sprintf("%#v", this.XXX_unrecognized)`}, "")) } outStr := strings.Join([]string{"s := ", stringsPkg.Use(), ".Join([]string{`&", packageName, ".", ccTypeName, "{` + \n"}, "") outStr += strings.Join(outFlds, ",\n") outStr += strings.Join([]string{" + `}`", `}`, `,", "`, ")"}, "") p.P(outStr) p.P(`return s`) p.Out() p.P(`}`) } if !p.atleastOne { return } p.P(`func valueToGoString`, p.localName, `(v interface{}, typ string) string {`) p.In() p.P(`rv := `, reflectPkg.Use(), `.ValueOf(v)`) p.P(`if rv.IsNil() {`) p.In() p.P(`return "nil"`) p.Out() p.P(`}`) p.P(`pv := `, reflectPkg.Use(), `.Indirect(rv).Interface()`) p.P(`return `, fmtPkg.Use(), `.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)`) p.Out() p.P(`}`) p.P(`func extensionToGoString`, p.localName, `(e map[int32]`, protoPkg.Use(), `.Extension) string {`) p.In() p.P(`if e == nil { return "nil" }`) p.P(`s := "map[int32]proto.Extension{"`) p.P(`keys := make([]int, 0, len(e))`) p.P(`for k := range e {`) p.In() p.P(`keys = append(keys, int(k))`) p.Out() p.P(`}`) p.P(sortPkg.Use(), `.Ints(keys)`) p.P(`ss := []string{}`) p.P(`for _, k := range keys {`) p.In() p.P(`ss = append(ss, `, strconvPkg.Use(), `.Itoa(k) + ": " + e[int32(k)].GoString())`) p.Out() p.P(`}`) p.P(`s+=`, stringsPkg.Use(), `.Join(ss, ",") + "}"`) p.P(`return s`) p.Out() p.P(`}`) }
func (p *marshalto) Generate(file *generator.FileDescriptor) { proto3 := gogoproto.IsProto3(file.FileDescriptorProto) numGen := NewNumGen() p.PluginImports = generator.NewPluginImports(p.Generator) p.atleastOne = false p.localName = generator.FileName(file) mathPkg := p.NewImport("math") protoPkg := p.NewImport("github.com/VividCortex/protobuf/proto") if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) { protoPkg = p.NewImport("github.com/golang/protobuf/proto") } sortKeysPkg := p.NewImport("github.com/VividCortex/protobuf/sortkeys") p.unsafePkg = p.NewImport("unsafe") p.errorsPkg = p.NewImport("errors") for _, message := range file.Messages() { if message.DescriptorProto.GetOptions().GetMapEntry() { continue } ccTypeName := generator.CamelCaseSlice(message.TypeName()) if p.unsafe { if !gogoproto.IsUnsafeMarshaler(file.FileDescriptorProto, message.DescriptorProto) { continue } if gogoproto.IsMarshaler(file.FileDescriptorProto, message.DescriptorProto) { panic(fmt.Sprintf("unsafe_marshaler and marshalto enabled for %v", ccTypeName)) } } if !p.unsafe { if !gogoproto.IsMarshaler(file.FileDescriptorProto, message.DescriptorProto) { continue } if gogoproto.IsUnsafeMarshaler(file.FileDescriptorProto, message.DescriptorProto) { panic(fmt.Sprintf("unsafe_marshaler and marshalto enabled for %v", ccTypeName)) } } p.atleastOne = true p.P(`func (m *`, ccTypeName, `) Marshal() (data []byte, err error) {`) p.In() p.P(`size := m.Size()`) p.P(`data = make([]byte, size)`) p.P(`n, err := m.MarshalTo(data)`) p.P(`if err != nil {`) p.In() p.P(`return nil, err`) p.Out() p.P(`}`) p.P(`return data[:n], nil`) p.Out() p.P(`}`) p.P(``) p.P(`func (m *`, ccTypeName, `) MarshalTo(data []byte) (n int, err error) {`) p.In() p.P(`var i int`) p.P(`_ = i`) p.P(`var l int`) p.P(`_ = l`) fields := orderFields(message.GetField()) sort.Sort(fields) for _, field := range message.Field { fieldname := p.GetFieldName(message, field) nullable := gogoproto.IsNullable(field) repeated := field.IsRepeated() required := field.IsRequired() if required && nullable { p.P(`if m.`, fieldname, `== nil {`) p.In() p.P(`return 0, `, protoPkg.Use(), `.NewRequiredNotSetError("`, field.GetName(), `")`) p.Out() p.P(`} else {`) } else if repeated { p.P(`if len(m.`, fieldname, `) > 0 {`) p.In() } else if ((!proto3 || field.IsMessage()) && nullable) || (*field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES && !gogoproto.IsCustomType(field)) { p.P(`if m.`, fieldname, ` != nil {`) p.In() } packed := field.IsPacked() wireType := field.WireType() fieldNumber := field.GetNumber() if packed { wireType = proto.WireBytes } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: if !p.unsafe { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 8`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.P(`f`, numGen.Next(), ` := `, mathPkg.Use(), `.Float64bits(num)`) p.encodeFixed64("f" + numGen.Current()) p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`f`, numGen.Next(), ` := `, mathPkg.Use(), `.Float64bits(num)`) p.encodeFixed64("f" + numGen.Current()) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callFixed64(mathPkg.Use(), `.Float64bits(m.`+fieldname, `)`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callFixed64(mathPkg.Use(), `.Float64bits(m.`+fieldname, `)`) } else { p.encodeKey(fieldNumber, wireType) p.callFixed64(mathPkg.Use(), `.Float64bits(*m.`+fieldname, `)`) } } else { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 8`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.unsafeFixed64("num", "float64") p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed64("num", "float64") p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed64(`m.`+fieldname, "float64") p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.unsafeFixed64(`m.`+fieldname, "float64") } else { p.encodeKey(fieldNumber, wireType) p.unsafeFixed64(`*m.`+fieldname, `float64`) } } case descriptor.FieldDescriptorProto_TYPE_FLOAT: if !p.unsafe { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 4`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.P(`f`, numGen.Next(), ` := `, mathPkg.Use(), `.Float32bits(num)`) p.encodeFixed32("f" + numGen.Current()) p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`f`, numGen.Next(), ` := `, mathPkg.Use(), `.Float32bits(num)`) p.encodeFixed32("f" + numGen.Current()) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callFixed32(mathPkg.Use(), `.Float32bits(m.`+fieldname, `)`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callFixed32(mathPkg.Use(), `.Float32bits(m.`+fieldname, `)`) } else { p.encodeKey(fieldNumber, wireType) p.callFixed32(mathPkg.Use(), `.Float32bits(*m.`+fieldname, `)`) } } else { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 4`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.unsafeFixed32("num", "float32") p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed32("num", "float32") p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed32(`m.`+fieldname, `float32`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.unsafeFixed32(`m.`+fieldname, `float32`) } else { p.encodeKey(fieldNumber, wireType) p.unsafeFixed32(`*m.`+fieldname, "float32") } } case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: if packed { jvar := "j" + numGen.Next() p.P(`data`, numGen.Next(), ` := make([]byte, len(m.`, fieldname, `)*10)`) p.P(`var `, jvar, ` int`) if *field.Type == descriptor.FieldDescriptorProto_TYPE_INT64 || *field.Type == descriptor.FieldDescriptorProto_TYPE_INT32 { p.P(`for _, num1 := range m.`, fieldname, ` {`) p.In() p.P(`num := uint64(num1)`) } else { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() } p.P(`for num >= 1<<7 {`) p.In() p.P(`data`, numGen.Current(), `[`, jvar, `] = uint8(uint64(num)&0x7f|0x80)`) p.P(`num >>= 7`) p.P(jvar, `++`) p.Out() p.P(`}`) p.P(`data`, numGen.Current(), `[`, jvar, `] = uint8(num)`) p.P(jvar, `++`) p.Out() p.P(`}`) p.encodeKey(fieldNumber, wireType) p.callVarint(jvar) p.P(`i += copy(data[i:], data`, numGen.Current(), `[:`, jvar, `])`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint("num") p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`m.`, fieldname) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callVarint(`m.`, fieldname) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`*m.`, fieldname) } case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: if !p.unsafe { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 8`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeFixed64("num") p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.encodeFixed64("num") p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callFixed64("m." + fieldname) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callFixed64("m." + fieldname) } else { p.encodeKey(fieldNumber, wireType) p.callFixed64("*m." + fieldname) } } else { typeName := "int64" if *field.Type == descriptor.FieldDescriptorProto_TYPE_FIXED64 { typeName = "uint64" } if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 8`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.unsafeFixed64("num", typeName) p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed64("num", typeName) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed64("m."+fieldname, typeName) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.unsafeFixed64("m."+fieldname, typeName) } else { p.encodeKey(fieldNumber, wireType) p.unsafeFixed64("*m."+fieldname, typeName) } } case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: if !p.unsafe { if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 4`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeFixed32("num") p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.encodeFixed32("num") p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callFixed32("m." + fieldname) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callFixed32("m." + fieldname) } else { p.encodeKey(fieldNumber, wireType) p.callFixed32("*m." + fieldname) } } else { typeName := "int32" if *field.Type == descriptor.FieldDescriptorProto_TYPE_FIXED32 { typeName = "uint32" } if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `) * 4`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.unsafeFixed32("num", typeName) p.Out() p.P(`}`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed32("num", typeName) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.unsafeFixed32("m."+fieldname, typeName) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.unsafeFixed32("m."+fieldname, typeName) } else { p.encodeKey(fieldNumber, wireType) p.unsafeFixed32("*m."+fieldname, typeName) } } case descriptor.FieldDescriptorProto_TYPE_BOOL: if packed { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `)`) p.P(`for _, b := range m.`, fieldname, ` {`) p.In() p.P(`if b {`) p.In() p.P(`data[i] = 1`) p.Out() p.P(`} else {`) p.In() p.P(`data[i] = 0`) p.Out() p.P(`}`) p.P(`i++`) p.Out() p.P(`}`) } else if repeated { p.P(`for _, b := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`if b {`) p.In() p.P(`data[i] = 1`) p.Out() p.P(`} else {`) p.In() p.P(`data[i] = 0`) p.Out() p.P(`}`) p.P(`i++`) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`if m.`, fieldname, ` {`) p.In() p.P(`data[i] = 1`) p.Out() p.P(`} else {`) p.In() p.P(`data[i] = 0`) p.Out() p.P(`}`) p.P(`i++`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.P(`if m.`, fieldname, ` {`) p.In() p.P(`data[i] = 1`) p.Out() p.P(`} else {`) p.In() p.P(`data[i] = 0`) p.Out() p.P(`}`) p.P(`i++`) } else { p.encodeKey(fieldNumber, wireType) p.P(`if *m.`, fieldname, ` {`) p.In() p.P(`data[i] = 1`) p.Out() p.P(`} else {`) p.In() p.P(`data[i] = 0`) p.Out() p.P(`}`) p.P(`i++`) } case descriptor.FieldDescriptorProto_TYPE_STRING: if repeated { p.P(`for _, s := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`l = len(s)`) p.encodeVarint("l") p.P(`i+=copy(data[i:], s)`) p.Out() p.P(`}`) } else if proto3 { p.P(`if len(m.`, fieldname, `) > 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `)`) p.P(`i+=copy(data[i:], m.`, fieldname, `)`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `)`) p.P(`i+=copy(data[i:], m.`, fieldname, `)`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(*m.`, fieldname, `)`) p.P(`i+=copy(data[i:], *m.`, fieldname, `)`) } case descriptor.FieldDescriptorProto_TYPE_GROUP: panic(fmt.Errorf("marshaler does not support group %v", fieldname)) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: if generator.IsMap(file.FileDescriptorProto, field) { mapMsg := generator.GetMap(file.FileDescriptorProto, field) keyField, valueField := mapMsg.GetMapFields() keysName := `keysFor` + fieldname keygoTyp, keywire := p.GoType(nil, keyField) keygoTyp = strings.Replace(keygoTyp, "*", "", 1) _, valuewire := p.GoType(nil, valueField) keyCapTyp := generator.CamelCase(keygoTyp) keyKeySize := keySize(1, wireToType(keywire)) valueKeySize := keySize(2, wireToType(valuewire)) p.P(keysName, ` := make([]`, keygoTyp, `, 0, len(m.`, fieldname, `))`) p.P(`for k, _ := range m.`, fieldname, ` {`) p.In() p.P(keysName, ` = append(`, keysName, `, k)`) p.Out() p.P(`}`) p.P(sortKeysPkg.Use(), `.`, keyCapTyp, `s(`, keysName, `)`) p.P(`for _, k := range `, keysName, ` {`) p.In() p.encodeKey(fieldNumber, wireType) sum := []string{strconv.Itoa(keyKeySize)} switch keyField.GetType() { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: sum = append(sum, `8`) case descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: sum = append(sum, `4`) case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM, descriptor.FieldDescriptorProto_TYPE_INT32: sum = append(sum, `sov`+p.localName+`(uint64(k))`) case descriptor.FieldDescriptorProto_TYPE_BOOL: sum = append(sum, `1`) case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: sum = append(sum, `len(k)+sov`+p.localName+`(uint64(len(k)))`) case descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: sum = append(sum, `soz`+p.localName+`(uint64(k))`) } p.P(`v := m.`, fieldname, `[k]`) sum = append(sum, strconv.Itoa(valueKeySize)) switch valueField.GetType() { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: sum = append(sum, strconv.Itoa(8)) case descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: sum = append(sum, strconv.Itoa(4)) case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM, descriptor.FieldDescriptorProto_TYPE_INT32: sum = append(sum, `sov`+p.localName+`(uint64(v))`) case descriptor.FieldDescriptorProto_TYPE_BOOL: sum = append(sum, `1`) case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: sum = append(sum, `len(v)+sov`+p.localName+`(uint64(len(v)))`) case descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: sum = append(sum, `soz`+p.localName+`(uint64(v))`) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: p.P(`if v == nil {`) p.In() p.P(`return 0, `, p.errorsPkg.Use(), `.New("proto: map has nil element")`) p.Out() p.P(`}`) p.P(`msgSize := v.Size()`) sum = append(sum, `msgSize + sov`+p.localName+`(uint64(msgSize))`) } p.P(`mapSize := `, strings.Join(sum, " + ")) p.callVarint("mapSize") p.encodeKey(1, wireToType(keywire)) p.mapField(numGen, mathPkg, keyField.GetType(), "k") p.encodeKey(2, wireToType(valuewire)) p.mapField(numGen, mathPkg, valueField.GetType(), "v") p.Out() p.P(`}`) } else if repeated { p.P(`for _, msg := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint("msg.Size()") p.P(`n, err := msg.MarshalTo(data[i:])`) p.P(`if err != nil {`) p.In() p.P(`return 0, err`) p.Out() p.P(`}`) p.P(`i+=n`) p.Out() p.P(`}`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`m.`, fieldname, `.Size()`) p.P(`n`, numGen.Next(), `, err := m.`, fieldname, `.MarshalTo(data[i:])`) p.P(`if err != nil {`) p.In() p.P(`return 0, err`) p.Out() p.P(`}`) p.P(`i+=n`, numGen.Current()) } case descriptor.FieldDescriptorProto_TYPE_BYTES: if !gogoproto.IsCustomType(field) { if repeated { p.P(`for _, b := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint("len(b)") p.P(`i+=copy(data[i:], b)`) p.Out() p.P(`}`) } else if proto3 { p.P(`if len(m.`, fieldname, `) > 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `)`) p.P(`i+=copy(data[i:], m.`, fieldname, `)`) p.Out() p.P(`}`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`len(m.`, fieldname, `)`) p.P(`i+=copy(data[i:], m.`, fieldname, `)`) } } else { if repeated { p.P(`for _, msg := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`msg.Size()`) p.P(`n, err := msg.MarshalTo(data[i:])`) p.P(`if err != nil {`) p.In() p.P(`return 0, err`) p.Out() p.P(`}`) p.P(`i+=n`) p.Out() p.P(`}`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`m.`, fieldname, `.Size()`) p.P(`n`, numGen.Next(), `, err := m.`, fieldname, `.MarshalTo(data[i:])`) p.P(`if err != nil {`) p.In() p.P(`return 0, err`) p.Out() p.P(`}`) p.P(`i+=n`, numGen.Current()) } } case descriptor.FieldDescriptorProto_TYPE_SINT32: if packed { datavar := "data" + numGen.Next() jvar := "j" + numGen.Next() p.P(datavar, ` := make([]byte, len(m.`, fieldname, ")*5)") p.P(`var `, jvar, ` int`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() xvar := "x" + numGen.Next() p.P(xvar, ` := (uint32(num) << 1) ^ uint32((num >> 31))`) p.P(`for `, xvar, ` >= 1<<7 {`) p.In() p.P(datavar, `[`, jvar, `] = uint8(uint64(`, xvar, `)&0x7f|0x80)`) p.P(jvar, `++`) p.P(xvar, ` >>= 7`) p.Out() p.P(`}`) p.P(datavar, `[`, jvar, `] = uint8(`, xvar, `)`) p.P(jvar, `++`) p.Out() p.P(`}`) p.encodeKey(fieldNumber, wireType) p.callVarint(jvar) p.P(`i+=copy(data[i:], `, datavar, `[:`, jvar, `])`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`x`, numGen.Next(), ` := (uint32(num) << 1) ^ uint32((num >> 31))`) p.encodeVarint("x" + numGen.Current()) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint32(m.`, fieldname, `) << 1) ^ uint32((m.`, fieldname, ` >> 31))`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint32(m.`, fieldname, `) << 1) ^ uint32((m.`, fieldname, ` >> 31))`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint32(*m.`, fieldname, `) << 1) ^ uint32((*m.`, fieldname, ` >> 31))`) } case descriptor.FieldDescriptorProto_TYPE_SINT64: if packed { jvar := "j" + numGen.Next() xvar := "x" + numGen.Next() datavar := "data" + numGen.Next() p.P(`var `, jvar, ` int`) p.P(datavar, ` := make([]byte, len(m.`, fieldname, `)*10)`) p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.P(xvar, ` := (uint64(num) << 1) ^ uint64((num >> 63))`) p.P(`for `, xvar, ` >= 1<<7 {`) p.In() p.P(datavar, `[`, jvar, `] = uint8(uint64(`, xvar, `)&0x7f|0x80)`) p.P(jvar, `++`) p.P(xvar, ` >>= 7`) p.Out() p.P(`}`) p.P(datavar, `[`, jvar, `] = uint8(`, xvar, `)`) p.P(jvar, `++`) p.Out() p.P(`}`) p.encodeKey(fieldNumber, wireType) p.callVarint(jvar) p.P(`i+=copy(data[i:], `, datavar, `[:`, jvar, `])`) } else if repeated { p.P(`for _, num := range m.`, fieldname, ` {`) p.In() p.encodeKey(fieldNumber, wireType) p.P(`x`, numGen.Next(), ` := (uint64(num) << 1) ^ uint64((num >> 63))`) p.encodeVarint("x" + numGen.Current()) p.Out() p.P(`}`) } else if proto3 { p.P(`if m.`, fieldname, ` != 0 {`) p.In() p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint64(m.`, fieldname, `) << 1) ^ uint64((m.`, fieldname, ` >> 63))`) p.Out() p.P(`}`) } else if !nullable { p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint64(m.`, fieldname, `) << 1) ^ uint64((m.`, fieldname, ` >> 63))`) } else { p.encodeKey(fieldNumber, wireType) p.callVarint(`(uint64(*m.`, fieldname, `) << 1) ^ uint64((*m.`, fieldname, ` >> 63))`) } default: panic("not implemented") } if (required && nullable) || ((!proto3 || field.IsMessage()) && nullable) || repeated || (*field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES && !gogoproto.IsCustomType(field)) { p.Out() p.P(`}`) } } if message.DescriptorProto.HasExtension() { if gogoproto.HasExtensionsMap(file.FileDescriptorProto, message.DescriptorProto) { p.P(`if len(m.XXX_extensions) > 0 {`) p.In() p.P(`n, err := `, protoPkg.Use(), `.EncodeExtensionMap(m.XXX_extensions, data[i:])`) p.P(`if err != nil {`) p.In() p.P(`return 0, err`) p.Out() p.P(`}`) p.P(`i+=n`) p.Out() p.P(`}`) } else { p.P(`if m.XXX_extensions != nil {`) p.In() p.P(`i+=copy(data[i:], m.XXX_extensions)`) p.Out() p.P(`}`) } } if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) { p.P(`if m.XXX_unrecognized != nil {`) p.In() p.P(`i+=copy(data[i:], m.XXX_unrecognized)`) p.Out() p.P(`}`) } p.P(`return i, nil`) p.Out() p.P(`}`) p.P() } if p.atleastOne { p.P(`func encodeFixed64`, p.localName, `(data []byte, offset int, v uint64) int {`) p.In() p.P(`data[offset] = uint8(v)`) p.P(`data[offset+1] = uint8(v >> 8)`) p.P(`data[offset+2] = uint8(v >> 16)`) p.P(`data[offset+3] = uint8(v >> 24)`) p.P(`data[offset+4] = uint8(v >> 32)`) p.P(`data[offset+5] = uint8(v >> 40)`) p.P(`data[offset+6] = uint8(v >> 48)`) p.P(`data[offset+7] = uint8(v >> 56)`) p.P(`return offset+8`) p.Out() p.P(`}`) p.P(`func encodeFixed32`, p.localName, `(data []byte, offset int, v uint32) int {`) p.In() p.P(`data[offset] = uint8(v)`) p.P(`data[offset+1] = uint8(v >> 8)`) p.P(`data[offset+2] = uint8(v >> 16)`) p.P(`data[offset+3] = uint8(v >> 24)`) p.P(`return offset+4`) p.Out() p.P(`}`) p.P(`func encodeVarint`, p.localName, `(data []byte, offset int, v uint64) int {`) p.In() p.P(`for v >= 1<<7 {`) p.In() p.P(`data[offset] = uint8(v&0x7f|0x80)`) p.P(`v >>= 7`) p.P(`offset++`) p.Out() p.P(`}`) p.P(`data[offset] = uint8(v)`) p.P(`return offset+1`) p.Out() p.P(`}`) } }
func (g *grpc) generateServerMethod(servName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, codec ", grpcPkg, ".Codec, buf []byte) (interface{}, error) {") g.P("in := new(", inType, ")") g.P("if err := codec.Unmarshal(buf, in); err != nil { return nil, err }") g.P("out, err := srv.(", servName, "Server).", methName, "(ctx, in)") g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return hname } streamType := unexport(servName) + methName + "Server" g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") if !method.GetClientStreaming() { g.P("m := new(", inType, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") } else { g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") } g.P("}") g.P() genSend := method.GetServerStreaming() genSendAndClose := !method.GetServerStreaming() genRecv := method.GetClientStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Server interface {") if genSend { g.P("Send(*", outType, ") error") } if genSendAndClose { g.P("SendAndClose(*", outType, ") error") } if genRecv { g.P("Recv() (*", inType, ", error)") } g.P(grpcPkg, ".ServerStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ServerStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genSendAndClose { g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") g.P("m := new(", inType, ")") g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } return hname }
func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) methName := generator.CamelCase(method.GetName()) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("out := new(", outType, ")") // TODO: Pass descExpr to Invoke. g.P("err := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, opts...)`) g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return } streamType := unexport(servName) + methName + "Client" g.P("stream, err := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, sname, `", opts...)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.GetClientStreaming() { g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") } g.P("return x, nil") g.P("}") g.P() genSend := method.GetClientStreaming() genRecv := method.GetServerStreaming() genCloseAndRecv := !method.GetServerStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Client interface {") if genSend { g.P("Send(*", inType, ") error") } if genRecv { g.P("Recv() (*", outType, ", error)") } if genCloseAndRecv { g.P("CloseAndRecv() (*", outType, ", error)") } g.P(grpcPkg, ".ClientStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ClientStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", inType, ") error {") g.P("return x.ClientStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } if genCloseAndRecv { g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } }
// generateService generates all the code for the named service. func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { path := fmt.Sprintf("6,%d", index) // 6 means service. origServName := service.GetName() fullServName := file.GetPackage() + "." + origServName servName := generator.CamelCase(origServName) g.P() g.P("// Client API for ", servName, " service") g.P() // Client interface. g.P("type ", servName, "Client interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateClientSignature(servName, method)) } g.P("}") g.P() // Client structure. g.P("type ", unexport(servName), "Client struct {") g.P("cc *", grpcPkg, ".ClientConn") g.P("}") g.P() // NewClient factory. g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") g.P("return &", unexport(servName), "Client{cc}") g.P("}") g.P() var methodIndex, streamIndex int serviceDescVar := "_" + servName + "_serviceDesc" // Client method implementations. for _, method := range service.Method { var descExpr string if !method.GetServerStreaming() && !method.GetClientStreaming() { // Unary RPC method descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) methodIndex++ } else { // Streaming RPC method descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) streamIndex++ } g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) } g.P("// Server API for ", servName, " service") g.P() // Server interface. serverType := servName + "Server" g.P("type ", serverType, " interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateServerSignature(servName, method)) } g.P("}") g.P() // Server registration. g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") g.P("s.RegisterService(&", serviceDescVar, `, srv)`) g.P("}") g.P() // Server handler implementations. var handlerNames []string for _, method := range service.Method { hname := g.generateServerMethod(servName, method) handlerNames = append(handlerNames, hname) } // Service descriptor. g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") g.P("ServiceName: ", strconv.Quote(fullServName), ",") g.P("HandlerType: (*", serverType, ")(nil),") g.P("Methods: []", grpcPkg, ".MethodDesc{") for i, method := range service.Method { if method.GetServerStreaming() || method.GetClientStreaming() { continue } g.P("{") g.P("MethodName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") g.P("},") } g.P("},") g.P("Streams: []", grpcPkg, ".StreamDesc{") for i, method := range service.Method { if !method.GetServerStreaming() && !method.GetClientStreaming() { continue } g.P("{") g.P("StreamName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") if method.GetServerStreaming() { g.P("ServerStreams: true,") } if method.GetClientStreaming() { g.P("ClientStreams: true,") } g.P("},") } g.P("},") g.P("}") g.P() }