File: registry.go

package info (click to toggle)
golang-github-hashicorp-go-bexpr 0.1.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 356 kB
  • sloc: makefile: 50
file content (59 lines) | stat: -rw-r--r-- 1,239 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package bexpr

import (
	"reflect"
	"sync"
)

var DefaultRegistry Registry = NewSyncRegistry()

type Registry interface {
	GetFieldConfigurations(reflect.Type) (FieldConfigurations, error)
}

type SyncRegistry struct {
	configurations map[reflect.Type]FieldConfigurations
	lock           sync.RWMutex
}

func NewSyncRegistry() *SyncRegistry {
	return &SyncRegistry{
		configurations: make(map[reflect.Type]FieldConfigurations),
	}
}

func (r *SyncRegistry) GetFieldConfigurations(rtype reflect.Type) (FieldConfigurations, error) {
	if r != nil {
		r.lock.RLock()
		configurations, ok := r.configurations[rtype]
		r.lock.RUnlock()

		if ok {
			return configurations, nil
		}
	}

	fields, err := generateFieldConfigurations(rtype)
	if err != nil {
		return nil, err
	}

	if r != nil {
		r.lock.Lock()
		r.configurations[rtype] = fields
		r.lock.Unlock()
	}

	return fields, nil
}

type nilRegistry struct{}

// The pass through registry can be used to prevent using the default registry and thus storing
// any field configurations
var NilRegistry = (*nilRegistry)(nil)

func (r *nilRegistry) GetFieldConfigurations(rtype reflect.Type) (FieldConfigurations, error) {
	fields, err := generateFieldConfigurations(rtype)
	return fields, err
}