diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-01-08 23:48:37 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-12 16:16:53 -0700 |
commit | 573316e3c2ddd91fd0f36d2251f9660b4f98bebc (patch) | |
tree | 3e4793944472e3e2ae8262e4b2ef52cd19b08d58 /lib | |
parent | 61656c6d1ba2bb463c1a51b69c151eb2e495c20b (diff) |
binstruct: Make the cache thread-safe
Diffstat (limited to 'lib')
-rw-r--r-- | lib/binstruct/structs.go | 27 |
1 files changed, 13 insertions, 14 deletions
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 } |