Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values.
()
| 285 | |
| 286 | |
| 287 | def _FloatDecoder(): |
| 288 | """Returns a decoder for a float field. |
| 289 | |
| 290 | This code works around a bug in struct.unpack for non-finite 32-bit |
| 291 | floating-point values. |
| 292 | """ |
| 293 | |
| 294 | local_unpack = struct.unpack |
| 295 | |
| 296 | def InnerDecode(buffer, pos): |
| 297 | """Decode serialized float to a float and new position. |
| 298 | |
| 299 | Args: |
| 300 | buffer: memoryview of the serialized bytes |
| 301 | pos: int, position in the memory view to start at. |
| 302 | |
| 303 | Returns: |
| 304 | Tuple[float, int] of the deserialized float value and new position |
| 305 | in the serialized data. |
| 306 | """ |
| 307 | # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign |
| 308 | # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. |
| 309 | new_pos = pos + 4 |
| 310 | float_bytes = buffer[pos:new_pos].tobytes() |
| 311 | |
| 312 | # If this value has all its exponent bits set, then it's non-finite. |
| 313 | # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. |
| 314 | # To avoid that, we parse it specially. |
| 315 | if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'): |
| 316 | # If at least one significand bit is set... |
| 317 | if float_bytes[0:3] != b'\x00\x00\x80': |
| 318 | return (math.nan, new_pos) |
| 319 | # If sign bit is set... |
| 320 | if float_bytes[3:4] == b'\xFF': |
| 321 | return (-math.inf, new_pos) |
| 322 | return (math.inf, new_pos) |
| 323 | |
| 324 | # Note that we expect someone up-stack to catch struct.error and convert |
| 325 | # it to _DecodeError -- this way we don't have to set up exception- |
| 326 | # handling blocks every time we parse one value. |
| 327 | result = local_unpack('<f', float_bytes)[0] |
| 328 | return (result, new_pos) |
| 329 | return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode) |
| 330 | |
| 331 | |
| 332 | def _DoubleDecoder(): |
no test coverage detected