Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.

Commit 3d7602a

Browse files
committed
refactor(keyexchange): Tidy up useGroupKey with switch instead of multiple if + early return.
1 parent 0f30ab2 commit 3d7602a

File tree

1 file changed

+33
-31
lines changed

1 file changed

+33
-31
lines changed

src/stream/KeyExchange.js

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -106,38 +106,40 @@ function GroupKeyStore({ groupKeys = new Map() }) {
106106
},
107107
useGroupKey() {
108108
const nextGroupKey = nextGroupKeys.pop()
109-
// first message
110-
if (!currentGroupKeyId && nextGroupKey) {
111-
storeKey(nextGroupKey)
112-
currentGroupKeyId = nextGroupKey.id
113-
return [
114-
this.get(currentGroupKeyId),
115-
undefined,
116-
]
117-
}
118-
119-
// key changed
120-
if (currentGroupKeyId && nextGroupKey) {
121-
storeKey(nextGroupKey)
122-
const prevGroupKey = this.get(currentGroupKeyId)
123-
currentGroupKeyId = nextGroupKey.id
124-
// use current key one more time
125-
return [
126-
prevGroupKey,
127-
nextGroupKey,
128-
]
129-
}
130-
131-
// generate & use key if none already set
132-
if (!currentGroupKeyId) {
133-
this.rotateGroupKey()
134-
return this.useGroupKey()
109+
switch (true) {
110+
// First use of group key on this stream, no current key. Make next key current.
111+
case (!currentGroupKeyId && nextGroupKey): {
112+
storeKey(nextGroupKey)
113+
currentGroupKeyId = nextGroupKey.id
114+
return [
115+
this.get(currentGroupKeyId),
116+
undefined,
117+
]
118+
}
119+
// Keep using current key (empty next)
120+
case (currentGroupKeyId && !nextGroupKey): {
121+
return [
122+
this.get(currentGroupKeyId),
123+
undefined
124+
]
125+
}
126+
// Key changed (non-empty next). return current + next. Make next key current.
127+
case (currentGroupKeyId && nextGroupKey): {
128+
storeKey(nextGroupKey)
129+
const prevGroupKey = this.get(currentGroupKeyId)
130+
currentGroupKeyId = nextGroupKey.id
131+
// use current key one more time
132+
return [
133+
prevGroupKey,
134+
nextGroupKey,
135+
]
136+
}
137+
// Generate & use new key if none already set.
138+
default: {
139+
this.rotateGroupKey()
140+
return this.useGroupKey()
141+
}
135142
}
136-
137-
return [
138-
this.get(currentGroupKeyId),
139-
nextGroupKey
140-
]
141143
},
142144
get(groupKeyId) {
143145
const groupKey = store.get(groupKeyId)

0 commit comments

Comments
 (0)