| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package datatest |
| 8 |
|
| 9 |
import "fmt" |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
type ConstantRegistry struct { |
| 14 |
constants map[string]int |
| 15 |
} |
| 16 |
|
| 17 |
|
| 18 |
func NewConstantRegistry() *ConstantRegistry { |
| 19 |
return &ConstantRegistry{ |
| 20 |
constants: make(map[string]int), |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
func (r *ConstantRegistry) Register(name string, value int) { |
| 31 |
r.constants[name] = value |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
func (r *ConstantRegistry) Resolve(name string) (int, bool) { |
| 37 |
val, ok := r.constants[name] |
| 38 |
return val, ok |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
func (r *ConstantRegistry) MustResolve(name string) int { |
| 44 |
val, ok := r.Resolve(name) |
| 45 |
if !ok { |
| 46 |
panic(fmt.Sprintf("constant %q not registered", name)) |
| 47 |
} |
| 48 |
return val |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
func (r *ConstantRegistry) Has(name string) bool { |
| 53 |
_, ok := r.constants[name] |
| 54 |
return ok |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
func (r *ConstantRegistry) MergeFrom(other *ConstantRegistry) { |
| 60 |
for name, value := range other.constants { |
| 61 |
r.constants[name] = value |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
func (r *ConstantRegistry) ListConstants() []string { |
| 67 |
names := make([]string, 0, len(r.constants)) |
| 68 |
for name := range r.constants { |
| 69 |
names = append(names, name) |
| 70 |
} |
| 71 |
return names |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
func (r *ConstantRegistry) ResolveIntOrString(value any) (int, error) { |
| 79 |
switch v := value.(type) { |
| 80 |
case int: |
| 81 |
return v, nil |
| 82 |
case string: |
| 83 |
if resolved, ok := r.Resolve(v); ok { |
| 84 |
return resolved, nil |
| 85 |
} |
| 86 |
return 0, fmt.Errorf("constant %q not found", v) |
| 87 |
default: |
| 88 |
return 0, fmt.Errorf("expected int or string, got %T", value) |
| 89 |
} |
| 90 |
} |