Skip to content

Commit cd28476

Browse files
authored
feat: small speed up to writing outgoing packets (#1316)
1 parent 0d60b61 commit cd28476

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

src/zeroconf/_protocol/outgoing.pxd

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ cdef object LOGGING_DEBUG
3232

3333
cdef cython.tuple BYTE_TABLE
3434
cdef cython.tuple SHORT_LOOKUP
35+
cdef cython.dict LONG_LOOKUP
3536

3637
cdef class DNSOutgoing:
3738

@@ -70,7 +71,7 @@ cdef class DNSOutgoing:
7071
index=cython.uint,
7172
length=cython.uint
7273
)
73-
cdef cython.bint _write_record(self, DNSRecord record, object now)
74+
cdef cython.bint _write_record(self, DNSRecord record, float now)
7475

7576
@cython.locals(class_=cython.uint)
7677
cdef _write_record_class(self, DNSEntry record)
@@ -91,7 +92,7 @@ cdef class DNSOutgoing:
9192

9293
cdef bint _has_more_to_add(self, unsigned int questions_offset, unsigned int answer_offset, unsigned int authority_offset, unsigned int additional_offset)
9394

94-
cdef _write_ttl(self, DNSRecord record, object now)
95+
cdef _write_ttl(self, DNSRecord record, float now)
9596

9697
@cython.locals(
9798
labels=cython.list,

src/zeroconf/_protocol/outgoing.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
from .._logger import log
3232
from ..const import (
3333
_CLASS_UNIQUE,
34+
_DNS_HOST_TTL,
35+
_DNS_OTHER_TTL,
3436
_DNS_PACKET_HEADER_LEN,
3537
_FLAGS_QR_MASK,
3638
_FLAGS_QR_QUERY,
@@ -57,6 +59,7 @@
5759

5860
BYTE_TABLE = tuple(PACK_BYTE(i) for i in range(256))
5961
SHORT_LOOKUP = tuple(PACK_SHORT(i) for i in range(SHORT_CACHE_MAX))
62+
LONG_LOOKUP = {i: PACK_LONG(i) for i in (_DNS_OTHER_TTL, _DNS_HOST_TTL, 0)}
6063

6164

6265
class State(enum.Enum):
@@ -242,7 +245,12 @@ def write_short(self, value: int_) -> None:
242245

243246
def _write_int(self, value: Union[float, int]) -> None:
244247
"""Writes an unsigned integer to the packet"""
245-
self.data.append(PACK_LONG(int(value)))
248+
value_as_int = int(value)
249+
long_bytes = LONG_LOOKUP.get(value_as_int)
250+
if long_bytes is not None:
251+
self.data.append(long_bytes)
252+
else:
253+
self.data.append(PACK_LONG(value_as_int))
246254
self.size += 4
247255

248256
def write_string(self, value: bytes_) -> None:

0 commit comments

Comments
 (0)