From e89cfdc80dc826c7dfdd6d79f600fdef13c62ee0 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 27 Mar 2024 11:18:16 +0300 Subject: [PATCH] move sort.Uniq to dedicated package Signed-off-by: Vasiliy Tolstov --- tracer/tracer.go | 38 +------------------------------------- util/sort/sort.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 37 deletions(-) create mode 100644 util/sort/sort.go diff --git a/tracer/tracer.go b/tracer/tracer.go index de3f6a7e..e2634305 100644 --- a/tracer/tracer.go +++ b/tracer/tracer.go @@ -1,10 +1,8 @@ // Package tracer provides an interface for distributed tracing -package tracer // import "go.unistack.org/micro/v4/tracer" +package tracer import ( "context" - "fmt" - "sort" "go.unistack.org/micro/v4/logger" "go.unistack.org/micro/v4/options" @@ -71,37 +69,3 @@ type Span interface { // SpanID returns span id SpanID() string } - -// sort labels alphabeticaly by label name -type byKey []interface{} - -func (k byKey) Len() int { return len(k) / 2 } -func (k byKey) Less(i, j int) bool { return fmt.Sprintf("%s", k[i*2]) < fmt.Sprintf("%s", k[j*2]) } -func (k byKey) Swap(i, j int) { - k[i*2], k[j*2] = k[j*2], k[i*2] - k[i*2+1], k[j*2+1] = k[j*2+1], k[i*2+1] -} - -func UniqLabels(labels []interface{}) []interface{} { - if len(labels)%2 == 1 { - labels = labels[:len(labels)-1] - } - - if len(labels) > 2 { - sort.Sort(byKey(labels)) - - idx := 0 - for { - if labels[idx] == labels[idx+2] { - copy(labels[idx:], labels[idx+2:]) - labels = labels[:len(labels)-2] - } else { - idx += 2 - } - if idx+2 >= len(labels) { - break - } - } - } - return labels -} diff --git a/util/sort/sort.go b/util/sort/sort.go new file mode 100644 index 00000000..d80794b1 --- /dev/null +++ b/util/sort/sort.go @@ -0,0 +1,40 @@ +package sort + +import ( + "fmt" + "sort" +) + +// sort labels alphabeticaly by label name +type byKey []interface{} + +func (k byKey) Len() int { return len(k) / 2 } +func (k byKey) Less(i, j int) bool { return fmt.Sprintf("%s", k[i*2]) < fmt.Sprintf("%s", k[j*2]) } +func (k byKey) Swap(i, j int) { + k[i*2], k[j*2] = k[j*2], k[i*2] + k[i*2+1], k[j*2+1] = k[j*2+1], k[i*2+1] +} + +func Uniq(labels []interface{}) []interface{} { + if len(labels)%2 == 1 { + labels = labels[:len(labels)-1] + } + + if len(labels) > 2 { + sort.Sort(byKey(labels)) + + idx := 0 + for { + if labels[idx] == labels[idx+2] { + copy(labels[idx:], labels[idx+2:]) + labels = labels[:len(labels)-2] + } else { + idx += 2 + } + if idx+2 >= len(labels) { + break + } + } + } + return labels +}