1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-05 22:44:55 +00:00
arikawa/state/store/defaultstore/emoji.go
diamondburned c6679dc52c State: Separate Store into smaller interfaces, Cabinet API
This commit refactors the Store interface in State into smaller
interfaces in package store. These interfaces are combined into one
structure called a "Cabinet". The default implementation of those
interfaces have been rewritten in package defaultstore, while the old
no-op implementation stays with the store package.

This commit also omitted several state handlers for user events, as it
is unclear what they are actually structured like.
2020-11-29 16:57:58 -08:00

85 lines
1.5 KiB
Go

package defaultstore
import (
"sync"
"github.com/diamondburned/arikawa/v2/discord"
"github.com/diamondburned/arikawa/v2/internal/moreatomic"
"github.com/diamondburned/arikawa/v2/state/store"
)
type Emoji struct {
guilds moreatomic.Map
}
type emojis struct {
mut sync.Mutex
emojis []discord.Emoji
}
var _ store.EmojiStore = (*Emoji)(nil)
func NewEmoji() *Emoji {
return &Emoji{
guilds: *moreatomic.NewMap(func() interface{} {
return &emojis{
emojis: []discord.Emoji{},
}
}),
}
}
func (s *Emoji) Reset() error {
s.guilds.Reset()
return nil
}
func (s *Emoji) Emoji(guildID discord.GuildID, emojiID discord.EmojiID) (*discord.Emoji, error) {
iv, ok := s.guilds.Load(guildID)
if !ok {
return nil, store.ErrNotFound
}
es := iv.(*emojis)
es.mut.Lock()
defer es.mut.Unlock()
for _, emoji := range es.emojis {
if emoji.ID == emojiID {
// Emoji is an implicit copy made by range, so we could do this
// safely.
return &emoji, nil
}
}
return nil, store.ErrNotFound
}
func (s *Emoji) Emojis(guildID discord.GuildID) ([]discord.Emoji, error) {
iv, ok := s.guilds.Load(guildID)
if !ok {
return nil, store.ErrNotFound
}
es := iv.(*emojis)
es.mut.Lock()
defer es.mut.Unlock()
// We're never modifying the slice internals ourselves, so this is fine.
return es.emojis, nil
}
func (s *Emoji) EmojiSet(guildID discord.GuildID, allEmojis []discord.Emoji) error {
iv, _ := s.guilds.LoadOrStore(guildID)
es := iv.(*emojis)
es.mut.Lock()
es.emojis = allEmojis
es.mut.Unlock()
return nil
}