Document undefined case. Clarify test code.
Signed-off-by: Dave Rodgman <dave.rodgman@arm.com>
diff --git a/library/bignum_core.c b/library/bignum_core.c
index 1f3a57c..998c06c 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -33,11 +33,18 @@
#include "bn_mul.h"
#include "constant_time_internal.h"
+/**
+ * \brief Count leading zeros
+ *
+ * \warning The result is undefined if \p a == 0
+ *
+ * \param a The value to operate on
+ *
+ * \return The number of leading zeros, if \p a != 0. If \p a == 0, the result
+ * is undefined.
+ */
inline size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a)
{
- /* Note: the result is undefined for a == 0
- * (because this is the behaviour of __builtin_clz).
- */
#if defined(__has_builtin)
#if __has_builtin(__builtin_clz)
if (sizeof(mbedtls_mpi_uint) == sizeof(unsigned int)) {
diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function
index 6f810ff..53aa002 100644
--- a/tests/suites/test_suite_bignum_core.function
+++ b/tests/suites/test_suite_bignum_core.function
@@ -311,25 +311,28 @@
/* BEGIN_CASE */
-void mpi_core_clz(int lz, int tz)
+void mpi_core_clz(int leading_zeros, int trailing_zeros)
{
- if ((size_t) (lz + tz) >= (sizeof(mbedtls_mpi_uint) * 8)) {
+ if ((size_t) (leading_zeros + trailing_zeros) >= (sizeof(mbedtls_mpi_uint) * 8)) {
// can't fit required number of leading and trailing zeros - skip test
goto exit;
}
+ // Construct a test input value where the count of leading zeros and
+ // trailing zeros is given in the test case, and we add ones to fill
+ // the gap.
mbedtls_mpi_uint x;
- if ((lz + tz) > 0) {
+ if ((leading_zeros + trailing_zeros) > 0) {
// some zero bits
- uint32_t s = (sizeof(mbedtls_mpi_uint) * 8 - lz - tz);
- x = ((((mbedtls_mpi_uint) 1) << s) - 1) << tz;
+ uint32_t s = (sizeof(mbedtls_mpi_uint) * 8 - leading_zeros - trailing_zeros);
+ x = ((((mbedtls_mpi_uint) 1) << s) - 1) << trailing_zeros;
} else {
// all bits set
x = ~((mbedtls_mpi_uint) 0);
}
size_t n = mbedtls_mpi_core_clz(x);
- TEST_EQUAL(n, lz);
+ TEST_EQUAL(n, leading_zeros);
exit:
;
}