diff options
| author | Paul Buetow <paul@buetow.org> | 2026-05-24 18:14:35 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2026-05-24 18:14:35 +0300 |
| commit | b7dc4fa4be1dadefd799ccc7ec843524c9e3fc29 (patch) | |
| tree | 7ad30ffa8e33377ef81be680a8b504a8ca96468d | |
| parent | 5fddbbf194085205977c8ca652c97ffb6ec7f522 (diff) | |
fix(rpn): replace parseCategory iota loop with O(1) map lookup (task zj)
| -rw-r--r-- | internal/rpn/metric_type.go | 9 | ||||
| -rw-r--r-- | internal/rpn/operations_metric_cmd.go | 13 |
2 files changed, 14 insertions, 8 deletions
diff --git a/internal/rpn/metric_type.go b/internal/rpn/metric_type.go index 9d92fb1..49e3236 100644 --- a/internal/rpn/metric_type.go +++ b/internal/rpn/metric_type.go @@ -49,6 +49,15 @@ var categoryNames = []string{ "Custom", } +// categoryByName provides O(1) lookup from category name to Category value. +var categoryByName = func() map[string]Category { + m := make(map[string]Category, len(categoryNames)) + for i, name := range categoryNames { + m[name] = Category(i) + } + return m +}() + // String returns the human-readable name of the category. func (c Category) String() string { if c >= 0 && c < Category(len(categoryNames)) { diff --git a/internal/rpn/operations_metric_cmd.go b/internal/rpn/operations_metric_cmd.go index bde134b..255daed 100644 --- a/internal/rpn/operations_metric_cmd.go +++ b/internal/rpn/operations_metric_cmd.go @@ -81,16 +81,13 @@ func (o *Operations) MetricCompatible(stack *Stack) (string, error) { } // parseCategory converts a category name string to a Category constant. -// Iterates over all valid Category values using a for loop bounded by _sentinel, -// so adding a new Category constant (between Universal and _sentinel) automatically -// makes it available here without modifying this function. +// Uses a pre-built map for O(1) lookup. func parseCategory(name string) (Category, bool) { - for cat := Category(0); cat < _sentinel; cat++ { - if cat.String() == name { - return cat, true - } + cat, ok := categoryByName[name] + if !ok { + return invalidCategory, false } - return invalidCategory, false + return cat, true } // CustomShow returns detailed info for custom metrics. |
