MCPcopy
hub / github.com/golang/protobuf / marshalValue

Method marshalValue

jsonpb/encode.go:421–512  ·  view source on GitHub ↗
(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string)

Source from the content-addressed store, hash-verified

419}
420
421func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
422 switch {
423 case fd.IsList():
424 w.write("[")
425 comma := ""
426 lv := v.List()
427 for i := 0; i < lv.Len(); i++ {
428 w.write(comma)
429 if w.Indent != "" {
430 w.write("\n")
431 w.write(indent)
432 w.write(w.Indent)
433 w.write(w.Indent)
434 }
435 if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil {
436 return err
437 }
438 comma = ","
439 }
440 if w.Indent != "" {
441 w.write("\n")
442 w.write(indent)
443 w.write(w.Indent)
444 }
445 w.write("]")
446 return nil
447 case fd.IsMap():
448 kfd := fd.MapKey()
449 vfd := fd.MapValue()
450 mv := v.Map()
451
452 // Collect a sorted list of all map keys and values.
453 type entry struct{ key, val protoreflect.Value }
454 var entries []entry
455 mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
456 entries = append(entries, entry{k.Value(), v})
457 return true
458 })
459 sort.Slice(entries, func(i, j int) bool {
460 switch kfd.Kind() {
461 case protoreflect.BoolKind:
462 return !entries[i].key.Bool() && entries[j].key.Bool()
463 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
464 return entries[i].key.Int() < entries[j].key.Int()
465 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
466 return entries[i].key.Uint() < entries[j].key.Uint()
467 case protoreflect.StringKind:
468 return entries[i].key.String() < entries[j].key.String()
469 default:
470 panic("invalid kind")
471 }
472 })
473
474 w.write(`{`)
475 comma := ""
476 for _, entry := range entries {
477 w.write(comma)
478 if w.Indent != "" {

Callers 2

marshalMessageMethod · 0.95
marshalFieldMethod · 0.95

Calls 6

writeMethod · 0.95
marshalSingularValueMethod · 0.95
InterfaceMethod · 0.80
MarshalMethod · 0.65
LenMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected