[sstruct] Accept pad byte format character

The list of format characters that sstruct accepts was missing “x” for
ignored pad bytes.
This commit is contained in:
Khaled Hosny 2021-07-03 13:47:41 +02:00
parent bdd462f066
commit 383e70fc39

View File

@ -59,7 +59,7 @@ class Error(Exception):
pass
def pack(fmt, obj):
formatstring, names, fixes = getformat(fmt)
formatstring, names, fixes = getformat(fmt, keep_pad_byte=True)
elements = []
if not isinstance(obj, dict):
obj = obj.__dict__
@ -112,7 +112,7 @@ _elementRE = re.compile(
r"\s*" # whitespace
r"([A-Za-z_][A-Za-z_0-9]*)" # name (python identifier)
r"\s*:\s*" # whitespace : whitespace
r"([cbB?hHiIlLqQfd]|" # formatchar...
r"([xcbB?hHiIlLqQfd]|" # formatchar...
r"[0-9]+[ps]|" # ...formatchar...
r"([0-9]+)\.([0-9]+)(F))" # ...formatchar
r"\s*" # whitespace
@ -132,7 +132,7 @@ _fixedpointmappings = {
_formatcache = {}
def getformat(fmt):
def getformat(fmt, keep_pad_byte=False):
fmt = tostr(fmt, encoding="ascii")
try:
formatstring, names, fixes = _formatcache[fmt]
@ -154,8 +154,9 @@ def getformat(fmt):
if not m:
raise Error("syntax error in fmt: '%s'" % line)
name = m.group(1)
names.append(name)
formatchar = m.group(2)
if keep_pad_byte or formatchar != "x":
names.append(name)
if m.group(3):
# fixed point
before = int(m.group(3))
@ -184,6 +185,7 @@ def _test():
afloat: f; adouble: d # multiple "statements" are allowed
afixed: 16.16F
abool: ?
apad: x
"""
print('size:', calcsize(fmt))