Skip to content

Commit f1f0a25

Browse files
authored
feat: speed up incoming packet processing with a memory view (#1290)
1 parent c2f99d9 commit f1f0a25

2 files changed

Lines changed: 8 additions & 5 deletions

File tree

src/zeroconf/_protocol/incoming.pxd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ cdef class DNSIncoming:
5050
cdef public unsigned int flags
5151
cdef cython.uint offset
5252
cdef public bytes data
53+
cdef const unsigned char [:] view
5354
cdef unsigned int _data_len
5455
cdef public cython.dict name_cache
5556
cdef public cython.list questions

src/zeroconf/_protocol/incoming.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class DNSIncoming:
7878
'flags',
7979
'offset',
8080
'data',
81+
'view',
8182
'_data_len',
8283
'name_cache',
8384
'questions',
@@ -105,6 +106,7 @@ def __init__(
105106
self.flags = 0
106107
self.offset = 0
107108
self.data = data
109+
self.view = data
108110
self._data_len = len(data)
109111
self.name_cache: Dict[int, List[str]] = {}
110112
self.questions: List[DNSQuestion] = []
@@ -228,7 +230,7 @@ def _read_questions(self) -> None:
228230

229231
def _read_character_string(self) -> str:
230232
"""Reads a character string from the packet"""
231-
length = self.data[self.offset]
233+
length = self.view[self.offset]
232234
self.offset += 1
233235
info = self.data[self.offset : self.offset + length].decode('utf-8', 'replace')
234236
self.offset += length
@@ -334,8 +336,8 @@ def _read_bitmap(self, end: _int) -> List[int]:
334336
offset = self.offset
335337
offset_plus_one = offset + 1
336338
offset_plus_two = offset + 2
337-
window = self.data[offset]
338-
bitmap_length = self.data[offset_plus_one]
339+
window = self.view[offset]
340+
bitmap_length = self.view[offset_plus_one]
339341
bitmap_end = offset_plus_two + bitmap_length
340342
for i, byte in enumerate(self.data[offset_plus_two:bitmap_end]):
341343
for bit in range(0, 8):
@@ -361,7 +363,7 @@ def _read_name(self) -> str:
361363
def _decode_labels_at_offset(self, off: _int, labels: List[str], seen_pointers: Set[int]) -> int:
362364
# This is a tight loop that is called frequently, small optimizations can make a difference.
363365
while off < self._data_len:
364-
length = self.data[off]
366+
length = self.view[off]
365367
if length == 0:
366368
return off + DNS_COMPRESSION_HEADER_LEN
367369

@@ -377,7 +379,7 @@ def _decode_labels_at_offset(self, off: _int, labels: List[str], seen_pointers:
377379
)
378380

379381
# We have a DNS compression pointer
380-
link_data = self.data[off + 1]
382+
link_data = self.view[off + 1]
381383
link = (length & 0x3F) * 256 + link_data
382384
link_py_int = link
383385
if link > self._data_len:

0 commit comments

Comments
 (0)