sstruct.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """sstruct.py -- SuperStruct
  2. Higher level layer on top of the struct module, enabling to
  3. bind names to struct elements. The interface is similar to
  4. struct, except the objects passed and returned are not tuples
  5. (or argument lists), but dictionaries or instances.
  6. Just like struct, we use fmt strings to describe a data
  7. structure, except we use one line per element. Lines are
  8. separated by newlines or semi-colons. Each line contains
  9. either one of the special struct characters ('@', '=', '<',
  10. '>' or '!') or a 'name:formatchar' combo (eg. 'myFloat:f').
  11. Repetitions, like the struct module offers them are not useful
  12. in this context, except for fixed length strings (eg. 'myInt:5h'
  13. is not allowed but 'myString:5s' is). The 'x' fmt character
  14. (pad byte) is treated as 'special', since it is by definition
  15. anonymous. Extra whitespace is allowed everywhere.
  16. The sstruct module offers one feature that the "normal" struct
  17. module doesn't: support for fixed point numbers. These are spelled
  18. as "n.mF", where n is the number of bits before the point, and m
  19. the number of bits after the point. Fixed point numbers get
  20. converted to floats.
  21. pack(fmt, object):
  22. 'object' is either a dictionary or an instance (or actually
  23. anything that has a __dict__ attribute). If it is a dictionary,
  24. its keys are used for names. If it is an instance, it's
  25. attributes are used to grab struct elements from. Returns
  26. a string containing the data.
  27. unpack(fmt, data, object=None)
  28. If 'object' is omitted (or None), a new dictionary will be
  29. returned. If 'object' is a dictionary, it will be used to add
  30. struct elements to. If it is an instance (or in fact anything
  31. that has a __dict__ attribute), an attribute will be added for
  32. each struct element. In the latter two cases, 'object' itself
  33. is returned.
  34. unpack2(fmt, data, object=None)
  35. Convenience function. Same as unpack, except data may be longer
  36. than needed. The returned value is a tuple: (object, leftoverdata).
  37. calcsize(fmt)
  38. like struct.calcsize(), but uses our own fmt strings:
  39. it returns the size of the data in bytes.
  40. """
  41. from fontTools.misc.fixedTools import fixedToFloat as fi2fl, floatToFixed as fl2fi
  42. from fontTools.misc.textTools import tobytes, tostr
  43. import struct
  44. import re
  45. __version__ = "1.2"
  46. __copyright__ = "Copyright 1998, Just van Rossum <just@letterror.com>"
  47. class Error(Exception):
  48. pass
  49. def pack(fmt, obj):
  50. formatstring, names, fixes = getformat(fmt, keep_pad_byte=True)
  51. elements = []
  52. if not isinstance(obj, dict):
  53. obj = obj.__dict__
  54. for name in names.keys():
  55. value = obj[name]
  56. if name in fixes:
  57. # fixed point conversion
  58. value = fl2fi(value, fixes[name])
  59. elif isinstance(value, str):
  60. value = tobytes(value)
  61. elements.append(value)
  62. # Check it fits
  63. try:
  64. struct.pack(names[name], value)
  65. except Exception as e:
  66. raise ValueError(
  67. "Value %s does not fit in format %s for %s" % (value, names[name], name)
  68. ) from e
  69. data = struct.pack(*(formatstring,) + tuple(elements))
  70. return data
  71. def unpack(fmt, data, obj=None):
  72. if obj is None:
  73. obj = {}
  74. data = tobytes(data)
  75. formatstring, names, fixes = getformat(fmt)
  76. if isinstance(obj, dict):
  77. d = obj
  78. else:
  79. d = obj.__dict__
  80. elements = struct.unpack(formatstring, data)
  81. for i, name in enumerate(names.keys()):
  82. value = elements[i]
  83. if name in fixes:
  84. # fixed point conversion
  85. value = fi2fl(value, fixes[name])
  86. elif isinstance(value, bytes):
  87. try:
  88. value = tostr(value)
  89. except UnicodeDecodeError:
  90. pass
  91. d[name] = value
  92. return obj
  93. def unpack2(fmt, data, obj=None):
  94. length = calcsize(fmt)
  95. return unpack(fmt, data[:length], obj), data[length:]
  96. def calcsize(fmt):
  97. formatstring, names, fixes = getformat(fmt)
  98. return struct.calcsize(formatstring)
  99. # matches "name:formatchar" (whitespace is allowed)
  100. _elementRE = re.compile(
  101. r"\s*" # whitespace
  102. r"([A-Za-z_][A-Za-z_0-9]*)" # name (python identifier)
  103. r"\s*:\s*" # whitespace : whitespace
  104. r"([xcbB?hHiIlLqQfd]|" # formatchar...
  105. r"[0-9]+[ps]|" # ...formatchar...
  106. r"([0-9]+)\.([0-9]+)(F))" # ...formatchar
  107. r"\s*" # whitespace
  108. r"(#.*)?$" # [comment] + end of string
  109. )
  110. # matches the special struct fmt chars and 'x' (pad byte)
  111. _extraRE = re.compile(r"\s*([x@=<>!])\s*(#.*)?$")
  112. # matches an "empty" string, possibly containing whitespace and/or a comment
  113. _emptyRE = re.compile(r"\s*(#.*)?$")
  114. _fixedpointmappings = {8: "b", 16: "h", 32: "l"}
  115. _formatcache = {}
  116. def getformat(fmt, keep_pad_byte=False):
  117. fmt = tostr(fmt, encoding="ascii")
  118. try:
  119. formatstring, names, fixes = _formatcache[fmt]
  120. except KeyError:
  121. lines = re.split("[\n;]", fmt)
  122. formatstring = ""
  123. names = {}
  124. fixes = {}
  125. for line in lines:
  126. if _emptyRE.match(line):
  127. continue
  128. m = _extraRE.match(line)
  129. if m:
  130. formatchar = m.group(1)
  131. if formatchar != "x" and formatstring:
  132. raise Error("a special fmt char must be first")
  133. else:
  134. m = _elementRE.match(line)
  135. if not m:
  136. raise Error("syntax error in fmt: '%s'" % line)
  137. name = m.group(1)
  138. formatchar = m.group(2)
  139. if keep_pad_byte or formatchar != "x":
  140. names[name] = formatchar
  141. if m.group(3):
  142. # fixed point
  143. before = int(m.group(3))
  144. after = int(m.group(4))
  145. bits = before + after
  146. if bits not in [8, 16, 32]:
  147. raise Error("fixed point must be 8, 16 or 32 bits long")
  148. formatchar = _fixedpointmappings[bits]
  149. names[name] = formatchar
  150. assert m.group(5) == "F"
  151. fixes[name] = after
  152. formatstring += formatchar
  153. _formatcache[fmt] = formatstring, names, fixes
  154. return formatstring, names, fixes
  155. def _test():
  156. fmt = """
  157. # comments are allowed
  158. > # big endian (see documentation for struct)
  159. # empty lines are allowed:
  160. ashort: h
  161. along: l
  162. abyte: b # a byte
  163. achar: c
  164. astr: 5s
  165. afloat: f; adouble: d # multiple "statements" are allowed
  166. afixed: 16.16F
  167. abool: ?
  168. apad: x
  169. """
  170. print("size:", calcsize(fmt))
  171. class foo(object):
  172. pass
  173. i = foo()
  174. i.ashort = 0x7FFF
  175. i.along = 0x7FFFFFFF
  176. i.abyte = 0x7F
  177. i.achar = "a"
  178. i.astr = "12345"
  179. i.afloat = 0.5
  180. i.adouble = 0.5
  181. i.afixed = 1.5
  182. i.abool = True
  183. data = pack(fmt, i)
  184. print("data:", repr(data))
  185. print(unpack(fmt, data))
  186. i2 = foo()
  187. unpack(fmt, data, i2)
  188. print(vars(i2))
  189. if __name__ == "__main__":
  190. _test()