MCPcopy Create free account
hub / github.com/pion/rtcp / formatField

Function formatField

packet_stringifier.go:40–112  ·  view source on GitHub ↗

nolint:gocognit,cyclop

(name string, format string, f any, indent string)

Source from the content-addressed store, hash-verified

38
39//nolint:gocognit,cyclop
40func formatField(name string, format string, f any, indent string) string {
41 out := indent
42 value := reflect.ValueOf(f)
43
44 if !value.IsValid() {
45 return fmt.Sprintf("%s%s: <nil>\n", out, name)
46 }
47
48 isPacket := reflect.TypeOf(f).Implements(reflect.TypeFor[Packet]())
49
50 // Resolve pointers to their underlying values
51 if value.Type().Kind() == reflect.Ptr && !value.IsNil() {
52 underlying := reflect.Indirect(value)
53 if underlying.IsValid() {
54 value = underlying
55 }
56 }
57
58 // If the field type has a custom String method, use that
59 // (unless we're a packet, since we want to avoid recursing
60 // back into this function if the Packet's String() method
61 // uses it)
62 if stringMethod := value.MethodByName("String"); !isPacket && stringMethod.IsValid() {
63 out += fmt.Sprintf("%s: %s\n", name, stringMethod.Call([]reflect.Value{}))
64
65 return out
66 }
67
68 switch value.Kind() {
69 case reflect.Struct:
70 out += fmt.Sprintf("%s:\n", name)
71 for i := 0; i < value.NumField(); i++ {
72 if value.Field(i).CanInterface() {
73 format = value.Type().Field(i).Tag.Get("fmt")
74 if format == "" {
75 format = "%+v"
76 }
77 out += formatField(value.Type().Field(i).Name, format, value.Field(i).Interface(), indent+"\t")
78 }
79 }
80 case reflect.Slice:
81 childKind := value.Type().Elem().Kind()
82 _, hasStringMethod := value.Type().Elem().MethodByName("String")
83 if hasStringMethod || childKind == reflect.Struct || childKind == reflect.Ptr ||
84 childKind == reflect.Interface || childKind == reflect.Slice {
85 out += fmt.Sprintf("%s:\n", name)
86 for i := 0; i < value.Len(); i++ {
87 childName := fmt.Sprint(i)
88 // Since interfaces can hold different types of things, we add the
89 // most specific type name to the name to make it clear what the
90 // subsequent fields represent.
91 if value.Index(i).Kind() == reflect.Interface {
92 childName += fmt.Sprintf(" (%s)", reflect.Indirect(reflect.ValueOf(value.Index(i).Interface())).Type())
93 }
94 if value.Index(i).CanInterface() {
95 out += formatField(childName, format, value.Index(i).Interface(), indent+"\t")
96 }
97 }

Callers 1

stringifyFunction · 0.85

Calls 2

TypeMethod · 0.80
LenMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…