From e3cdce7ada2be1fdf77a5e15130b4fcef3045c26 Mon Sep 17 00:00:00 2001 From: pg9182 <96569817+pg9182@users.noreply.github.com> Date: Sat, 26 Nov 2022 22:51:50 -0500 Subject: pkg/metricsx: Initial commit --- pkg/metricsx/metricsx.go | 39 ++++++++++++++++++++++++++++++++++++++ pkg/metricsx/metricsx_test.go | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 pkg/metricsx/metricsx.go create mode 100644 pkg/metricsx/metricsx_test.go (limited to 'pkg/metricsx') diff --git a/pkg/metricsx/metricsx.go b/pkg/metricsx/metricsx.go new file mode 100644 index 0000000..bc37843 --- /dev/null +++ b/pkg/metricsx/metricsx.go @@ -0,0 +1,39 @@ +// Package metricsx extends github.com/VictoriaMetrics/metrics. +package metricsx + +import "strings" + +func splitName(name string) (base, arg string) { + if n := len(name); n != 0 { + base = name + for i, r := range base { + if r == '{' { + if j := len(base) - 1; j > i && base[j] == '}' { + base, arg = base[:i], base[i+1:j] + break + } + } + } + } + return +} + +func formatName(base, arg string, args ...string) string { + var b strings.Builder + b.WriteString(base) + b.WriteByte('{') + if arg != "" { + b.WriteString(arg) + } + for i := 1; i < len(args); i += 2 { + if arg != "" || i > 1 { + b.WriteByte(',') + } + b.WriteString(args[i-1]) + b.WriteString("=\"") + b.WriteString(args[i]) + b.WriteByte('"') + } + b.WriteByte('}') + return b.String() +} diff --git a/pkg/metricsx/metricsx_test.go b/pkg/metricsx/metricsx_test.go new file mode 100644 index 0000000..5bcf8ab --- /dev/null +++ b/pkg/metricsx/metricsx_test.go @@ -0,0 +1,44 @@ +package metricsx + +import "testing" + +func TestSplitName(t *testing.T) { + for _, c := range [][3]string{ + // valid + {`test`, `test`, ``}, + {`test{}`, `test`, ``}, + {`test{test=""}`, `test`, `test=""`}, + {`test{test="{}"}`, `test`, `test="{}"`}, + + // invalid + {``, ``, ``}, + {`test{`, `test{`, ``}, + {`test}`, `test}`, ``}, + {`test}{`, `test}{`, ``}, + {`test{}{}`, `test`, `}{`}, + {`test{}{test}`, `test`, `}{test`}, + {`test{test{}}`, `test`, `test{}`}, + {`test{}{test{}}`, `test`, `}{test{}`}, + } { + name, xbase, xarg := c[0], c[1], c[2] + if base, arg := splitName(name); base != xbase || arg != xarg { + t.Errorf("split %#q: expected (%#q, %#q), got (%#q, %#q)", name, xbase, xarg, base, arg) + } + } +} + +func TestFormatName(t *testing.T) { + for _, c := range [][]string{ + {`test{}`, `test`, ``}, + {`test{a="1"}`, `test`, `a="1"`}, + {`test{a="1",b="2"}`, `test`, `a="1"`, `b`, `2`}, + {`test{a="1",b="2"}`, `test`, `a="1",b="2"`}, + {`test{a="1",b="2",c="3"}`, `test`, `a="1"`, `b`, `2`, `c`, `3`}, + {`test{a="1",b="2",c="3"}`, `test`, `a="1",b="2"`, `c`, `3`}, + } { + exp, base, arg, args := c[0], c[1], c[2], c[3:] + if act := formatName(base, arg, args...); act != exp { + t.Errorf("format (%#q, %#q, %#q, %#q): expected %#q, got %#q", exp, base, arg, args, exp, act) + } + } +} -- cgit v1.2.3