Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions pkg/conv/conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,29 @@ func StructToFlatMap(obj any) map[string]any {
for k, v := range nestedMap {
result[fieldName+"."+k] = v
}
} else if (field.Kind() == reflect.Ptr ||
field.Kind() == reflect.Array ||
field.Kind() == reflect.Slice ||
field.Kind() == reflect.Map) && field.IsNil() {
continue
}

if field.Kind() == reflect.Ptr {
if field.IsNil() {
result[fieldName] = nil
continue
}

// If the pointer is to a struct, flatten it as well
if field.Elem().Kind() == reflect.Struct {
nestedMap := StructToFlatMap(field.Elem().Interface())
for k, v := range nestedMap {
Comment on lines +74 to +77

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Guard against cycles when flattening pointer fields

The new pointer-handling block recurses into struct pointers by calling StructToFlatMap(field.Elem().Interface()) without tracking visited nodes. If the input struct contains cyclic references (for example a self-referencing linked list or a child struct pointing back to its parent), this will now recurse forever and overflow the stack. The prior version simply stored the pointer value and did not recurse, so cyclic data could be processed; the change therefore introduces a crash on cyclic inputs.

Useful? React with 👍 / 👎.

result[fieldName+"."+k] = v
}
continue
}

result[fieldName] = field.Elem().Interface()
continue
}

if (field.Kind() == reflect.Slice || field.Kind() == reflect.Map) && field.IsNil() {
result[fieldName] = nil
} else {
result[fieldName] = field.Interface()
Expand Down
40 changes: 40 additions & 0 deletions pkg/conv/conv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package conv

import "testing"

func TestStructToFlatMapArrayField(t *testing.T) {
type Example struct {
Numbers [2]int
}
defer func() {
if r := recover(); r != nil {
t.Fatalf("StructToFlatMap panicked: %v", r)
}
}()
_ = StructToFlatMap(Example{Numbers: [2]int{1, 2}})
}

func TestStructToFlatMapPointerStruct(t *testing.T) {
type Inner struct {
Name string
}
type Outer struct {
Inner *Inner
}

m := StructToFlatMap(Outer{Inner: &Inner{Name: "value"}})
if v, ok := m["Inner.Name"]; !ok || v != "value" {
t.Fatalf("expected Inner.Name to be 'value', got %v", m)
}
}

func TestStructToFlatMapNilPointer(t *testing.T) {
type Outer struct {
Inner *int
}

m := StructToFlatMap(Outer{})
if v, ok := m["Inner"]; !ok || v != nil {
t.Fatalf("expected Inner to be nil, got %v", m)
}
}
Loading