View a bytes-compatible object as a sequence of objects described by a struct format code.
| 710 | |
| 711 | |
| 712 | class TypedView(Sequence): |
| 713 | """ |
| 714 | View a bytes-compatible object as a sequence of objects described |
| 715 | by a struct format code. |
| 716 | """ |
| 717 | |
| 718 | def __init__(self, mem, mem_format): |
| 719 | assert isinstance(mem, memoryview) |
| 720 | self.mem = mem |
| 721 | self.mem_format = mem_format |
| 722 | self.byte_width = struct.calcsize('=' + mem_format) |
| 723 | self.length = mem.nbytes // self.byte_width |
| 724 | |
| 725 | def _check_index(self, index): |
| 726 | if not 0 <= index < self.length: |
| 727 | raise IndexError("Wrong index for bitmap") |
| 728 | |
| 729 | def __len__(self): |
| 730 | return self.length |
| 731 | |
| 732 | def __getitem__(self, index): |
| 733 | self._check_index(index) |
| 734 | w = self.byte_width |
| 735 | # Cannot use memoryview.cast() because the 'e' format for half-floats |
| 736 | # is poorly supported. |
| 737 | mem = self.mem[index * w:(index + 1) * w] |
| 738 | return struct.unpack('=' + self.mem_format, mem) |
| 739 | |
| 740 | |
| 741 | class Bitmap(Sequence): |