Debian Codegraph @

gavo/votable/dec_binary.py

raw
1 """
2 Coding and decoding from binary.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re #noflake: used by generated code
12 import struct #noflake: used by generated code
13
14 from gavo import stc #noflake: used by generated code
15 from gavo import utils #noflake: used by generated code
16 from gavo.utils import parseDefaultDatetime, parseDefaultDate #noflake: used by generated code
17 from gavo.utils import pgsphere #noflake: used by generated code
18 from gavo.votable import coding
19 from gavo.votable import common #noflake: used by generated code
20 from gavo.votable.model import VOTable
21
22 from gavo.utils.dachstypes import Any, Callable, Dict, List, Optional
23
24
25 # literals for BINARY booleans
26 BINENCBOOL = {
27 b't': True,
28 b'T': True,
29 b'1': True,
30 b'f': False,
31 b'F': False,
32 b'0': False,
33 b'?': None,
34 }
35
36
37 def _addNullvalueCode(
38 field: VOTable.TypedElement,
39 src: List[str],
40 validator: Callable[[Any], Any]) -> List[str]:
41 """adds code to catch nullvalues if required by field.
42
43 validator must be a function returning a valid python value for
44 a nullvalue attribute or raise an exception. This is security
45 critical since whatever validator returns gets embedded into
46 natively-run source code.
47 """
48 nullvalue = coding.getNullvalue(field, validator)
49 if nullvalue:
50 src.extend([
51 'if val==%s:'%validator(nullvalue),
52 ' row.append(None)',
53 'else:',
54 ' row.append(val)',])
55 else:
56 src.append('row.append(val)')
57 return src
58
59
60 def _makeFloatDecoder(field: VOTable.TypedElement) -> List[str]:
61 numBytes, structCode, _ = _typemap[field.datatype]
62 return [
63 'val = struct.unpack("!%s", inF.read(%d))[0]'%(structCode, numBytes),
64 'if val!=val:',
65 ' row.append(None)',
66 'else:',
67 ' row.append(val)']
68
69
70 def _makeComplexDecoder(
71 field: VOTable.TypedElement,
72 numBytes: int,
73 structCode: str) -> List[str]:
74 return [
75 '_re, _im = struct.unpack(%s, inF.read(%d))'%(repr(structCode), numBytes),
76 'if _re!=_re or _im!=_im:',
77 ' row.append(None)',
78 'else:',
79 ' row.append(_re+1j*_im)']
80
81
82 def _makeIntDecoder(field: VOTable.TypedElement) -> List[str]:
83 numBytes, structCode, _ = _typemap[field.datatype]
84 src = [
85 'val = struct.unpack("!%s", inF.read(%d))[0]'%(structCode, numBytes)
86 ]
87 return _addNullvalueCode(field, src, int)
88
89
90 def _makeBooleanDecoder(field: VOTable.TypedElement) -> List[str]:
91 return [
92 'row.append(BINENCBOOL[inF.read(1)])']
93
94
95 def _getArraysizeCode(field: VOTable.TypedElement) -> List[str]:
96 src = []
97 if field.hasVarLength():
98 src.append('arraysize = struct.unpack("!i", inF.read(4))[0]')
99 else:
100 fieldLength = field.getLength() or 1
101 src.append(f"arraysize = {fieldLength}")
102 return src
103
104
105 def _makeBitDecoder(field: VOTable.TypedElement) -> List[str]:
106 # bits/bit arrays are just dumped bits we turn to integers
107 # it's basically the same thing for arrays and single values.
108 src = _getArraysizeCode(field)
109 src.extend([
110 'if arraysize==0:',
111 ' res = []',
112 'else:',
113 ' numBytes = (arraysize+7)//8',
114 ' topMask = (1<<(arraysize%8))-1', # mask for payload in topmost byte
115 ' if topMask==0: topMask = 0xff',
116 ' bytes = struct.unpack("%dB"%numBytes, inF.read(numBytes))',
117 ' res = bytes[0]&topMask',
118 ' for b in bytes[1:]:',
119 ' res = (res<<8)+b',
120 'row.append(res)'])
121 return src
122
123
124 def _makeString(
125 field: VOTable.TypedElement,
126 customSrc: List[str]) -> List[str]:
127 src = _getArraysizeCode(field)
128 src.extend(customSrc)
129
130 if field.isMultiDim():
131 src.append("val = coding.unravelArray(%s, val)"%repr(field.arraysize))
132
133 src.append("if '\\0' in val: val = val[:val.index('\\0')]")
134 src.extend(common.getXtypeDecoderCode(field))
135 _addNullvalueCode(field, src, repr)
136 return src
137
138
139 def _makeCharDecoder(field: VOTable.TypedElement) -> List[str]:
140 return _makeString(field, [
141 'val = struct.unpack("%ds"%arraysize, inF.read(arraysize))[0]'
142 '.decode("ascii", "qmreplace")'])
143
144
145 def _makeUnicodeCharDecoder(field: VOTable.TypedElement) -> List[str]:
146 # XXX BUG: Anything outside the BMP will kill this
147 return _makeString(field, [
148 'val = struct.unpack("%ds"%(2*arraysize), inF.read(2*arraysize)'
149 ')[0].decode("utf-16be")'])
150
151
152 _typemap = {
153 "unsignedByte": (1, 'B', "bytelist"),
154 "short": (2, 'h', "intlist"),
155 "int": (4, 'i', "intlist"),
156 "long": (8, 'q', "intlist"),
157 "float": (4, 'f', "floatlist"),
158 "double": (8, 'd', "floatlist"),}
159
160
161 _decoders = {
162 'boolean': _makeBooleanDecoder,
163 'bit': _makeBitDecoder,
164 'char': _makeCharDecoder,
165 'unicodeChar': _makeUnicodeCharDecoder,
166
167 'unsignedByte': _makeIntDecoder,
168 'short': _makeIntDecoder,
169 'int': _makeIntDecoder,
170 'long': _makeIntDecoder,
171
172 'float': _makeFloatDecoder,
173 'double': _makeFloatDecoder,
174 'floatComplex': lambda v: _makeComplexDecoder(v, 8, '!ff'),
175 'doubleComplex': lambda v: _makeComplexDecoder(v, 16, '!dd'),
176 }
177
178 def _makeShortcutCode(
179 field: VOTable.TypedElement, type: str) -> Optional[List[str]]:
180 """returns None or code to quickly decode a field array.
181
182 Fast decoding for whatever is mentioned in _typemap and no nullvalues
183 are defined.
184 """
185 if type not in _typemap:
186 return None
187 if coding.getNullvalue(field, str) is not None:
188 return None
189 if "x" in field.arraysize or field.xtype:
190 return None
191
192 # TODO: The following fails rather often (taptest.py SimpleRunnerTest.testColumnNames)
193 # Fix it and then remove the return None:
194 return None
195
196 numBytes, typecode, listtype = _typemap[type]
197 src = _getArraysizeCode(field)
198 src.append(
199 'vals = struct.unpack("!%%d%s"%%arraysize, inF.read(arraysize*%d))'%(
200 typecode, numBytes))
201 if type=='float' or type=='double':
202 src.append(
203 'row.append(utils.%s(None if v!=v else v for v in vals))'%listtype)
204 else:
205 src.append(
206 'row.append(utils.%s(vals))'%listtype)
207
208 return src
209
210
211 def _getArrayDecoderLines(field: VOTable.TypedElement) -> List[str]:
212 """returns lines that decode arrays of literals.
213
214 Unfortunately, the spec is plain nuts, so we need to pull some tricks here.
215 """
216 type = field.datatype
217
218 # Weird things
219 if type=="bit":
220 return _makeBitDecoder(field)
221 elif type=='char':
222 return _makeCharDecoder(field)
223 elif type=='unicodeChar':
224 return _makeUnicodeCharDecoder(field)
225
226 # Fast array decoding for fields without null values
227 src = _makeShortcutCode(field, type)
228 if src is not None:
229 return src
230
231 _, _, listtype = _typemap.get(type, (None, None, 'list'))
232
233 # default processing
234 src = [ # OMG. I'm still hellbent on not calling functions here.
235 'fullRow, row = row, []',
236 ]
237 src.extend(_getArraysizeCode(field))
238 src.extend([
239 "for i in range(arraysize):"])
240 src.extend(common.indentList(_decoders[type](field), " "))
241
242 src.extend(coding.makeShapeValidator(field))
243 src.extend([
244 "val = utils.%s(row)"%listtype,
245 "row = fullRow"])
246 src.append("val = coding.unravelArray(%s, val)"%repr(field.arraysize))
247 src.extend(common.getXtypeDecoderCode(field))
248 src.append("row.append(val)")
249 return src
250
251
252 def getLinesFor(field: VOTable.TypedElement) -> List[str]:
253 """returns a sequence of python source lines to decode BINARY-encoded
254 values for field.
255 """
256 if field.isScalar():
257 return _decoders[field.datatype](field)
258 else:
259 return _getArrayDecoderLines(field)
260
261
262 def getRowDecoderSource(tableDefinition: VOTable.TABLE) -> str:
263 """returns the source for a function deserializing a BINARY stream.
264
265 tableDefinition is a VOTable.TABLE instance. The function returned
266 expects a file-like object.
267 """
268 source = ["def codec(inF):", " row = []"]
269 for index, field in enumerate(
270 tableDefinition.iterChildrenOfType(VOTable.FIELD)):
271 source.extend([
272 " try:",]+
273 common.indentList(getLinesFor(field), " ")+[
274 " except IOError:", # EOF on empty row is ok.
275 " if inF.atEnd() and row==[]:",
276 " return None",
277 " raise",
278 " except common.VOTableError:",
279 " raise",
280 " except:",
281 # " import traceback; traceback.print_exc()",
282 " raise common.BadVOTableLiteral('%s', repr(inF.lastRes), name=%r)"%(
283 field.datatype, field.name)])
284 source.append(" return row")
285 return "\n".join(source)
286
287
288 def getGlobals(tableDefinition: VOTable.TABLE) -> Dict[str, Any]:
289 return globals()