feat: optimize construction of outgoing dns records (#1182) · python-zeroconf/python-zeroconf@fc0341f

@@ -40,6 +40,11 @@

4040

)

4141

from .incoming import DNSIncoming

424243+

str_ = str

44+

float_ = float

45+

DNSQuestion_ = DNSQuestion

46+

DNSRecord_ = DNSRecord

47+43484449

class State(enum.Enum):

4550

init = 0

@@ -238,7 +243,7 @@ def write_character_string(self, value: bytes) -> None:

238243

self._write_byte(length)

239244

self.write_string(value)

240245241-

def write_name(self, name: str) -> None:

246+

def write_name(self, name: str_) -> None:

242247

"""

243248

Write names to packet

244249

@@ -276,26 +281,26 @@ def write_name(self, name: str) -> None:

276281

# this is the end of a name

277282

self._write_byte(0)

278283279-

def _write_question(self, question: DNSQuestion) -> bool:

284+

def _write_question(self, question: DNSQuestion_) -> bool:

280285

"""Writes a question to the packet"""

281286

start_data_length, start_size = len(self.data), self.size

282287

self.write_name(question.name)

283288

self.write_short(question.type)

284289

self._write_record_class(question)

285290

return self._check_data_limit_or_rollback(start_data_length, start_size)

286291287-

def _write_record_class(self, record: Union[DNSQuestion, DNSRecord]) -> None:

292+

def _write_record_class(self, record: Union[DNSQuestion_, DNSRecord_]) -> None:

288293

"""Write out the record class including the unique/unicast (QU) bit."""

289294

if record.unique and self.multicast:

290295

self.write_short(record.class_ | _CLASS_UNIQUE)

291296

else:

292297

self.write_short(record.class_)

293298294-

def _write_ttl(self, record: DNSRecord, now: float) -> None:

299+

def _write_ttl(self, record: DNSRecord_, now: float_) -> None:

295300

"""Write out the record ttl."""

296301

self._write_int(record.ttl if now == 0 else record.get_remaining_ttl(now))

297302298-

def _write_record(self, record: DNSRecord, now: float) -> bool:

303+

def _write_record(self, record: DNSRecord_, now: float_) -> bool:

299304

"""Writes a record (answer, authoritative answer, additional) to

300305

the packet. Returns True on success, or False if we did not

301306

because the packet because the record does not fit."""

@@ -308,7 +313,9 @@ def _write_record(self, record: DNSRecord, now: float) -> bool:

308313

self.write_short(0) # Will get replaced with the actual size

309314

record.write(self)

310315

# Adjust size for the short we will write before this record

311-

length = sum(len(d) for d in self.data[index + 1 :])

316+

length = 0

317+

for d in self.data[index + 1 :]:

318+

length += len(d)

312319

# Here we replace the 0 length short we wrote

313320

# before with the actual length

314321

self._replace_short(index, length)