From 25823013f8143be98204589f4da8b086db81ff2a Mon Sep 17 00:00:00 2001 From: "suchi.sahoo" Date: Mon, 9 Aug 2021 21:28:56 +0300 Subject: [PATCH] [Core] Add switch_safe_atol() and switch_safe_atoll() functions. Add a unit-test. --- src/include/switch_utils.h | 28 ++++++++++++++++++++++++++-- tests/unit/switch_core.c | 16 ++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/include/switch_utils.h b/src/include/switch_utils.h index 20655ecd4e..24c6151331 100644 --- a/src/include/switch_utils.h +++ b/src/include/switch_utils.h @@ -831,10 +831,10 @@ static inline char *switch_clean_name_string(char *s) /*! - \brief Turn a string into a number (default if NULL) + \brief Turn a string into an integer (default if NULL) \param nptr the string \param dft the default - \return the number version of the string or the default + \return the integer version of the string or the default */ static inline int switch_safe_atoi(const char *nptr, int dft) { @@ -842,6 +842,30 @@ static inline int switch_safe_atoi(const char *nptr, int dft) } +/*! + \brief Turn a string into a long integer (default if NULL) + \param nptr the string + \param dft the default + \return the long integer version of the string or the default +*/ +static inline long int switch_safe_atol(const char *nptr, long int dft) +{ + return nptr ? atol(nptr) : dft; +} + + +/*! + \brief Turn a string into a long long integer (default if NULL) + \param nptr the string + \param dft the default + \return the long long integer version of the string or the default +*/ +static inline long long int switch_safe_atoll(const char *nptr, long long int dft) +{ + return nptr ? atoll(nptr) : dft; +} + + /*! \brief Free a pointer and set it to NULL unless it already is NULL \param it the pointer diff --git a/tests/unit/switch_core.c b/tests/unit/switch_core.c index bba7272cac..ed84e39c06 100644 --- a/tests/unit/switch_core.c +++ b/tests/unit/switch_core.c @@ -223,6 +223,22 @@ FST_CORE_BEGIN("./conf") #endif } FST_TEST_END() + + FST_TEST_BEGIN(test_switch_safe_atoXX) + { + fst_check_int_equals(switch_safe_atoi("1", 0), 1); + fst_check_int_equals(switch_safe_atoi("", 2), 0); + fst_check_int_equals(switch_safe_atoi(0, 3), 3); + + fst_check_int_equals(switch_safe_atol("9275806", 0), 9275806); + fst_check_int_equals(switch_safe_atol("", 2), 0); + fst_check_int_equals(switch_safe_atol(0, 3), 3); + + fst_check_int_equals(switch_safe_atoll("9275806", 0), 9275806); + fst_check_int_equals(switch_safe_atoll("", 2), 0); + fst_check_int_equals(switch_safe_atoll(0, 3), 3); + } + FST_TEST_END() } FST_SUITE_END() }