summaryrefslogtreecommitdiffstats
path: root/common
diff options
context:
space:
mode:
Diffstat (limited to 'common')
-rw-r--r--common/collections/slice.go20
-rw-r--r--common/collections/slice_test.go15
2 files changed, 35 insertions, 0 deletions
diff --git a/common/collections/slice.go b/common/collections/slice.go
index 51cb6ec1f..bf5c7b52b 100644
--- a/common/collections/slice.go
+++ b/common/collections/slice.go
@@ -15,6 +15,7 @@ package collections
import (
"reflect"
+ "sort"
)
// Slicer defines a very generic way to create a typed slice. This is used
@@ -74,3 +75,22 @@ func StringSliceToInterfaceSlice(ss []string) []any {
return result
}
+
+type SortedStringSlice []string
+
+// Contains returns true if s is in ss.
+func (ss SortedStringSlice) Contains(s string) bool {
+ i := sort.SearchStrings(ss, s)
+ return i < len(ss) && ss[i] == s
+}
+
+// Count returns the number of times s is in ss.
+func (ss SortedStringSlice) Count(s string) int {
+ var count int
+ i := sort.SearchStrings(ss, s)
+ for i < len(ss) && ss[i] == s {
+ count++
+ i++
+ }
+ return count
+}
diff --git a/common/collections/slice_test.go b/common/collections/slice_test.go
index 8e6553994..5788b9161 100644
--- a/common/collections/slice_test.go
+++ b/common/collections/slice_test.go
@@ -122,3 +122,18 @@ func TestSlice(t *testing.T) {
c.Assert(test.expected, qt.DeepEquals, result, errMsg)
}
}
+
+func TestSortedStringSlice(t *testing.T) {
+ t.Parallel()
+ c := qt.New(t)
+
+ var s SortedStringSlice = []string{"a", "b", "b", "b", "c", "d"}
+
+ c.Assert(s.Contains("a"), qt.IsTrue)
+ c.Assert(s.Contains("b"), qt.IsTrue)
+ c.Assert(s.Contains("z"), qt.IsFalse)
+ c.Assert(s.Count("b"), qt.Equals, 3)
+ c.Assert(s.Count("z"), qt.Equals, 0)
+ c.Assert(s.Count("a"), qt.Equals, 1)
+
+}