Skip to content

Commit 6a949ca

Browse files
committed
refactor(protocols): reorder misc, schema and base class members to the member-order convention (#2490)
- protocol: move _packing_target and _next_layer_entry out of Methods, and _make_data to the head of Utilities. - pcap frame/header: move Frame.__index__ into Data models and its private helpers into Utilities after _make_data; move Header.from_data into Methods. - pcapng: move _make_data to the head of Utilities, then the helpers read() calls directly, in first-use order (_read_block_short with its maker). - schema: put Methods ahead of Data models in Schema, EnumSchema, Option, FlagsField, OptionEnumField and SystemdJournalExportBlock; put the IPv6 schema's TYPE_CHECKING __init__ stub after post_process. Pure move: member set, member ASTs and comments are unchanged.
1 parent 9135806 commit 6a949ca

7 files changed

Lines changed: 989 additions & 989 deletions

File tree

‎pcapkit/protocols/misc/pcap/frame.py‎

Lines changed: 56 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -521,36 +521,6 @@ def __length_hint__(self) -> 'Literal[16]':
521521
"""Return an estimated length for the object."""
522522
return RECORD_HEADER_LEN # type: ignore[return-value]
523523

524-
def _check_record_floor(self, length: 'Optional[int]') -> 'None':
525-
"""Refuse a tail too short to hold a record header.
526-
527-
Args:
528-
length: Length of packet data, as the caller declared it, or
529-
:obj:`None` to measure what is left in
530-
:attr:`self._file <pcapkit.protocols.protocol.Protocol._file>`.
531-
532-
Raises:
533-
StreamEOFError: If fewer than sixteen octets are left to read.
534-
535-
A PCAP record header is sixteen octets, which is what
536-
:meth:`__length_hint__` reports. A shorter tail is not a record, so
537-
parsing one would only invent fields from zero padding. Reporting the
538-
end of the stream instead lets :meth:`Extractor.record_frames
539-
<pcapkit.foundation.extraction.Extractor.record_frames>` stop with the
540-
frames read so far, as the PCAP-NG reader does for a truncated block
541-
(:issue:`678`). See :issue:`1265`.
542-
543-
"""
544-
if length is None:
545-
current = self._file.tell()
546-
length = self._file.seek(0, io.SEEK_END) - current
547-
self._file.seek(current, io.SEEK_SET)
548-
549-
if length < RECORD_HEADER_LEN:
550-
raise StreamEOFError(f'PCAP: record truncated: {length} octet(s) left, '
551-
f'fewer than the {RECORD_HEADER_LEN} a record header needs',
552-
quiet=True)
553-
554524
# NOTE: This is a hack to make the ``__index__`` method work both as a
555525
# class method and an instance method.
556526
def __index__(self: 'Optional[Frame]' = None) -> 'int': # type: ignore[override]
@@ -601,38 +571,35 @@ def _make_data(cls, data: 'Data_Frame') -> 'dict[str, Any]': # type: ignore[ove
601571
'packet': cls._make_payload(data),
602572
}
603573

604-
def _make_timestamp(self, timestamp: 'Optional[float | Decimal | dt_type | int]' = None, ts_sec: 'Optional[int]' = None,
605-
ts_usec: 'Optional[int]' = None, nanosecond: 'bool' = False) -> 'tuple[int, int]':
606-
"""Make timestamp.
574+
def _check_record_floor(self, length: 'Optional[int]') -> 'None':
575+
"""Refuse a tail too short to hold a record header.
607576
608577
Args:
609-
timestamp: UNIX-Epoch timestamp
610-
ts_sec: timestamp seconds
611-
ts_usec: timestamp microseconds
612-
nanosecond: nanosecond-resolution file flag
613-
614-
Returns:
615-
Second and microsecond/nanosecond value of timestamp.
578+
length: Length of packet data, as the caller declared it, or
579+
:obj:`None` to measure what is left in
580+
:attr:`self._file <pcapkit.protocols.protocol.Protocol._file>`.
616581
617-
"""
618-
with localcontext(prec=64):
619-
if timestamp is None:
620-
if nanosecond:
621-
timestamp = decimal.Decimal(time.time_ns()) / 1_000_000_000
622-
else:
623-
timestamp = decimal.Decimal(time.time())
624-
else:
625-
if isinstance(timestamp, datetime.datetime):
626-
timestamp = totimestamp(timestamp)
627-
timestamp = decimal.Decimal(timestamp)
582+
Raises:
583+
StreamEOFError: If fewer than sixteen octets are left to read.
628584
629-
if ts_sec is None:
630-
ts_sec = int(timestamp)
585+
A PCAP record header is sixteen octets, which is what
586+
:meth:`__length_hint__` reports. A shorter tail is not a record, so
587+
parsing one would only invent fields from zero padding. Reporting the
588+
end of the stream instead lets :meth:`Extractor.record_frames
589+
<pcapkit.foundation.extraction.Extractor.record_frames>` stop with the
590+
frames read so far, as the PCAP-NG reader does for a truncated block
591+
(:issue:`678`). See :issue:`1265`.
631592
632-
if ts_usec is None:
633-
ts_usec = int((timestamp - ts_sec) * RESOLUTION[bool(nanosecond)])
593+
"""
594+
if length is None:
595+
current = self._file.tell()
596+
length = self._file.seek(0, io.SEEK_END) - current
597+
self._file.seek(current, io.SEEK_SET)
634598

635-
return ts_sec, ts_usec
599+
if length < RECORD_HEADER_LEN:
600+
raise StreamEOFError(f'PCAP: record truncated: {length} octet(s) left, '
601+
f'fewer than the {RECORD_HEADER_LEN} a record header needs',
602+
quiet=True)
636603

637604
def _decode_next_layer(self, dict_: 'Data_Frame', proto: 'Optional[int]' = None,
638605
length: 'Optional[int]' = None, *, packet: 'Optional[dict[str, Any]]' = None) -> 'Data_Frame': # pylint: disable=arguments-differ
@@ -680,6 +647,39 @@ def _decode_next_layer(self, dict_: 'Data_Frame', proto: 'Optional[int]' = None,
680647
self._protos = chain # pylint: disable=attribute-defined-outside-init
681648
return dict_
682649

650+
def _make_timestamp(self, timestamp: 'Optional[float | Decimal | dt_type | int]' = None, ts_sec: 'Optional[int]' = None,
651+
ts_usec: 'Optional[int]' = None, nanosecond: 'bool' = False) -> 'tuple[int, int]':
652+
"""Make timestamp.
653+
654+
Args:
655+
timestamp: UNIX-Epoch timestamp
656+
ts_sec: timestamp seconds
657+
ts_usec: timestamp microseconds
658+
nanosecond: nanosecond-resolution file flag
659+
660+
Returns:
661+
Second and microsecond/nanosecond value of timestamp.
662+
663+
"""
664+
with localcontext(prec=64):
665+
if timestamp is None:
666+
if nanosecond:
667+
timestamp = decimal.Decimal(time.time_ns()) / 1_000_000_000
668+
else:
669+
timestamp = decimal.Decimal(time.time())
670+
else:
671+
if isinstance(timestamp, datetime.datetime):
672+
timestamp = totimestamp(timestamp)
673+
timestamp = decimal.Decimal(timestamp)
674+
675+
if ts_sec is None:
676+
ts_sec = int(timestamp)
677+
678+
if ts_usec is None:
679+
ts_usec = int((timestamp - ts_sec) * RESOLUTION[bool(nanosecond)])
680+
681+
return ts_sec, ts_usec
682+
683683
def _dispatch_linktype(self, proto: 'Optional[int]', length: 'Optional[int]' = None) -> 'Optional[int]':
684684
"""Link type a frame's data is dispatched under.
685685

‎pcapkit/protocols/misc/pcap/header.py‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,22 @@ def make(self,
230230
reversed=network_reversed, pack=False),
231231
)
232232

233+
@classmethod
234+
def from_data(cls, data: 'Data_Header | dict[str, Any]', **kwargs: 'Any') -> 'Self':
235+
"""Create protocol instance from data.
236+
237+
Args:
238+
data: Protocol data.
239+
**kwargs: Construction keywords, as for :meth:`Protocol.from_data
240+
<pcapkit.protocols.protocol.Protocol.from_data>`.
241+
242+
Returns:
243+
Protocol instance, cut back to what was captured when the header
244+
it was parsed from was cut short (:issue:`1470`).
245+
246+
"""
247+
return replay_short_read(super().from_data(data, **kwargs), data)
248+
233249
##########################################################################
234250
# Data models.
235251
##########################################################################
@@ -281,22 +297,6 @@ def __length_hint__(self) -> 'Literal[24]':
281297
"""Return an estimated length for the object."""
282298
return GLOBAL_HEADER_LEN # type: ignore[return-value]
283299

284-
@classmethod
285-
def from_data(cls, data: 'Data_Header | dict[str, Any]', **kwargs: 'Any') -> 'Self':
286-
"""Create protocol instance from data.
287-
288-
Args:
289-
data: Protocol data.
290-
**kwargs: Construction keywords, as for :meth:`Protocol.from_data
291-
<pcapkit.protocols.protocol.Protocol.from_data>`.
292-
293-
Returns:
294-
Protocol instance, cut back to what was captured when the header
295-
it was parsed from was cut short (:issue:`1470`).
296-
297-
"""
298-
return replay_short_read(super().from_data(data, **kwargs), data)
299-
300300
@classmethod
301301
def __index__(cls) -> 'NoReturn':
302302
"""Numeral registry index of the protocol.

0 commit comments

Comments
 (0)