Skip to content

Commit

Permalink
Small optimization of cache during parsing (#4526)
Browse files Browse the repository at this point in the history
  • Loading branch information
gpotter2 authored Sep 7, 2024
1 parent 1935723 commit 1c09692
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions scapy/packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def __init__(self,
self.fieldtype = {} # type: Dict[str, AnyField]
self.packetfields = [] # type: List[AnyField]
self.payload = NoPayload() # type: Packet
self.init_fields()
self.init_fields(bool(_pkt))
self.underlayer = _underlayer
self.parent = _parent
if isinstance(_pkt, bytearray):
Expand Down Expand Up @@ -253,16 +253,16 @@ def __deepcopy__(self,
"""Used by copy.deepcopy"""
return self.copy()

def init_fields(self):
# type: () -> None
def init_fields(self, for_dissect_only=False):
# type: (bool) -> None
"""
Initialize each fields of the fields_desc dict
"""

if self.class_dont_cache.get(self.__class__, False):
self.do_init_fields(self.fields_desc)
else:
self.do_init_cached_fields()
self.do_init_cached_fields(for_dissect_only=for_dissect_only)

def do_init_fields(self,
flist, # type: Sequence[AnyField]
Expand All @@ -280,8 +280,8 @@ def do_init_fields(self,
# We set default_fields last to avoid race issues
self.default_fields = default_fields

def do_init_cached_fields(self):
# type: () -> None
def do_init_cached_fields(self, for_dissect_only=False):
# type: (bool) -> None
"""
Initialize each fields of the fields_desc dict, or use the cached
fields information
Expand All @@ -300,6 +300,10 @@ def do_init_cached_fields(self):
self.fieldtype = Packet.class_fieldtype[cls_name]
self.packetfields = Packet.class_packetfields[cls_name]

# Optimization: no need for references when only dissecting.
if for_dissect_only:
return

# Deepcopy default references
for fname in Packet.class_default_fields_ref[cls_name]:
value = self.default_fields[fname]
Expand Down Expand Up @@ -334,8 +338,7 @@ def prepare_cached_fields(self, flist):
self.do_init_fields(self.fields_desc)
return

tmp_copy = copy.deepcopy(f.default)
class_default_fields[f.name] = tmp_copy
class_default_fields[f.name] = copy.deepcopy(f.default)
class_fieldtype[f.name] = f
if f.holds_packets:
class_packetfields.append(f)
Expand Down

0 comments on commit 1c09692

Please sign in to comment.