ContactTable
class
ContactTable
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
78
79
80
81
82
83
84
85
86
static func tableSpec(_ id: Int32) -> ValueBoxTable {
return ValueBoxTable(id: id, keyType: .binary, compactValuesOnCreation: true)
}
private let peerNameIndexTable: PeerNameIndexTable
private func key(_ id: PeerId, sharedKey: ValueBoxKey = ValueBoxKey(length: 8)) -> ValueBoxKey {
sharedKey.setInt64(0, value: id.toInt64())
return sharedKey
}
// get
func get() -> Set<PeerId> {
if let peerIds = self.peerIds {
return peerIds
} else {
var peerIds = Set<PeerId>()
self.valueBox.scan(self.table, keys: { key in
peerIds.insert(PeerId(key.getInt64(0)))
return true
})
self.peerIds = peerIds
return peerIds
}
}
// replace
func replace(_ ids: Set<PeerId>) {
if self.peerIdsBeforeModification == nil {
self.peerIdsBeforeModification = self.get()
}
self.peerIds = ids
}
// clear memory cache
override func clearMemoryCache() {
assert(self.peerIdsBeforeModification == nil)
self.peerIds = nil
}
// transaction update peers
func transactionUpdatedPeers() -> [PeerId: (Bool, Bool)] {
var result: [PeerId: (Bool, Bool)] = [:]
if let peerIdsBeforeModification = self.peerIdsBeforeModification {
if let peerIds = self.peerIds {
let removedPeerIds = peerIdsBeforeModification.subtracting(peerIds)
let addedPeerIds = peerIds.subtracting(peerIdsBeforeModification)
for peerId in removedPeerIds.union(addedPeerIds) {
result[peerId] = (removedPeerIds.contains(peerId), addedPeerIds.contains(peerId))
}
}
}
return result
}
// before commit
override func beforeCommit() {
if let peerIdsBeforeModification = self.peerIdsBeforeModification {
if let peerIds = self.peerIds {
let removedPeerIds = peerIdsBeforeModification.subtracting(peerIds)
let addedPeerIds = peerIds.subtracting(peerIdsBeforeModification)
let sharedKey = self.key(PeerId(0))
for peerId in removedPeerIds {
self.valueBox.remove(self.table, key: self.key(peerId, sharedKey: sharedKey), secure: false)
self.peerNameIndexTable.setPeerCategoryState(peerId: peerId, category: [.contacts], includes: false)
}
for peerId in addedPeerIds {
self.valueBox.set(self.table, key: self.key(peerId, sharedKey: sharedKey), value: MemoryBuffer())
self.peerNameIndexTable.setPeerCategoryState(peerId: peerId, category: [.contacts], includes: true)
}
} else {
assertionFailure()
}
self.peerIdsBeforeModification = nil
}
if !self.useCaches {
self.peerIds = nil
}
}