Skip to content

Commit b3659d7

Browse files
committed
Re-optimize the O(1) code path
1 parent 8267056 commit b3659d7

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

msal/token_cache.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def _get(self, credential_type, key, default=None): # O(1)
118118
return self._cache.get(credential_type, {}).get(key, default)
119119

120120
@staticmethod
121-
def _is_matching(entry: dict, query: dict, target_set: set):
121+
def _is_matching(entry: dict, query: dict, target_set: set = None) -> bool:
122122
return is_subdict_of(query or {}, entry) and (
123123
target_set <= set(entry.get("target", "").split())
124124
if target_set else True)
@@ -131,7 +131,6 @@ def _find(self, credential_type, target=None, query=None): # O(n) generator
131131
"""
132132
target = sorted(target or []) # Match the order sorted by add()
133133
assert isinstance(target, list), "Invalid parameter type"
134-
target_set = set(target)
135134

136135
preferred_result = None
137136
if (credential_type == self.CredentialType.ACCESS_TOKEN
@@ -143,17 +142,19 @@ def _find(self, credential_type, target=None, query=None): # O(n) generator
143142
query["home_account_id"], query["environment"],
144143
query["client_id"], query["realm"], target)
145144
if preferred_result and self._is_matching(
146-
preferred_result, query, target_set,
145+
preferred_result, query,
146+
# Needs no target_set here because it is satisfied by dict key
147147
):
148148
yield preferred_result
149149

150+
target_set = set(target)
150151
with self._lock:
151152
# Since the target inside token cache key is (per schema) unsorted,
152153
# there is no point to attempt an O(1) key-value search here.
153154
# So we always do an O(n) in-memory search.
154155
for entry in self._cache.get(credential_type, {}).values():
155156
if (entry != preferred_result # Avoid yielding the same entry twice
156-
and self._is_matching(entry, query, target_set)
157+
and self._is_matching(entry, query, target_set=target_set)
157158
):
158159
yield entry
159160

0 commit comments

Comments
 (0)