Skip to content

Commit

Permalink
feat: small speed up to writing outgoing packets (#1316)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Nov 15, 2023
1 parent 0d60b61 commit cd28476
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/zeroconf/_protocol/outgoing.pxd
Expand Up @@ -32,6 +32,7 @@ cdef object LOGGING_DEBUG

cdef cython.tuple BYTE_TABLE
cdef cython.tuple SHORT_LOOKUP
cdef cython.dict LONG_LOOKUP

cdef class DNSOutgoing:

Expand Down Expand Up @@ -70,7 +71,7 @@ cdef class DNSOutgoing:
index=cython.uint,
length=cython.uint
)
cdef cython.bint _write_record(self, DNSRecord record, object now)
cdef cython.bint _write_record(self, DNSRecord record, float now)

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

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

cdef _write_ttl(self, DNSRecord record, object now)
cdef _write_ttl(self, DNSRecord record, float now)

@cython.locals(
labels=cython.list,
Expand Down
10 changes: 9 additions & 1 deletion src/zeroconf/_protocol/outgoing.py
Expand Up @@ -31,6 +31,8 @@
from .._logger import log
from ..const import (
_CLASS_UNIQUE,
_DNS_HOST_TTL,
_DNS_OTHER_TTL,
_DNS_PACKET_HEADER_LEN,
_FLAGS_QR_MASK,
_FLAGS_QR_QUERY,
Expand All @@ -57,6 +59,7 @@

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


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

def _write_int(self, value: Union[float, int]) -> None:
"""Writes an unsigned integer to the packet"""
self.data.append(PACK_LONG(int(value)))
value_as_int = int(value)
long_bytes = LONG_LOOKUP.get(value_as_int)
if long_bytes is not None:
self.data.append(long_bytes)
else:
self.data.append(PACK_LONG(value_as_int))
self.size += 4

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

0 comments on commit cd28476

Please sign in to comment.