-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnull.go
More file actions
46 lines (40 loc) · 1003 Bytes
/
null.go
File metadata and controls
46 lines (40 loc) · 1003 Bytes
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
package sentinel
import (
"github.com/sfcompute/nodes-go/internal/encoding/json/shims"
"reflect"
"sync"
)
type cacheEntry struct {
x any
ptr uintptr
kind reflect.Kind
}
var nullCache sync.Map // map[reflect.Type]cacheEntry
func NewNullSentinel[T any](mk func() T) T {
t := shims.TypeFor[T]()
entry, loaded := nullCache.Load(t) // avoid premature allocation
if !loaded {
x := mk()
ptr := reflect.ValueOf(x).Pointer()
entry, _ = nullCache.LoadOrStore(t, cacheEntry{x, ptr, t.Kind()})
}
return entry.(cacheEntry).x.(T)
}
// for internal use only
func IsValueNull(v reflect.Value) bool {
switch v.Kind() {
case reflect.Map, reflect.Slice:
null, ok := nullCache.Load(v.Type())
return ok && v.Pointer() == null.(cacheEntry).ptr
}
return false
}
func IsNull[T any](v T) bool {
t := shims.TypeFor[T]()
switch t.Kind() {
case reflect.Map, reflect.Slice:
null, ok := nullCache.Load(t)
return ok && reflect.ValueOf(v).Pointer() == null.(cacheEntry).ptr
}
return false
}