Data held in a QR compatible format. Doesn't currently handle KANJI.
| 413 | |
| 414 | |
| 415 | class QRData: |
| 416 | """ |
| 417 | Data held in a QR compatible format. |
| 418 | |
| 419 | Doesn't currently handle KANJI. |
| 420 | """ |
| 421 | |
| 422 | def __init__(self, data, mode=None, check_data=True): |
| 423 | """ |
| 424 | If ``mode`` isn't provided, the most compact QR data type possible is |
| 425 | chosen. |
| 426 | """ |
| 427 | if check_data: |
| 428 | data = to_bytestring(data) |
| 429 | |
| 430 | if mode is None: |
| 431 | self.mode = optimal_mode(data) |
| 432 | else: |
| 433 | self.mode = mode |
| 434 | if mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE): |
| 435 | raise TypeError(f"Invalid mode ({mode})") # pragma: no cover |
| 436 | if check_data and mode < optimal_mode(data): # pragma: no cover |
| 437 | raise ValueError(f"Provided data can not be represented in mode {mode}") |
| 438 | |
| 439 | self.data = data |
| 440 | |
| 441 | def __len__(self): |
| 442 | return len(self.data) |
| 443 | |
| 444 | def write(self, buffer): |
| 445 | if self.mode == MODE_NUMBER: |
| 446 | for i in range(0, len(self.data), 3): |
| 447 | chars = self.data[i : i + 3] |
| 448 | bit_length = NUMBER_LENGTH[len(chars)] |
| 449 | buffer.put(int(chars), bit_length) |
| 450 | elif self.mode == MODE_ALPHA_NUM: |
| 451 | for i in range(0, len(self.data), 2): |
| 452 | chars = self.data[i : i + 2] |
| 453 | if len(chars) > 1: |
| 454 | buffer.put( |
| 455 | ALPHA_NUM.find(chars[0]) * 45 + ALPHA_NUM.find(chars[1]), 11 |
| 456 | ) |
| 457 | else: |
| 458 | buffer.put(ALPHA_NUM.find(chars), 6) |
| 459 | else: |
| 460 | # Iterating a bytestring in Python 3 returns an integer, |
| 461 | # no need to ord(). |
| 462 | data = self.data |
| 463 | for c in data: |
| 464 | buffer.put(c, 8) |
| 465 | |
| 466 | def __repr__(self): |
| 467 | return repr(self.data) |
| 468 | |
| 469 | |
| 470 | class BitBuffer: |
no outgoing calls