forked from josharian/intern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintern.go
68 lines (62 loc) · 1.83 KB
/
intern.go
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Package intern performs best-effort interning or memoization of arbitrary data, with specializations for string/[]byte/[]rune.
//
// Interned/memoized data may be removed automatically at any time without notification.
//
// All functions may be called concurrently with themselves and each other.
package intern
var str ref[string, string]
// String returns s, interned.
func String[S interface{ ~string | ~[]byte | ~[]rune }](s S) string {
// TODO: can we support fmt.Stringer as well?
m := str.get()
c, ok := m[string(s)]
if !ok {
c = string(s)
m[c] = c
}
str.put(m)
return c
}
// Bytes returns b, interned as string.
//
// Deprecated: use String instead.
func Bytes(b []byte) string {
return String(b)
}
// Map allows to map from values of comparable type K to interned values of any type V.
type Map[K comparable, V any] struct {
// TODO: can we somehow create a type-parametrized singleton, so that we don't need
// a Map type?
p ref[K, V]
}
// Intern interns the value v for the specific key k.
// If the map already contains an interned value for the key k,
// it returns the interned value. Otherwise it interns and returns v.
func (c *Map[K, V]) Intern(k K, v V) V {
m := c.p.get()
iv, ok := m[k]
if !ok {
iv = v
m[k] = iv
}
c.p.put(m)
return iv
}
// InternFunc interns the value returned by fn for the specific key k.
// If the map already contains an interned value for the key k,
// it returns the interned value. Otherwise it interns and returns
// the result of calling fn(k).
//
// The passed fn should, in most common cases, return a value that is
// exclusively dependent on the input k. If InternFunc is called
// concurrently, fn must support concurrent invocations.
func (c *Map[K, V]) InternFunc(k K, fn func(K) V) V {
m := c.p.get()
iv, ok := m[k]
if !ok {
iv = fn(k)
m[k] = iv
}
c.p.put(m)
return iv
}