Skip to content

Commit 2f043a6

Browse files
committed
feat: cache short pack
1 parent b9a2c0c commit 2f043a6

2 files changed

Lines changed: 7 additions & 3 deletions

File tree

src/zeroconf/_protocol/outgoing.pxd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ cdef object TYPE_CHECKING
2020
cdef object PACK_BYTE
2121
cdef object PACK_SHORT
2222
cdef object PACK_LONG
23+
cdef object CACHED_PACK_SHORT
2324

2425
cdef class DNSOutgoing:
2526

src/zeroconf/_protocol/outgoing.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import enum
2424
import logging
25+
from functools import lru_cache
2526
from struct import Struct
2627
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
2728

@@ -53,6 +54,8 @@
5354
PACK_SHORT = Struct('>H').pack
5455
PACK_LONG = Struct('>L').pack
5556

57+
CACHED_PACK_SHORT = lru_cache(maxsize=None)(PACK_SHORT)
58+
5659

5760
class State(enum.Enum):
5861
init = 0
@@ -213,15 +216,15 @@ def _write_byte(self, value: int_) -> None:
213216

214217
def _insert_short_at_start(self, value: int_) -> None:
215218
"""Inserts an unsigned short at the start of the packet"""
216-
self.data.insert(0, PACK_SHORT(value))
219+
self.data.insert(0, CACHED_PACK_SHORT(value))
217220

218221
def _replace_short(self, index: int_, value: int_) -> None:
219222
"""Replaces an unsigned short in a certain position in the packet"""
220-
self.data[index] = PACK_SHORT(value)
223+
self.data[index] = CACHED_PACK_SHORT(value)
221224

222225
def write_short(self, value: int_) -> None:
223226
"""Writes an unsigned short to the packet"""
224-
self.data.append(PACK_SHORT(value))
227+
self.data.append(CACHED_PACK_SHORT(value))
225228
self.size += 2
226229

227230
def _write_int(self, value: Union[float, int]) -> None:

0 commit comments

Comments
 (0)