From 573316e3c2ddd91fd0f36d2251f9660b4f98bebc Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Sun, 8 Jan 2023 23:48:37 -0700 Subject: binstruct: Make the cache thread-safe --- Makefile | 2 +- go.mod | 2 +- lib/binstruct/structs.go | 27 +++++++++++++-------------- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index b3bcdd8..c16dfd7 100644 --- a/Makefile +++ b/Makefile @@ -54,7 +54,7 @@ go-mod-tidy: go-mod-tidy: go-mod-tidy/main go-mod-tidy/main: rm -f go.sum - go mod tidy -go $(goversion) -compat $(goversion) + go mod tidy -go 1.20 -compat $(goversion) .PHONY: go-mod-tidy/main go-mod-tidy: $(patsubst tools/src/%/go.mod,go-mod-tidy/tools/%,$(wildcard tools/src/*/go.mod)) diff --git a/go.mod b/go.mod index 2bd05ff..f2e26e7 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ module git.lukeshu.com/btrfs-progs-ng -go 1.19 +go 1.20 require ( git.lukeshu.com/go/lowmemjson v0.3.4 diff --git a/lib/binstruct/structs.go b/lib/binstruct/structs.go index 7eea600..52e5406 100644 --- a/lib/binstruct/structs.go +++ b/lib/binstruct/structs.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" + "git.lukeshu.com/go/typedsync" + "git.lukeshu.com/btrfs-progs-ng/lib/binstruct/binutil" ) @@ -178,21 +180,18 @@ func genStructHandler(structInfo reflect.Type) (structHandler, error) { return ret, nil } -var structCache = make(map[reflect.Type]structHandler) +var structCache typedsync.CacheMap[reflect.Type, structHandler] func getStructHandler(typ reflect.Type) structHandler { - h, ok := structCache[typ] - if ok { + ret, _ := structCache.LoadOrCompute(typ, func(typ reflect.Type) structHandler { + h, err := genStructHandler(typ) + if err != nil { + panic(&InvalidTypeError{ + Type: typ, + Err: err, + }) + } return h - } - - h, err := genStructHandler(typ) - if err != nil { - panic(&InvalidTypeError{ - Type: typ, - Err: err, - }) - } - structCache[typ] = h - return h + }) + return ret } -- cgit v1.2.3-2-g168b