Debian Codegraph @

internal/testutil/datatest/constants.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Constant registry for symbolic test data values.
5 // Allows test data to reference constants by name instead of magic numbers.
6
7 package datatest
8
9 import "fmt"
10
11 // ConstantRegistry maps constant names (strings) to their integer values.
12 // This allows test data to use symbolic constant names instead of magic numbers.
13 type ConstantRegistry struct {
14 constants map[string]int
15 }
16
17 // NewConstantRegistry creates a new constant registry.
18 func NewConstantRegistry() *ConstantRegistry {
19 return &ConstantRegistry{
20 constants: make(map[string]int),
21 }
22 }
23
24 // Register registers a constant name and its integer value.
25 //
26 // Example:
27 //
28 // registry.Register("STREAM_START_EVENT", 1)
29 // registry.Register("PLAIN_SCALAR_STYLE", 2)
30 func (r *ConstantRegistry) Register(name string, value int) {
31 r.constants[name] = value
32 }
33
34 // Resolve looks up a constant name and returns its value.
35 // Returns (value, true) if found, (0, false) if not found.
36 func (r *ConstantRegistry) Resolve(name string) (int, bool) {
37 val, ok := r.constants[name]
38 return val, ok
39 }
40
41 // MustResolve looks up a constant name and returns its value.
42 // Panics if the constant is not registered.
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 // Has checks if a constant is registered.
52 func (r *ConstantRegistry) Has(name string) bool {
53 _, ok := r.constants[name]
54 return ok
55 }
56
57 // MergeFrom merges constants from another registry into this one.
58 // If there are conflicts, values from the other registry take precedence.
59 func (r *ConstantRegistry) MergeFrom(other *ConstantRegistry) {
60 for name, value := range other.constants {
61 r.constants[name] = value
62 }
63 }
64
65 // ListConstants returns a list of all registered constant names.
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 // ResolveIntOrString attempts to parse a value as either:
75 // 1. An integer constant name (returns the resolved value)
76 // 2. A direct integer value
77 // Returns an error if neither works.
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 }