forked from bborbe/collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset-equal.go
76 lines (63 loc) · 1.25 KB
/
set-equal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) 2024 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package collection
import (
"sync"
)
type HasEqual[V any] interface {
Equal(value V) bool
}
type SetEqual[T HasEqual[T]] interface {
Add(element T)
Remove(element T)
Contains(element T) bool
Slice() []T
}
func NewSetEqual[T HasEqual[T]]() SetEqual[T] {
return &setEqual[T]{
data: make([]T, 0),
}
}
type setEqual[T HasEqual[T]] struct {
mux sync.Mutex
data []T
}
func (s *setEqual[T]) Add(element T) {
s.mux.Lock()
defer s.mux.Unlock()
if s.contains(element) {
return
}
s.data = append(s.data, element)
}
func (s *setEqual[T]) Remove(element T) {
s.mux.Lock()
defer s.mux.Unlock()
result := make([]T, 0, len(s.data))
for _, e := range s.data {
if e.Equal(element) {
continue
}
result = append(result, e)
}
s.data = result
}
func (s *setEqual[T]) Contains(element T) bool {
s.mux.Lock()
defer s.mux.Unlock()
return s.contains(element)
}
func (s *setEqual[T]) contains(element T) bool {
for _, e := range s.data {
if e.Equal(element) {
return true
}
}
return false
}
func (s *setEqual[T]) Slice() []T {
s.mux.Lock()
defer s.mux.Unlock()
return Copy(s.data)
}