MCPcopy Create free account
hub / github.com/oschwald/maxminddb-golang / internAt

Method internAt

internal/decoder/string_cache.go:36–70  ·  view source on GitHub ↗

internAt returns a string for the data at the given offset and size. Hot offsets are interned and the same backing string is returned on subsequent hits; cold offsets are returned freshly allocated on every call (see the admission rule below).

(offset, size uint, data []byte)

Source from the content-addressed store, hash-verified

34// subsequent hits; cold offsets are returned freshly allocated on every
35// call (see the admission rule below).
36func (sc *stringCache) internAt(offset, size uint, data []byte) string {
37 const (
38 minCachedLen = 2 // single byte strings not worth caching
39 maxCachedLen = 100 // reasonable upper bound for geographic strings
40 )
41
42 if size < minCachedLen || size > maxCachedLen {
43 return string(data[offset : offset+size])
44 }
45
46 i := offset % uint(len(sc.entries))
47 entry := &sc.entries[i]
48
49 if cached := entry.Load(); cached != nil && cached.offset == offset {
50 return cached.str
51 }
52
53 str := string(data[offset : offset+size])
54
55 // Only admit strings that miss twice in the same slot. This keeps the
56 // lock-free fast path for hot strings while avoiding heap churn for one-offs.
57 // The +1 bias reserves 0 as the "no prior miss" sentinel so the initial
58 // zero state of recentMisses[i] never spuriously matches a real offset of 0.
59 admissionValue := uint64(offset) + 1
60 if sc.recentMisses[i].Load() == admissionValue {
61 entry.Store(&cacheEntry{
62 str: str,
63 offset: offset,
64 })
65 } else {
66 sc.recentMisses[i].Store(admissionValue)
67 }
68
69 return str
70}

Calls

no outgoing calls