71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
package cache
|
|
|
|
import "sync"
|
|
|
|
type Cache struct {
|
|
mu sync.RWMutex
|
|
s2c map[string]string
|
|
c2s map[string]string
|
|
}
|
|
|
|
func NewCache() *Cache {
|
|
return &Cache{
|
|
s2c: make(map[string]string),
|
|
c2s: make(map[string]string),
|
|
}
|
|
}
|
|
|
|
// Set creates or overwrites the pair a -> b and b -> a.
|
|
// It ensures any previous mappings involving a or b are removed first.
|
|
func (c *Cache) Set(serverId, channelId string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
if old, ok := c.s2c[serverId]; ok && old != channelId {
|
|
delete(c.c2s, old)
|
|
}
|
|
|
|
if old, ok := c.c2s[channelId]; ok && old != serverId {
|
|
delete(c.s2c, old)
|
|
}
|
|
|
|
c.s2c[serverId] = channelId
|
|
c.c2s[channelId] = serverId
|
|
}
|
|
|
|
func (c *Cache) GetByServerId(serverId string) (string, bool) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
cId, ok := c.s2c[serverId]
|
|
return cId, ok
|
|
}
|
|
|
|
func (c *Cache) GetByChannelId(channelId string) (string, bool) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
sId, ok := c.c2s[channelId]
|
|
return sId, ok
|
|
}
|
|
|
|
func (c *Cache) RemoveByServerId(serverId string) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
if channelId, ok := c.s2c[serverId]; ok {
|
|
delete(c.s2c, serverId)
|
|
delete(c.c2s, channelId)
|
|
}
|
|
}
|
|
|
|
func (c *Cache) RemoveByChannelId(channelId string) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
if serverId, ok := c.s2c[channelId]; ok {
|
|
delete(c.c2s, channelId)
|
|
delete(c.s2c, serverId)
|
|
}
|
|
}
|