Skip to content

Commit 9ad4f7c

Browse files
committed
Refactoring: Extract as a method
1 parent e505198 commit 9ad4f7c

File tree

2 files changed

+34
-18
lines changed

2 files changed

+34
-18
lines changed

protobuf_decoder/protobuf_decoder.py

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -363,33 +363,50 @@ def _next_get_delimited_data_handler(self, value):
363363
self._fetcher.fetch()
364364
self._buffer.append(value)
365365

366+
@staticmethod
367+
def is_maybe_nested_protobuf(string_or_not) -> bool:
368+
"""
369+
Determine if the given input might be a nested protobuf.
370+
371+
Args:
372+
string_or_not (str): Input string or data to be checked.
373+
374+
Returns:
375+
bool: True if the input is likely a nested protobuf, otherwise False.
376+
"""
377+
378+
# Try to convert the input hex string to UTF-8
379+
try:
380+
_data = Utils.hex_string_to_utf8(string_or_not)
381+
except UnicodeDecodeError:
382+
# If a UnicodeDecodeError occurs, it's possibly a nested protobuf
383+
return True
384+
385+
# Check the first 4 characters of the decoded data
386+
for c in _data[0:4]:
387+
# If any character has an ordinal value less than 0x20,
388+
# it's possibly a nested protobuf
389+
if ord(c) < 0x20:
390+
return True
391+
392+
# If none of the above conditions were met, it's likely not a nested protobuf
393+
return False
394+
366395
def _get_delimited_data_handler(self, chunk):
367396
value = chunk
368397
if self._fetcher.has_next:
369398
return self._next_get_delimited_data_handler(value)
370399

371400
self._buffer.append(value)
372401
data = list(map(lambda x: hex(x)[2:].zfill(2), self._buffer))
373-
374-
_data = None
375-
try:
376-
_data = Utils.hex_string_to_utf8("".join(data))
377-
wire_type = "string"
378-
except UnicodeDecodeError:
379-
pass
380-
381-
escaped = 1 if _data and ord(_data[0]) <= 0x20 else 0
382-
if _data:
383-
for c in _data[1:4]:
384-
if ord(c) < 0x20:
385-
escaped += 1
386402

387-
if not _data or escaped > 0:
388-
sub_parsed_data = self._create_nested_parser().parse(" ".join(data))
389-
data = sub_parsed_data
403+
string_or_not = "".join(data)
404+
if self.is_maybe_nested_protobuf(string_or_not):
405+
data = self._create_nested_parser().parse(string_or_not)
390406
wire_type = "length_delimited"
391407
else:
392-
data = _data
408+
data = Utils.hex_string_to_utf8(string_or_not)
409+
wire_type = "string"
393410

394411
self._parsed_data.append(
395412
ParsedResult(

tests.py

Lines changed: 0 additions & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)