From e0132bb4bc37884a104f38008bf9bf625de1e306 Mon Sep 17 00:00:00 2001 From: William Dillon Date: Sun, 25 May 2025 17:30:53 -0400 Subject: [PATCH] adding slice methods --- set.go | 3 +++ simpleset/simpleset.go | 24 ++++++++++++++++++++++++ threadsafeset/threadsafeset.go | 18 ++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/set.go b/set.go index 7e02172..4dedd11 100644 --- a/set.go +++ b/set.go @@ -7,8 +7,11 @@ import ( type Set[T comparable] interface { Insert(T) (inserted bool) + InsertSlice([]T) (inserted []bool) Contains(T) bool + ContainsSlice([]T) []bool Remove(T) (removed bool) + RemoveSlice([]T) (removed []bool) Len() int ToSlice() []T Clear() diff --git a/simpleset/simpleset.go b/simpleset/simpleset.go index 91c2aec..6a84f7c 100644 --- a/simpleset/simpleset.go +++ b/simpleset/simpleset.go @@ -26,12 +26,28 @@ func (s *SimpleSet[T]) Insert(t T) (inserted bool) { } } +func (s *SimpleSet[T]) InsertSlice(slice []T) (inserted []bool) { + inserted = make([]bool, 0, len(slice)) + for _, t := range slice { + inserted = append(inserted, s.Insert(t)) + } + return inserted +} + func (s *SimpleSet[T]) Contains(t T) bool { s.lockedInitMapIfNil() _, found := s.set[t] return found } +func (s *SimpleSet[T]) ContainsSlice(slice []T) []bool { + results := make([]bool, 0, len(slice)) + for _, t := range slice { + results = append(results, s.Contains(t)) + } + return results +} + func (s *SimpleSet[T]) Len() int { s.lockedInitMapIfNil() return len(s.set) @@ -57,3 +73,11 @@ func (s *SimpleSet[T]) Remove(t T) (removed bool) { delete(s.set, t) return true } + +func (s *SimpleSet[T]) RemoveSlice(slice []T) (removed []bool) { + removed = make([]bool, 0, len(slice)) + for _, t := range slice { + removed = append(removed, s.Remove(t)) + } + return removed +} diff --git a/threadsafeset/threadsafeset.go b/threadsafeset/threadsafeset.go index 0a7e578..2beebcc 100644 --- a/threadsafeset/threadsafeset.go +++ b/threadsafeset/threadsafeset.go @@ -30,12 +30,24 @@ func (s *ThreadsafeSet[T]) Insert(t T) (inserted bool) { return s.set.Insert(t) } +func (s *ThreadsafeSet[T]) InsertSlice(slice []T) (inserted []bool) { + s.mutex.Lock() + defer s.mutex.Unlock() + return s.set.InsertSlice(slice) +} + func (s *ThreadsafeSet[T]) Contains(t T) bool { s.mutex.RLock() defer s.mutex.RUnlock() return s.set != nil && s.set.Contains(t) } +func (s *ThreadsafeSet[T]) ContainsSlice(slice []T) []bool { + s.mutex.RLock() + defer s.mutex.RUnlock() + return s.set.ContainsSlice(slice) +} + func (s *ThreadsafeSet[T]) Len() int { s.mutex.RLock() defer s.mutex.RUnlock() @@ -67,3 +79,9 @@ func (s *ThreadsafeSet[T]) Remove(t T) (removed bool) { s.lockedInitMapIfNil() return s.set.Remove(t) } + +func (s *ThreadsafeSet[T]) RemoveSlice(slice []T) (removed []bool) { + s.mutex.Lock() + defer s.mutex.Unlock() + return s.set.RemoveSlice(slice) +}