Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1-D with n * itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) * itemsize = bytelen applies. On su
(exporter, fmt, itemsize, shape=None)
| 651 | # ====================================================================== |
| 652 | |
| 653 | def cast_items(exporter, fmt, itemsize, shape=None): |
| 654 | """Interpret the raw memory of 'exporter' as a list of items with |
| 655 | size 'itemsize'. If shape=None, the new structure is assumed to |
| 656 | be 1-D with n * itemsize = bytelen. If shape is given, the usual |
| 657 | constraint for contiguous arrays prod(shape) * itemsize = bytelen |
| 658 | applies. On success, return (items, shape). If the constraints |
| 659 | cannot be met, return (None, None). If a chunk of bytes is interpreted |
| 660 | as NaN as a result of float conversion, return ('nan', None).""" |
| 661 | bytelen = exporter.nbytes |
| 662 | if shape: |
| 663 | if prod(shape) * itemsize != bytelen: |
| 664 | return None, shape |
| 665 | elif shape == []: |
| 666 | if exporter.ndim == 0 or itemsize != bytelen: |
| 667 | return None, shape |
| 668 | else: |
| 669 | n, r = divmod(bytelen, itemsize) |
| 670 | shape = [n] |
| 671 | if r != 0: |
| 672 | return None, shape |
| 673 | |
| 674 | mem = exporter.tobytes() |
| 675 | byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)] |
| 676 | |
| 677 | items = [] |
| 678 | for v in byteitems: |
| 679 | item = struct.unpack(fmt, v)[0] |
| 680 | if item != item: |
| 681 | return 'nan', shape |
| 682 | items.append(item) |
| 683 | |
| 684 | return (items, shape) if shape != [] else (items[0], shape) |
| 685 | |
| 686 | def gencastshapes(): |
| 687 | """Generate shapes to test casting.""" |