File: cache.go

package info (click to toggle)
golang-github-antchfx-xmlquery 1.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 108 kB
  • sloc: xml: 120; makefile: 2
file content (40 lines) | stat: -rw-r--r-- 822 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package xmlquery

import (
	"sync"

	"github.com/golang/groupcache/lru"

	"github.com/antchfx/xpath"
)

// DisableSelectorCache will disable caching for the query selector if value is true.
var DisableSelectorCache = false

// SelectorCacheMaxEntries allows how many selector object can be caching. Default is 50.
// Will disable caching if SelectorCacheMaxEntries <= 0.
var SelectorCacheMaxEntries = 50

var (
	cacheOnce sync.Once
	cache     *lru.Cache
)

func getQuery(expr string) (*xpath.Expr, error) {
	if DisableSelectorCache || SelectorCacheMaxEntries <= 0 {
		return xpath.Compile(expr)
	}
	cacheOnce.Do(func() {
		cache = lru.New(50)
	})
	if v, ok := cache.Get(expr); ok {
		return v.(*xpath.Expr), nil
	}
	v, err := xpath.Compile(expr)
	if err != nil {
		return nil, err
	}
	cache.Add(expr, v)
	return v, nil

}