/
device_lists.go
77 lines (69 loc) · 1.36 KB
/
device_lists.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package internal
import (
"database/sql/driver"
"encoding/json"
)
const (
DeviceListChanged = 1
DeviceListLeft = 2
)
type DeviceLists struct {
// map user_id -> DeviceList enum
New MapStringInt `json:"n"`
Sent MapStringInt `json:"s"`
}
type MapStringInt map[string]int
// Value implements driver.Valuer
func (dl MapStringInt) Value() (driver.Value, error) {
if len(dl) == 0 {
return "{}", nil
}
v, err := json.Marshal(dl)
return v, err
}
func (dl DeviceLists) Combine(newer DeviceLists) DeviceLists {
n := dl.New
if n == nil {
n = make(map[string]int)
}
for k, v := range newer.New {
n[k] = v
}
s := dl.Sent
if s == nil {
s = make(map[string]int)
}
for k, v := range newer.Sent {
s[k] = v
}
return DeviceLists{
New: n,
Sent: s,
}
}
func ToDeviceListChangesMap(changed, left []string) map[string]int {
if len(changed) == 0 && len(left) == 0 {
return nil
}
m := make(map[string]int)
for _, userID := range changed {
m[userID] = DeviceListChanged
}
for _, userID := range left {
m[userID] = DeviceListLeft
}
return m
}
func DeviceListChangesArrays(m map[string]int) (changed, left []string) {
changed = make([]string, 0)
left = make([]string, 0)
for userID, state := range m {
switch state {
case DeviceListChanged:
changed = append(changed, userID)
case DeviceListLeft:
left = append(left, userID)
}
}
return
}