From 558c2a9e043512aa5e91e8368241b190e23df532 Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Tue, 13 May 2025 22:40:10 +0800 Subject: [PATCH 1/2] text/template: use sync.OnceValue for builtinFuncs --- src/text/template/funcs.go | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/src/text/template/funcs.go b/src/text/template/funcs.go index 4d733135fe5a85..ee45591f2efb11 100644 --- a/src/text/template/funcs.go +++ b/src/text/template/funcs.go @@ -62,26 +62,13 @@ func builtins() FuncMap { } } -var builtinFuncsOnce struct { - sync.Once - v map[string]reflect.Value -} - // builtinFuncsOnce lazily computes & caches the builtinFuncs map. -// TODO: revert this back to a global map once golang.org/issue/2559 is fixed. -func builtinFuncs() map[string]reflect.Value { - builtinFuncsOnce.Do(func() { - builtinFuncsOnce.v = createValueFuncs(builtins()) - }) - return builtinFuncsOnce.v -} - -// createValueFuncs turns a FuncMap into a map[string]reflect.Value -func createValueFuncs(funcMap FuncMap) map[string]reflect.Value { - m := make(map[string]reflect.Value) +var builtinFuncsOnce = sync.OnceValue(func() map[string]reflect.Value { + funcMap := builtins() + m := make(map[string]reflect.Value, len(funcMap)) addValueFuncs(m, funcMap) return m -} +}) // addValueFuncs adds to values the functions in funcs, converting them to reflect.Values. func addValueFuncs(out map[string]reflect.Value, in FuncMap) { @@ -149,7 +136,7 @@ func findFunction(name string, tmpl *Template) (v reflect.Value, isBuiltin, ok b return fn, false, true } } - if fn := builtinFuncs()[name]; fn.IsValid() { + if fn := builtinFuncsOnce()[name]; fn.IsValid() { return fn, true, true } return reflect.Value{}, false, false From 7540b1efba864901c1dc00833a72cb9ed306c52f Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Wed, 14 May 2025 23:23:00 +0800 Subject: [PATCH 2/2] text/template: rename builtinFuncsOnce to builtinFuncs --- src/text/template/funcs.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/text/template/funcs.go b/src/text/template/funcs.go index ee45591f2efb11..c28c3ea2002d21 100644 --- a/src/text/template/funcs.go +++ b/src/text/template/funcs.go @@ -62,8 +62,8 @@ func builtins() FuncMap { } } -// builtinFuncsOnce lazily computes & caches the builtinFuncs map. -var builtinFuncsOnce = sync.OnceValue(func() map[string]reflect.Value { +// builtinFuncs lazily computes & caches the builtinFuncs map. +var builtinFuncs = sync.OnceValue(func() map[string]reflect.Value { funcMap := builtins() m := make(map[string]reflect.Value, len(funcMap)) addValueFuncs(m, funcMap) @@ -136,7 +136,7 @@ func findFunction(name string, tmpl *Template) (v reflect.Value, isBuiltin, ok b return fn, false, true } } - if fn := builtinFuncsOnce()[name]; fn.IsValid() { + if fn := builtinFuncs()[name]; fn.IsValid() { return fn, true, true } return reflect.Value{}, false, false