From b7dc4fa4be1dadefd799ccc7ec843524c9e3fc29 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sun, 24 May 2026 18:14:35 +0300 Subject: fix(rpn): replace parseCategory iota loop with O(1) map lookup (task zj) --- internal/rpn/metric_type.go | 9 +++++++++ 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. -- cgit v1.2.3