Просмотр исходного кода

util/set: add a basic map-based Set type

We have two other types of Sets here. Add the basic obvious one too.

Needed for a change elsewhere.

Updates #cleanup

Signed-off-by: Brad Fitzpatrick <[email protected]>
Brad Fitzpatrick 2 лет назад
Родитель
Сommit
b69059334b
2 измененных файлов с 39 добавлено и 0 удалено
  1. 15 0
      util/set/set.go
  2. 24 0
      util/set/set_test.go

+ 15 - 0
util/set/set.go

@@ -4,6 +4,21 @@
 // Package set contains set types.
 package set
 
+// Set is a set of T.
+type Set[T comparable] map[T]struct{}
+
+// Add adds e to the set.
+func (s Set[T]) Add(e T) { s[e] = struct{}{} }
+
+// Contains reports whether s contains e.
+func (s Set[T]) Contains(e T) bool {
+	_, ok := s[e]
+	return ok
+}
+
+// Len reports the number of items in s.
+func (s Set[T]) Len() int { return len(s) }
+
 // HandleSet is a set of T.
 //
 // It is not safe for concurrent use.

+ 24 - 0
util/set/set_test.go

@@ -0,0 +1,24 @@
+// Copyright (c) Tailscale Inc & AUTHORS
+// SPDX-License-Identifier: BSD-3-Clause
+
+package set
+
+import "testing"
+
+func TestSet(t *testing.T) {
+	s := Set[int]{}
+	s.Add(1)
+	s.Add(2)
+	if !s.Contains(1) {
+		t.Error("missing 1")
+	}
+	if !s.Contains(2) {
+		t.Error("missing 2")
+	}
+	if s.Contains(3) {
+		t.Error("shouldn't have 3")
+	}
+	if s.Len() != 2 {
+		t.Errorf("wrong len %d; want 2", s.Len())
+	}
+}