/ adafruit_rsa / machine_size.py
machine_size.py
 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  __version__ = "0.0.0-auto.0"
22  __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git"
23  
24  MAX_INT = sys.maxsize
25  MAX_INT64 = (1 << 63) - 1
26  MAX_INT32 = (1 << 31) - 1
27  MAX_INT16 = (1 << 15) - 1
28  
29  # Determine the word size of the processor.
30  if MAX_INT == MAX_INT64:
31      # 64-bit processor.
32      MACHINE_WORD_SIZE = 64
33  elif MAX_INT == MAX_INT32:
34      # 32-bit processor.
35      MACHINE_WORD_SIZE = 32
36  else:
37      # Else we just assume 64-bit processor keeping up with modern times.
38      MACHINE_WORD_SIZE = 64
39  
40  
41  def get_word_alignment(num, force_arch=64, _machine_word_size=MACHINE_WORD_SIZE):
42      """
43      Returns alignment details for the given number based on the platform
44      Python is running on.
45  
46      :param num:
47          Unsigned integral number.
48      :param force_arch:
49          If you don't want to use 64-bit unsigned chunks, set this to
50          anything other than 64. 32-bit chunks will be preferred then.
51          Default 64 will be used when on a 64-bit machine.
52      :param _machine_word_size:
53          (Internal) The machine word size used for alignment.
54      :returns:
55          4-tuple::
56  
57              (word_bits, word_bytes,
58               max_uint, packing_format_type)
59      """
60      max_uint64 = 0xFFFFFFFFFFFFFFFF
61      max_uint32 = 0xFFFFFFFF
62      max_uint16 = 0xFFFF
63      max_uint8 = 0xFF
64  
65      if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32:
66          # 64-bit unsigned integer.
67          return 64, 8, max_uint64, "Q"
68      if num > max_uint16:
69          # 32-bit unsigned integer
70          return 32, 4, max_uint32, "L"
71      if num > max_uint8:
72          # 16-bit unsigned integer.
73          return 16, 2, max_uint16, "H"
74      # 8-bit unsigned integer.
75      return 8, 1, max_uint8, "B"