2022-10-27 16:00:57 +02:00
|
|
|
package dataext
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
2022-12-22 10:23:34 +01:00
|
|
|
type SyncSet[TData comparable] struct {
|
|
|
|
data map[TData]bool
|
2022-10-27 16:00:57 +02:00
|
|
|
lock sync.Mutex
|
|
|
|
}
|
|
|
|
|
2023-08-08 15:28:29 +02:00
|
|
|
// Add adds `value` to the set
|
|
|
|
// returns true if the value was actually inserted
|
|
|
|
// returns false if the value already existed
|
2022-12-22 10:23:34 +01:00
|
|
|
func (s *SyncSet[TData]) Add(value TData) bool {
|
2022-10-27 16:00:57 +02:00
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
|
|
|
|
if s.data == nil {
|
2022-12-22 10:23:34 +01:00
|
|
|
s.data = make(map[TData]bool)
|
2022-10-27 16:00:57 +02:00
|
|
|
}
|
|
|
|
|
2023-08-08 15:28:29 +02:00
|
|
|
_, existsInPreState := s.data[value]
|
2022-10-27 16:00:57 +02:00
|
|
|
s.data[value] = true
|
|
|
|
|
2023-08-08 15:28:29 +02:00
|
|
|
return !existsInPreState
|
2022-10-27 16:00:57 +02:00
|
|
|
}
|
|
|
|
|
2022-12-22 10:23:34 +01:00
|
|
|
func (s *SyncSet[TData]) AddAll(values []TData) {
|
2022-10-27 16:00:57 +02:00
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
|
|
|
|
if s.data == nil {
|
2022-12-22 10:23:34 +01:00
|
|
|
s.data = make(map[TData]bool)
|
2022-10-27 16:00:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, value := range values {
|
|
|
|
s.data[value] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-22 10:23:34 +01:00
|
|
|
func (s *SyncSet[TData]) Contains(value TData) bool {
|
2022-10-27 16:00:57 +02:00
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
|
|
|
|
if s.data == nil {
|
2022-12-22 10:23:34 +01:00
|
|
|
s.data = make(map[TData]bool)
|
2022-10-27 16:00:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
_, ok := s.data[value]
|
|
|
|
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2022-12-22 10:23:34 +01:00
|
|
|
func (s *SyncSet[TData]) Get() []TData {
|
2022-10-27 16:00:57 +02:00
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
|
|
|
|
if s.data == nil {
|
2022-12-22 10:23:34 +01:00
|
|
|
s.data = make(map[TData]bool)
|
2022-10-27 16:00:57 +02:00
|
|
|
}
|
|
|
|
|
2022-12-22 10:23:34 +01:00
|
|
|
r := make([]TData, 0, len(s.data))
|
2022-10-27 16:00:57 +02:00
|
|
|
|
|
|
|
for k := range s.data {
|
|
|
|
r = append(r, k)
|
|
|
|
}
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|