feat: optimize DNSCache.get_by_details (#1254) · python-zeroconf/python-zeroconf@ce59787

@@ -147,7 +147,7 @@ def async_all_by_details(self, name: _str, type_: _int, class_: _int) -> List[DN

147147

if records is None:

148148

return matches

149149

for record in records:

150-

if _dns_record_matches(record, key, type_, class_):

150+

if type_ == record.type and class_ == record.class_:

151151

matches.append(record)

152152

return matches

153153

@@ -181,7 +181,7 @@ def get(self, entry: DNSEntry) -> Optional[DNSRecord]:

181181

return cached_entry

182182

return None

183183184-

def get_by_details(self, name: str, type_: int, class_: int) -> Optional[DNSRecord]:

184+

def get_by_details(self, name: str, type_: _int, class_: _int) -> Optional[DNSRecord]:

185185

"""Gets the first matching entry by details. Returns None if no entries match.

186186187187

Calling this function is not recommended as it will only

@@ -194,17 +194,21 @@ def get_by_details(self, name: str, type_: int, class_: int) -> Optional[DNSReco

194194

Use get_all_by_details instead.

195195

"""

196196

key = name.lower()

197-

for cached_entry in reversed(list(self.cache.get(key, []))):

198-

if _dns_record_matches(cached_entry, key, type_, class_):

197+

records = self.cache.get(key)

198+

if records is None:

199+

return None

200+

for cached_entry in reversed(list(records)):

201+

if type_ == cached_entry.type and class_ == cached_entry.class_:

199202

return cached_entry

200203

return None

201204202-

def get_all_by_details(self, name: str, type_: int, class_: int) -> List[DNSRecord]:

205+

def get_all_by_details(self, name: str, type_: _int, class_: _int) -> List[DNSRecord]:

203206

"""Gets all matching entries by details."""

204207

key = name.lower()

205-

return [

206-

entry for entry in list(self.cache.get(key, [])) if _dns_record_matches(entry, key, type_, class_)

207-

]

208+

records = self.cache.get(key)

209+

if records is None:

210+

return []

211+

return [entry for entry in list(records) if type_ == entry.type and class_ == entry.class_]

208212209213

def entries_with_server(self, server: str) -> List[DNSRecord]:

210214

"""Returns a list of entries whose server matches the name."""

@@ -243,7 +247,3 @@ def async_mark_unique_records_older_than_1s_to_expire(

243247

if (now - created_float > _ONE_SECOND) and record not in answers_rrset:

244248

# Expire in 1s

245249

record.set_created_ttl(now, 1)

246-247-248-

def _dns_record_matches(record: _DNSRecord, key: _str, type_: _int, class_: _int) -> bool:

249-

return key == record.key and type_ == record.type and class_ == record.class_