File: registry.go

package info (click to toggle)
golang-github-lestrrat-go-jwx 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,872 kB
  • sloc: sh: 222; makefile: 86; perl: 62
file content (52 lines) | stat: -rw-r--r-- 1,016 bytes parent folder | download
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
package json

import (
	"fmt"
	"reflect"
	"sync"
)

type Registry struct {
	mu   *sync.RWMutex
	data map[string]reflect.Type
}

func NewRegistry() *Registry {
	return &Registry{
		mu:   &sync.RWMutex{},
		data: make(map[string]reflect.Type),
	}
}

func (r *Registry) Register(name string, object interface{}) {
	if object == nil {
		r.mu.Lock()
		defer r.mu.Unlock()
		delete(r.data, name)
		return
	}

	typ := reflect.TypeOf(object)
	r.mu.Lock()
	defer r.mu.Unlock()
	r.data[name] = typ
}

func (r *Registry) Decode(dec *Decoder, name string) (interface{}, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	if typ, ok := r.data[name]; ok {
		ptr := reflect.New(typ).Interface()
		if err := dec.Decode(ptr); err != nil {
			return nil, fmt.Errorf(`failed to decode field %s: %w`, name, err)
		}
		return reflect.ValueOf(ptr).Elem().Interface(), nil
	}

	var decoded interface{}
	if err := dec.Decode(&decoded); err != nil {
		return nil, fmt.Errorf(`failed to decode field %s: %w`, name, err)
	}
	return decoded, nil
}