aboutsummaryrefslogtreecommitdiff
path: root/telegram/cache
diff options
context:
space:
mode:
authorbodqhrohro <bodqhrohro@gmail.com>2019-12-28 05:35:40 +0300
committerbodqhrohro <bodqhrohro@gmail.com>2019-12-28 05:35:40 +0300
commit536451f648bce43aa34e90a9154adf831027dae7 (patch)
tree36c66093319e3972f97a141c68e332e25d468331 /telegram/cache
parentfdc8397b93ed355cb931646f0c4eda496ce0e858 (diff)
Make the chats/users cache thread-safe
Diffstat (limited to 'telegram/cache')
-rw-r--r--telegram/cache/cache.go84
1 files changed, 84 insertions, 0 deletions
diff --git a/telegram/cache/cache.go b/telegram/cache/cache.go
new file mode 100644
index 0000000..d1d16f9
--- /dev/null
+++ b/telegram/cache/cache.go
@@ -0,0 +1,84 @@
+package cache
+
+import (
+ "sync"
+
+ "github.com/zelenin/go-tdlib/client"
+)
+
+// Cache allows operating the chats and users cache in
+// a thread-safe manner
+type Cache struct {
+ chats map[int64]*client.Chat
+ users map[int32]*client.User
+ chatsLock sync.Mutex
+ usersLock sync.Mutex
+}
+
+// NewCache initializes a cache
+func NewCache() *Cache {
+ return &Cache{
+ chats: map[int64]*client.Chat{},
+ users: map[int32]*client.User{},
+ }
+}
+
+// ChatsKeys grabs chat ids synchronously to avoid lockups
+// while they are used
+func (cache *Cache) ChatsKeys() []int64 {
+ cache.chatsLock.Lock()
+ defer cache.chatsLock.Unlock()
+
+ var keys []int64
+ for id := range cache.chats {
+ keys = append(keys, id)
+ }
+ return keys
+}
+
+// UsersKeys grabs user ids synchronously to avoid lockups
+// while they are used
+func (cache *Cache) UsersKeys() []int32 {
+ cache.usersLock.Lock()
+ defer cache.usersLock.Unlock()
+
+ var keys []int32
+ for id := range cache.users {
+ keys = append(keys, id)
+ }
+ return keys
+}
+
+// GetChat retrieves chat by id if it's present in the cache
+func (cache *Cache) GetChat(id int64) (*client.Chat, bool) {
+ cache.chatsLock.Lock()
+ defer cache.chatsLock.Unlock()
+
+ chat, ok := cache.chats[id]
+ return chat, ok
+}
+
+// GetUser retrieves user by id if it's present in the cache
+func (cache *Cache) GetUser(id int32) (*client.User, bool) {
+ cache.usersLock.Lock()
+ defer cache.usersLock.Unlock()
+
+ user, ok := cache.users[id]
+ return user, ok
+}
+
+// SetChat stores a chat in the cache
+func (cache *Cache) SetChat(id int64, chat *client.Chat) {
+ cache.chatsLock.Lock()
+ defer cache.chatsLock.Unlock()
+
+ cache.chats[id] = chat
+}
+
+// SetUser stores a user in the cache
+func (cache *Cache) SetUser(id int32, user *client.User) {
+ cache.usersLock.Lock()
+ defer cache.usersLock.Unlock()
+
+ cache.users[id] = user
+}