Coverage for src / zmqtt / _internal / packets / reader.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-11-12 08:49 +0000

1"""Incremental buffer reader for MQTT packet framing over TCP.""" 

2 

3from collections.abc import Iterator 

4from typing import Final, Literal 

5 

6from zmqtt._internal.packets.codec import AnyPacket, decode 

7 

8 

9class PacketBuffer: 

10 """Accumulates incoming bytes and yields complete packets. 

11 

12 TCP delivers bytes in arbitrary chunks — a packet may arrive across 

13 multiple reads, or multiple packets in a single read. Feed bytes as they 

14 arrive; iterate to consume all fully-received packets. 

15 

16 Drain the iterator before feeding again. Iteration holds a ``memoryview`` 

17 of the buffer so that consumed bytes are skipped rather than copied out, 

18 and a ``bytearray`` cannot be resized while a view on it is exported, so a 

19 ``feed`` mid-iteration raises ``BufferError``. Leaving the loop early is 

20 fine: closing the iterator releases the view. 

21 

22 With *max_packet_size*, iteration raises ``PacketTooLargeError`` once the 

23 fixed header of an oversized packet has arrived. 

24 """ 

25 

26 def __init__( 

27 self, 

28 version: Literal["3.1.1", "5.0"] = "3.1.1", 

29 max_packet_size: int | None = None, 

30 ) -> None: 

31 self._buf: bytearray = bytearray() 

32 self._offset = 0 

33 self._version: Final = version 

34 self._max_packet_size: Final = max_packet_size 

35 

36 def feed(self, data: bytes) -> None: 

37 """Add bytes from one socket read, dropping whatever has been parsed.""" 

38 if self._offset: 

39 del self._buf[: self._offset] 

40 self._offset = 0 

41 self._buf += data 

42 

43 def __iter__(self) -> Iterator[AnyPacket]: 

44 view = memoryview(self._buf) 

45 try: 

46 while True: 

47 result = decode(view[self._offset :], version=self._version, max_packet_size=self._max_packet_size) 

48 if result is None: 

49 return 

50 packet, consumed = result 

51 self._offset += consumed 

52 yield packet 

53 finally: 

54 view.release()