Unify mask generation functions
Generate all-bits 0 or all bits 1 mask from a value instead of from a bit.
Signed-off-by: gabor-mezei-arm <gabor.mezei@arm.com>
diff --git a/library/constant_time.c b/library/constant_time.c
index 496843d..a407c79 100644
--- a/library/constant_time.c
+++ b/library/constant_time.c
@@ -72,9 +72,9 @@
}
/*
- * Turn a bit into a mask:
- * - if bit == 1, return the all-bits 1 mask, aka (size_t) -1
- * - if bit == 0, return the all-bits 0 mask, aka 0
+ * Turn a value into a mask:
+ * - if value != 0, return the all-bits 1 mask, aka (size_t) -1
+ * - if value == 0, return the all-bits 0 mask, aka 0
*
* This function can be used to write constant-time code by replacing branches
* with bit operations using masks.
@@ -82,7 +82,7 @@
* This function is implemented without using comparison operators, as those
* might be translated to branches by some compilers on some platforms.
*/
-size_t mbedtls_cf_size_mask( size_t bit )
+size_t mbedtls_cf_size_mask( size_t value )
{
/* MSVC has a warning about unary minus on unsigned integer types,
* but this is well-defined and precisely what we want to do here. */
@@ -90,7 +90,7 @@
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
- return -bit;
+ return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
diff --git a/library/constant_time.h b/library/constant_time.h
index ed6ec6a..80e59da 100644
--- a/library/constant_time.h
+++ b/library/constant_time.h
@@ -36,7 +36,7 @@
unsigned mbedtls_cf_uint_mask( unsigned value );
-size_t mbedtls_cf_size_mask( size_t bit );
+size_t mbedtls_cf_size_mask( size_t value );
size_t mbedtls_cf_size_mask_lt( size_t x,
size_t y );