machine_size.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. """Detection of 32-bit and 64-bit machines and byte alignment."""
  17. import sys
  18. MAX_INT = sys.maxsize
  19. MAX_INT64 = (1 << 63) - 1
  20. MAX_INT32 = (1 << 31) - 1
  21. MAX_INT16 = (1 << 15) - 1
  22. # Determine the word size of the processor.
  23. if MAX_INT == MAX_INT64:
  24. # 64-bit processor.
  25. MACHINE_WORD_SIZE = 64
  26. elif MAX_INT == MAX_INT32:
  27. # 32-bit processor.
  28. MACHINE_WORD_SIZE = 32
  29. else:
  30. # Else we just assume 64-bit processor keeping up with modern times.
  31. MACHINE_WORD_SIZE = 64
  32. def get_word_alignment(num, force_arch=64,
  33. _machine_word_size=MACHINE_WORD_SIZE):
  34. """
  35. Returns alignment details for the given number based on the platform
  36. Python is running on.
  37. :param num:
  38. Unsigned integral number.
  39. :param force_arch:
  40. If you don't want to use 64-bit unsigned chunks, set this to
  41. anything other than 64. 32-bit chunks will be preferred then.
  42. Default 64 will be used when on a 64-bit machine.
  43. :param _machine_word_size:
  44. (Internal) The machine word size used for alignment.
  45. :returns:
  46. 4-tuple::
  47. (word_bits, word_bytes,
  48. max_uint, packing_format_type)
  49. """
  50. max_uint64 = 0xffffffffffffffff
  51. max_uint32 = 0xffffffff
  52. max_uint16 = 0xffff
  53. max_uint8 = 0xff
  54. if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32:
  55. # 64-bit unsigned integer.
  56. return 64, 8, max_uint64, "Q"
  57. elif num > max_uint16:
  58. # 32-bit unsigned integer
  59. return 32, 4, max_uint32, "L"
  60. elif num > max_uint8:
  61. # 16-bit unsigned integer.
  62. return 16, 2, max_uint16, "H"
  63. else:
  64. # 8-bit unsigned integer.
  65. return 8, 1, max_uint8, "B"