From ac69b4548697d8bb01df958029b40b7905d19cd7 Mon Sep 17 00:00:00 2001 From: Dave Rodgman Date: Thu, 10 Aug 2023 12:13:27 +0100 Subject: [PATCH] Document and test mbedtls_ct_size_if_else_0 Signed-off-by: Dave Rodgman --- library/constant_time_internal.h | 16 ++++++++++++++++ tests/suites/test_suite_constant_time.function | 1 + 2 files changed, 17 insertions(+) diff --git a/library/constant_time_internal.h b/library/constant_time_internal.h index 23caa244e7..b6c7ecb215 100644 --- a/library/constant_time_internal.h +++ b/library/constant_time_internal.h @@ -325,6 +325,22 @@ static inline mbedtls_mpi_uint mbedtls_ct_mpi_uint_if(mbedtls_ct_condition_t con */ static inline unsigned mbedtls_ct_uint_if_else_0(mbedtls_ct_condition_t condition, unsigned if1); +/** Choose between an unsigned value and 0. + * + * Functionally equivalent to: + * + * condition ? if1 : 0. + * + * Functionally equivalent to mbedtls_ct_size_if(condition, if1, 0) but + * results in smaller code size. + * + * \param condition Condition to test. + * \param if1 Value to use if \p condition == MBEDTLS_CT_TRUE. + * + * \return \c if1 if \p condition == MBEDTLS_CT_TRUE, otherwise 0. + */ +static inline size_t mbedtls_ct_size_if_else_0(mbedtls_ct_condition_t condition, size_t if1); + #if defined(MBEDTLS_BIGNUM_C) /** Choose between an mbedtls_mpi_uint value and 0. diff --git a/tests/suites/test_suite_constant_time.function b/tests/suites/test_suite_constant_time.function index a8ba575cff..0e2cfdc0cb 100644 --- a/tests/suites/test_suite_constant_time.function +++ b/tests/suites/test_suite_constant_time.function @@ -136,6 +136,7 @@ void mbedtls_ct_if(char *c_str, char *t_str, char *f_str) #endif TEST_EQUAL(mbedtls_ct_uint_if_else_0(c, t), (unsigned) expected0); + TEST_EQUAL(mbedtls_ct_size_if_else_0(c, (size_t) t), (size_t) expected0); #if defined(MBEDTLS_BIGNUM_C) TEST_EQUAL(mbedtls_ct_mpi_uint_if_else_0(c, t), (mbedtls_mpi_uint) expected0); #endif