|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu> |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Detection of 32-bit and 64-bit machines and byte alignment.""" |
| 18 | + |
| 19 | +import sys |
| 20 | + |
| 21 | +MAX_INT = sys.maxsize |
| 22 | +MAX_INT64 = (1 << 63) - 1 |
| 23 | +MAX_INT32 = (1 << 31) - 1 |
| 24 | +MAX_INT16 = (1 << 15) - 1 |
| 25 | + |
| 26 | +# Determine the word size of the processor. |
| 27 | +if MAX_INT == MAX_INT64: |
| 28 | + # 64-bit processor. |
| 29 | + MACHINE_WORD_SIZE = 64 |
| 30 | +elif MAX_INT == MAX_INT32: |
| 31 | + # 32-bit processor. |
| 32 | + MACHINE_WORD_SIZE = 32 |
| 33 | +else: |
| 34 | + # Else we just assume 64-bit processor keeping up with modern times. |
| 35 | + MACHINE_WORD_SIZE = 64 |
| 36 | + |
| 37 | + |
| 38 | +def get_word_alignment(num, force_arch=64, |
| 39 | + _machine_word_size=MACHINE_WORD_SIZE): |
| 40 | + """ |
| 41 | + Returns alignment details for the given number based on the platform |
| 42 | + Python is running on. |
| 43 | +
|
| 44 | + :param num: |
| 45 | + Unsigned integral number. |
| 46 | + :param force_arch: |
| 47 | + If you don't want to use 64-bit unsigned chunks, set this to |
| 48 | + anything other than 64. 32-bit chunks will be preferred then. |
| 49 | + Default 64 will be used when on a 64-bit machine. |
| 50 | + :param _machine_word_size: |
| 51 | + (Internal) The machine word size used for alignment. |
| 52 | + :returns: |
| 53 | + 4-tuple:: |
| 54 | +
|
| 55 | + (word_bits, word_bytes, |
| 56 | + max_uint, packing_format_type) |
| 57 | + """ |
| 58 | + max_uint64 = 0xffffffffffffffff |
| 59 | + max_uint32 = 0xffffffff |
| 60 | + max_uint16 = 0xffff |
| 61 | + max_uint8 = 0xff |
| 62 | + |
| 63 | + if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32: |
| 64 | + # 64-bit unsigned integer. |
| 65 | + return 64, 8, max_uint64, "Q" |
| 66 | + elif num > max_uint16: |
| 67 | + # 32-bit unsigned integer |
| 68 | + return 32, 4, max_uint32, "L" |
| 69 | + elif num > max_uint8: |
| 70 | + # 16-bit unsigned integer. |
| 71 | + return 16, 2, max_uint16, "H" |
| 72 | + else: |
| 73 | + # 8-bit unsigned integer. |
| 74 | + return 8, 1, max_uint8, "B" |
0 commit comments