-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add message ids thread safe structure
- Loading branch information
1 parent
ea2bdbe
commit 7442560
Showing
3 changed files
with
85 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package helpers | ||
|
||
import ( | ||
"maps" | ||
"popstellar/channel" | ||
"slices" | ||
"sync" | ||
) | ||
|
||
// MessageIds provides a thread-safe structure that stores a channel id with its corresponding message ids | ||
type IdsByChannel struct { | ||
sync.RWMutex | ||
table map[string][]string | ||
} | ||
|
||
func NewIdsByChannel() IdsByChannel { | ||
return IdsByChannel{ | ||
table: make(map[string][]string), | ||
} | ||
} | ||
|
||
func (i *IdsByChannel) Add(channel string, id string) { | ||
i.Lock() | ||
defer i.Unlock() | ||
messageIds, channelStored := i.table[channel] | ||
if !channelStored { | ||
i.table[channel] = append(i.table[channel], id) | ||
return | ||
} | ||
alreadyStoredId := slices.Contains(messageIds, id) | ||
if !alreadyStoredId { | ||
i.table[channel] = append(i.table[channel], id) | ||
} | ||
} | ||
|
||
func (i *IdsByChannel) GetAll() map[string][]string { | ||
i.RLock() | ||
defer i.RUnlock() | ||
tableCopy := make(map[string][]string) | ||
maps.Copy(tableCopy, i.table) | ||
return tableCopy | ||
} | ||
|
||
func (i *IdsByChannel) IsEmpty() bool { | ||
i.RLock() | ||
defer i.RUnlock() | ||
|
||
return len(i.table) == 0 | ||
} | ||
|
||
type ChannelByID struct { | ||
sync.RWMutex | ||
table map[string]channel.Channel | ||
} | ||
|
||
func NewChannelById() ChannelByID { | ||
return ChannelByID{ | ||
table: make(map[string]channel.Channel), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters