From 130545d630cb24cfcde8182eb09c74015abf5d76 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 15 Oct 2026 07:40:02 +0800 Subject: [PATCH] perf: typed CloneMap deep copy without marshal round-trip (#78) Copy decoded JSON maps and slices directly instead of marshalling and re-parsing on every call. Both callers pass encoding/json trees, so the result is unchanged; the doc comment now states that contract. Co-authored-by: sk-dev-ai --- 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..5fbb845 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 without a marshal round-trip. Only +// map[string]any and []any are copied; every other value is shared as-is, so +// callers must pass trees produced by encoding/json, not maps built from typed +// Go slices or structs, which would alias instead of being normalized. +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