Skip to content

Commit

Permalink
Add LRU cache for JSONPointerToSlice and DotPathToSlice.
Browse files Browse the repository at this point in the history
Signed-off-by: Steve McDaniel <[email protected]>
  • Loading branch information
nibbleshift committed May 8, 2023
1 parent 81fbfc2 commit 8f7b913
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
28 changes: 28 additions & 0 deletions gabs.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import (
"os"
"strconv"
"strings"

lru "github.com/hashicorp/golang-lru/v2"
)

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -79,11 +81,17 @@ var (
var (
r1 *strings.Replacer
r2 *strings.Replacer
// Cache for DotPathToSlice
dotPathCache *lru.Cache[string, []string]
// Cache for JSONPointerToSlice
jsonPointerCache *lru.Cache[string, []string]
)

func init() {
r1 = strings.NewReplacer("~1", "/", "~0", "~")
r2 = strings.NewReplacer("~1", ".", "~0", "~")
dotPathCache, _ = lru.New[string, []string](1024)
jsonPointerCache, _ = lru.New[string, []string](1024)
}

//------------------------------------------------------------------------------
Expand All @@ -105,10 +113,20 @@ func JSONPointerToSlice(path string) ([]string, error) {
if path == "/" {
return []string{""}, nil
}

item, ok := jsonPointerCache.Get(path)

if ok {
return item, nil
}

hierarchy := strings.Split(path, "/")[1:]
for i, v := range hierarchy {
hierarchy[i] = r1.Replace(v)
}

jsonPointerCache.Add(path, hierarchy)

return hierarchy, nil
}

Expand All @@ -118,10 +136,20 @@ func JSONPointerToSlice(path string) ([]string, error) {
// if it appears in the reference key. Likewise, '~' (%x7E) must be encoded
// as '~0' since it is the escape character for encoding '.'.
func DotPathToSlice(path string) []string {
item, ok := dotPathCache.Get(path)

if ok {
return item
}

hierarchy := strings.Split(path, ".")

for i, v := range hierarchy {
hierarchy[i] = r2.Replace(v)
}

dotPathCache.Add(path, hierarchy)

return hierarchy
}

Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/Jeffail/gabs/v2

go 1.16
go 1.18

require github.com/hashicorp/golang-lru/v2 v2.0.2

0 comments on commit 8f7b913

Please sign in to comment.