blob: 279668fd5fcd226a56acc58867eecd08c8f6b3fe [file] [log] [blame]
Werner Lewis99e81782022-09-30 16:28:43 +01001"""Common features for bignum in test generation framework."""
2# Copyright The Mbed TLS Contributors
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://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, WITHOUT
13# 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
17import itertools
18import typing
19
20from abc import abstractmethod
21from typing import Iterator, List, Tuple, TypeVar
22
23T = TypeVar('T') #pylint: disable=invalid-name
24
Werner Lewisa8503122022-10-04 10:10:40 +010025def invmod(a: int, n: int) -> int:
26 """Return inverse of a to modulo n.
27
28 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
29 to long_invmod() in CPython.
30 """
31 b, c = 1, 0
32 while n:
33 q, r = divmod(a, n)
34 a, b, c, n = n, c, b - q*c, r
35 # at this point a is the gcd of the original inputs
36 if a == 1:
37 return b
38 raise ValueError("Not invertible")
39
Werner Lewis99e81782022-09-30 16:28:43 +010040def hex_to_int(val: str) -> int:
41 return int(val, 16) if val else 0
42
43def quote_str(val) -> str:
44 return "\"{}\"".format(val)
45
Werner Lewisf86c82e2022-10-19 13:50:10 +010046def bound_mpi(val: int, bits_in_limb: int) -> int:
47 """First number exceeding number of limbs needed for given input value."""
48 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010049
Werner Lewisf86c82e2022-10-19 13:50:10 +010050def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
51 """First number exceeding maximum of given number of limbs."""
52 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010053 return 1 << bits
54
Werner Lewisf86c82e2022-10-19 13:50:10 +010055def limbs_mpi(val: int, bits_in_limb: int) -> int:
56 """Return the number of limbs required to store value."""
57 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010058
59def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
60 """Return all pair combinations from input values.
61
62 The return value is cast, as older versions of mypy are unable to derive
63 the specific type returned by itertools.combinations_with_replacement.
64 """
65 return typing.cast(
66 List[Tuple[T, T]],
67 list(itertools.combinations_with_replacement(values, 2))
68 )
69
70
71class OperationCommon:
72 """Common features for bignum binary operations.
73
74 This adds functionality common in binary operation tests.
75
76 Attributes:
77 symbol: Symbol to use for the operation in case description.
78 input_values: List of values to use as test case inputs. These are
79 combined to produce pairs of values.
80 input_cases: List of tuples containing pairs of test case inputs. This
81 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010082 unique_combinations_only: Boolean to select if test case combinations
83 must be unique. If True, only A,B or B,A would be included as a test
84 case. If False, both A,B and B,A would be included.
Werner Lewis99e81782022-09-30 16:28:43 +010085 """
86 symbol = ""
87 input_values = [] # type: List[str]
88 input_cases = [] # type: List[Tuple[str, str]]
Werner Lewisbbf0a322022-10-04 10:07:13 +010089 unique_combinations_only = True
Werner Lewis99e81782022-09-30 16:28:43 +010090
91 def __init__(self, val_a: str, val_b: str) -> None:
92 self.arg_a = val_a
93 self.arg_b = val_b
94 self.int_a = hex_to_int(val_a)
95 self.int_b = hex_to_int(val_b)
96
97 def arguments(self) -> List[str]:
Werner Lewis1b20e7e2022-10-12 14:53:17 +010098 return [
99 quote_str(self.arg_a), quote_str(self.arg_b)
100 ] + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100101
102 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100103 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100104 """Get the result of the operation.
105
106 This could be calculated during initialization and stored as `_result`
107 and then returned, or calculated when the method is called.
108 """
109 raise NotImplementedError
110
111 @classmethod
112 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
113 """Generator to yield pairs of inputs.
114
115 Combinations are first generated from all input values, and then
116 specific cases provided.
117 """
Werner Lewisbbf0a322022-10-04 10:07:13 +0100118 if cls.unique_combinations_only:
119 yield from combination_pairs(cls.input_values)
120 else:
121 yield from (
122 (a, b)
123 for a in cls.input_values
124 for b in cls.input_values
125 )
Werner Lewis99e81782022-09-30 16:28:43 +0100126 yield from cls.input_cases
Janos Follathf8b3b722022-11-03 14:46:18 +0000127
128# BEGIN MERGE SLOT 1
129
130# END MERGE SLOT 1
131
132# BEGIN MERGE SLOT 2
133
134# END MERGE SLOT 2
135
136# BEGIN MERGE SLOT 3
137
138# END MERGE SLOT 3
139
140# BEGIN MERGE SLOT 4
141
142# END MERGE SLOT 4
143
144# BEGIN MERGE SLOT 5
145
146# END MERGE SLOT 5
147
148# BEGIN MERGE SLOT 6
149
150# END MERGE SLOT 6
151
152# BEGIN MERGE SLOT 7
153
154# END MERGE SLOT 7
155
156# BEGIN MERGE SLOT 8
157
158# END MERGE SLOT 8
159
160# BEGIN MERGE SLOT 9
161
162# END MERGE SLOT 9
163
164# BEGIN MERGE SLOT 10
165
166# END MERGE SLOT 10