From 2dd89196fb0f5b9c811ec93a453a157995a3d11b Mon Sep 17 00:00:00 2001 From: sk-dev-ai Date: Wed, 14 Oct 2026 17:32:42 +0530 Subject: [PATCH] perf: typed CloneMap deep copy without marshal round-trip The old form marshaled and re-parsed on every call, which is both slower and lossy: every number decoded as float64 regardless of what the caller held. The typed clone preserves map, slice, scalar, and json.Number values, returns nil for nil, and deep-copies nested maps and slices so callers cannot alias the input. --- internal/jsonutil/value.go | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/internal/jsonutil/value.go b/internal/jsonutil/value.go index 3d929b9..68e231d 100644 --- a/internal/jsonutil/value.go +++ b/internal/jsonutil/value.go @@ -42,12 +42,39 @@ func FirstAny(values ...any) any { } func CloneMap(input map[string]any) map[string]any { - data, _ := json.Marshal(input) - var output map[string]any - _ = json.Unmarshal(data, &output) + if input == nil { + return nil + } + return cloneMap(input) +} + +// cloneMap deep-copies decoded JSON values without a marshal round-trip. +// The old marshal+unmarshal form was both slower and lossy (every number +// became float64). This preserves the decoded types callers already hold: +// map[string]any, []any, scalars, json.Number. +func cloneMap(input map[string]any) map[string]any { + output := make(map[string]any, len(input)) + for key, value := range input { + output[key] = cloneValue(value) + } return output } +func cloneValue(value any) any { + switch typed := value.(type) { + case map[string]any: + return cloneMap(typed) + case []any: + output := make([]any, len(typed)) + for i, item := range typed { + output[i] = cloneValue(item) + } + return output + default: + return value + } +} + func AsSlice(value any) []any { if values, ok := value.([]any); ok { return values