Debian Codegraph @

gavo/votable/enc_binary.py

raw
1 """
2 Binary VOTable encoding.
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 datetime #noflake: used in generated code
12 import json #noflake: used in generated code
13 import struct
14
15 from gavo import utils #noflake: used by generated code
16 from gavo.utils import pgsphere #noflake: used by generated code
17 from gavo.votable import coding #noflake: used by generated code
18 from gavo.votable import common
19 from gavo.votable.model import VOTable
20
21 from gavo.utils.dachstypes import Any, Callable, Dict, List, Optional
22
23
24 floatNaN = struct.pack("!f", common.NaN)
25 doubleNaN = struct.pack("!d", common.NaN)
26
27
28 def _getArrayShapingCode(field: VOTable.FIELD, padder: str) -> List[str]:
29 """returns common code for almost all array serialization.
30
31 Field must describe an array (as opposed to a single value).
32
33 padder must be python-source for whatever is used to pad
34 arrays that are too short.
35 """
36 base = [
37 "if val is None: val = []"]
38 if field.isMultiDim():
39 # it's an n-d array (n>1): flatten out all values
40 base.append("val = coding.ravel(val)")
41 if field.hasVarLength():
42 return base+["tokens.append(struct.pack('!i', len(val)))"]
43 else:
44 return base+["val = coding.trim(val, %s, %s)"%(
45 field.getLength(), padder)]
46
47
48 def _addNullvalueCode(
49 field: VOTable.FIELD,
50 nullvalue: Optional[str],
51 src: List[str]) -> List[str]:
52 """adds code to let null values kick in a necessary.
53
54 nullvalue here has to be a ready-made *python* literal. Take care
55 when passing in user supplied values here.
56 """
57 if nullvalue is None:
58 action = (" raise common.BadVOTableData('None passed for field"
59 " that has no NULL value', None, '%s', hint='Integers in VOTable"
60 " have no natural serializations for missing values. You need to"
61 " define one using values null to allow for NULL in integer columns')"
62 )%field.getDesignation()
63 else:
64 action = " tokens.append(%s)"%nullvalue
65 return [
66 "if val is None:",
67 action,
68 "else:"
69 ]+common.indentList(src, " ")
70
71
72 def _makeBooleanEncoder(field: VOTable.FIELD) -> List[str]:
73 return [
74 "if val is None:",
75 " tokens.append(b'?')",
76 "elif val:",
77 " tokens.append(b'1')",
78 "else:",
79 " tokens.append(b'0')",
80 ]
81
82
83 def _makeBitEncoder(field: VOTable.FIELD, allowNULL: bool = False) -> List[str]:
84 # bits and bit arrays are just (possibly long) integers
85 # length may be None for var length.
86 length = field.getLength()
87 if allowNULL:
88 src = [
89 "if val is None:"
90 " tokens.append(b'\\0\\0\\0\\0')",]
91 else:
92 src = [
93 "if val is None:",
94 " raise common.BadVOTableData('Bits have no NULL value', None,",
95 " '%s')"%field.getDesignation(),]
96
97 src.extend([
98 "else:",
99 " tmp = []",
100 " curByte, rest = val%256, val//256",
101 " while curByte:",
102 " tmp.append(curByte)",
103 " curByte, rest = rest%256, rest//256",
104 " if not tmp:", # make sure we leave something even for 0
105 " tmp.append(0)",
106 " tmp.reverse()",])
107
108 if length!=1: # this not just a single bit
109 if length is None: # variable length: dump number of bits
110 src.extend([
111 " tokens.append(struct.pack('!i', len(tmp)*8))"])
112 else: # crop/expand as necessary
113 numBytes = int(length)//8+(not not int(length)%8)
114 src.extend([
115 " if len(tmp)<%d: tmp = [0]*(%d-len(tmp))+tmp"%(
116 numBytes, numBytes),
117 " if len(tmp)>%d: tmp = tmp[-%d:]"%(numBytes, numBytes)])
118
119 src.extend([
120 " tokens.append(bytes(tmp))"])
121 return src
122
123
124 def _generateFloatEncoderMaker(fmtCode: str, nullName: str
125 ) -> Callable[[VOTable.FIELD], List[str]]:
126 """returns a code-generating function for writing floats.
127
128 fmtCode is a struct format code, nullName is either singleNaN or
129 doubleNaN (these are module-globals defined above).
130
131 The indirection is because we want one piece of code for both
132 singles and doubles.
133 """
134 def makeFloatEncoder(field: VOTable.FIELD) -> List[str]:
135 return [
136 "if val is None:",
137 f" tokens.append({nullName})",
138 "else:",
139 f" tokens.append(struct.pack('{fmtCode}', val))"]
140 return makeFloatEncoder
141
142
143 def _generateComplexEncoderMaker(fmtCode: str, singleNull: str
144 ) -> Callable[[VOTable.FIELD], List[str]]:
145 """returns a code-generating function for writing complex numbers.
146
147 fmtCode is a struct format code.
148
149 Again, we can have singles and double, and hence there is this
150 extra indirection.
151 """
152 def makeComplexEncoder(field: VOTable.FIELD) -> List[str]:
153 return [
154 "if val is None:",
155 f" tokens.append({singleNull}+{singleNull})",
156 "else:",
157 f" tokens.append(struct.pack('{fmtCode}', val.real, val.imag))"]
158 return makeComplexEncoder
159
160
161 def _generateIntEncoderMaker(fmtCode: str
162 ) -> Callable[[VOTable.FIELD], List[str]]:
163 """returns a code-generating function for writing integers of all kinds.
164
165 fmtCode is a struct format code.
166 """
167
168 def makeIntEncoder(field: VOTable.FIELD) -> List[str]:
169 nullvalue = coding.getNullvalue(field, int)
170 if nullvalue is not None:
171 nullvalue = repr(struct.pack(fmtCode, int(nullvalue)))
172 return _addNullvalueCode(field, nullvalue, [
173 f"tokens.append(struct.pack('{fmtCode}', val))"])
174 return makeIntEncoder
175
176
177 def _makeUnsignedByteEncoder(field: VOTable.FIELD) -> List[str]:
178 # allow these to come from strings, too (db type bytea)
179 nullvalue = coding.getNullvalue(field, int)
180 if nullvalue is not None:
181 nullvalue = repr(struct.pack("B", int(nullvalue)))
182 return _addNullvalueCode(field, nullvalue, [
183 "if isinstance(val, int):",
184 " tokens.append(struct.pack('B', val))",
185 "else:",
186 " tokens.append(struct.pack('c', val[:1]))"])
187
188
189 def _makeCharEncoder(field: VOTable.FIELD) -> List[str]:
190 nullvalue = coding.getNullvalue(field, lambda _: True)
191 if nullvalue is not None:
192 nullvalue = repr(struct.pack("c", utils.bytify(nullvalue)))
193
194 return ["if isinstance(val, str): val = val.encode('ascii')",
195 ]+_addNullvalueCode(field, nullvalue, [
196 "tokens.append(bytes(val))"])
197
198
199 def _makeUnicodeCharEncoder(field: VOTable.FIELD) -> List[str]:
200 nullvalue = coding.getNullvalue(field, lambda _: True)
201 if nullvalue is not None:
202 coded = nullvalue.encode("utf-16be")
203 nullvalue = repr(struct.pack("%ds"%len(coded), coded))
204 return _addNullvalueCode(field, nullvalue, [
205 "coded = val.encode('utf-16be')",
206 "tokens.append(struct.pack('%ds'%len(coded), coded))"])
207
208
209 def _makeCharArrayEncoder(field: VOTable.FIELD) -> List[str]:
210 # special handling for character arrays, since we don't want to treat
211 # those as character arrays in python.
212 nullvalue = coding.getNullvalue(field, lambda _: True, default="")
213 src = []
214
215 src.extend(common.getXtypeEncoderCode(field))
216 src.append("val = coding.trimString(val, %s)"%repr(field.arraysize))
217
218 if field.hasVarLength():
219 src.append("tokens.append(struct.pack('!i', len(val)))")
220 if nullvalue is None:
221 nullvalue = repr('\0\0\0\0')
222 else:
223 # The bytes in the next line allows nullvalue to be str (containing
224 # ascii, of course)
225 nullvalue = repr(struct.pack("!i%ds"%len(nullvalue),
226 len(nullvalue), nullvalue.encode("utf-8")))
227 else:
228 if nullvalue is not None:
229 fieldLength = field.getLength() or 1
230 nullvalue = repr(struct.pack(f"{fieldLength}s",
231 coding.trimString(nullvalue, field.arraysize).encode("utf-8")))
232 # no predefined nullvalue for constant-length strings
233
234 if field.datatype=="unicodeChar":
235 src.append("val = val.encode('utf-16be')")
236 elif field.datatype=="char":
237 src.extend([
238 'if isinstance(val, str):',
239 ' val = val.encode("ascii", "replace")'])
240
241 src.append("tokens.append(struct.pack('%ds'%len(val), val))")
242 return _addNullvalueCode(field, nullvalue, src)
243
244
245 _encoders: Dict[str, Callable[[VOTable.FIELD], List[str]]] = {
246 "boolean": _makeBooleanEncoder,
247 "bit": _makeBitEncoder,
248 "unsignedByte": _makeUnsignedByteEncoder,
249 "short": _generateIntEncoderMaker('!h'),
250 "int": _generateIntEncoderMaker('!i'),
251 "long": _generateIntEncoderMaker('!q'),
252 "char": _makeCharEncoder,
253 "unicodeChar": _makeUnicodeCharEncoder,
254 "double": _generateFloatEncoderMaker("!d", "doubleNaN"),
255 "float": _generateFloatEncoderMaker("!f", "floatNaN"),
256 "doubleComplex": _generateComplexEncoderMaker("!dd", "doubleNaN"),
257 "floatComplex": _generateComplexEncoderMaker("!ff", "floatNaN"),
258 }
259
260 def _getArrayEncoderLines(field: VOTable.FIELD) -> List[str]:
261 """returns python lines to encode array values of field.
262 """
263 type = field.datatype
264
265 # bit array literals are integers, same as bits
266 if type=="bit":
267 return _makeBitEncoder(field)
268
269 if type=="char" or type=="unicodeChar":
270 return _makeCharArrayEncoder(field)
271
272
273 # Everything else can use some common array shaping code since value comes in
274 # some kind of sequence.
275 padder = '[None]'
276 src = [ # Painful name juggling to avoid having to call functions.
277 "fullTokens = tokens",
278 "tokens = []",
279 "if val is None:",
280 " arr = []",
281 "else:",
282 " arr = val",
283 "for val in arr:"
284 ]+common.indentList(
285 _encoders[field.datatype](field), " ")
286
287 src.extend([
288 "fullTokens.append(b''.join(tokens))",
289 "tokens = fullTokens"])
290
291 return (common.getXtypeEncoderCode(field)
292 + _getArrayShapingCode(field, padder)
293 + src)
294
295
296 def getLinesFor(field: VOTable.FIELD) -> List[str]:
297 """returns a sequence of python source lines to encode values described
298 by field into tabledata.
299 """
300 if field.isScalar():
301 return _encoders[field.datatype](field)
302 else:
303 return _getArrayEncoderLines(field)
304
305
306 def getPostamble(tableDefinition: VOTable.TABLE) -> List[str]:
307 return [
308 "return b''.join(tokens)"]
309
310
311 def getGlobals(tableDefinition: VOTable.TABLE) -> Dict[str, Any]:
312 return globals()