Files
open-im-server/internal/msggateway/new/user_map.go
T

66 lines
1.4 KiB
Go
Raw Normal View History

2023-02-14 21:08:36 +08:00
package new
import "sync"
type UserMap struct {
m sync.Map
}
func newUserMap() *UserMap {
return &UserMap{}
}
2023-02-16 16:32:31 +08:00
func (u *UserMap) GetAll(key string) ([]*Client, bool) {
2023-02-14 21:08:36 +08:00
allClients, ok := u.m.Load(key)
if ok {
2023-02-16 16:32:31 +08:00
return allClients.([]*Client), ok
2023-02-14 21:08:36 +08:00
}
2023-02-16 16:32:31 +08:00
return nil, ok
2023-02-14 21:08:36 +08:00
}
2023-02-16 16:32:31 +08:00
func (u *UserMap) Get(key string, platformID int) (*Client, bool, bool) {
allClients, userExisted := u.m.Load(key)
if userExisted {
2023-02-14 21:08:36 +08:00
for _, client := range allClients.([]*Client) {
2023-02-16 16:32:31 +08:00
if client.platformID == platformID {
return client, userExisted, true
2023-02-14 21:08:36 +08:00
}
}
2023-02-16 16:32:31 +08:00
return nil, userExisted, false
2023-02-14 21:08:36 +08:00
}
2023-02-16 16:32:31 +08:00
return nil, userExisted, false
2023-02-14 21:08:36 +08:00
}
func (u *UserMap) Set(key string, v *Client) {
allClients, existed := u.m.Load(key)
if existed {
oldClients := allClients.([]*Client)
oldClients = append(oldClients, v)
u.m.Store(key, oldClients)
} else {
clients := make([]*Client, 3)
clients = append(clients, v)
u.m.Store(key, clients)
}
}
2023-02-16 16:32:31 +08:00
func (u *UserMap) delete(key string, platformID int) (isDeleteUser bool) {
2023-02-14 21:08:36 +08:00
allClients, existed := u.m.Load(key)
if existed {
oldClients := allClients.([]*Client)
2023-02-16 16:32:31 +08:00
a := make([]*Client, 3)
2023-02-14 21:08:36 +08:00
for _, client := range oldClients {
2023-02-16 16:32:31 +08:00
if client.platformID != platformID {
2023-02-14 21:08:36 +08:00
a = append(a, client)
}
}
if len(a) == 0 {
u.m.Delete(key)
2023-02-16 16:32:31 +08:00
return true
2023-02-14 21:08:36 +08:00
} else {
u.m.Store(key, a)
2023-02-16 16:32:31 +08:00
return false
2023-02-14 21:08:36 +08:00
}
}
2023-02-16 16:32:31 +08:00
return existed
2023-02-14 21:08:36 +08:00
}
func (u *UserMap) DeleteAll(key string) {
u.m.Delete(key)
}