From: Naveen Albert Date: Wed, 1 Oct 2025 15:34:20 +0000 (-0400) Subject: func_math: Add DIGIT_SUM function. X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;p=thirdparty%2Fasterisk.git func_math: Add DIGIT_SUM function. Add a function (DIGIT_SUM) which returns the digit sum of a number. Resolves: #1499 UserNote: The DIGIT_SUM function can be used to return the digit sum of a number. --- diff --git a/funcs/func_math.c b/funcs/func_math.c index 5c68866130..9f0ceaa398 100644 --- a/funcs/func_math.c +++ b/funcs/func_math.c @@ -177,6 +177,28 @@ + + + 23.1.0 + 22.7.0 + 20.17.0 + + + Returns the sum of all the digits in a number. + + + + + + Returns the numeric sum of all the individual digits in a number, summed up. + This can be useful for computing checksums based on the number, + where errors are typically digits being off by one. + + same => n,Set(digitsum=${DIGIT_SUM(859)}) ; assigns digitsum=22 + same => n,Set(checksum=$[${digitsum} % 10]) ; assigns checksum=2 + + + ***/ enum TypeOfFunctions { @@ -634,6 +656,27 @@ static int acf_abs_exec(struct ast_channel *chan, const char *cmd, return 0; } +static int acf_digit_sum_exec(struct ast_channel *chan, const char *cmd, + char *parse, char *buffer, size_t buflen) +{ + int sum = 0; + + if (ast_strlen_zero(parse)) { + ast_log(LOG_WARNING, "Missing argument for number\n"); + return -1; + } + + for (; *parse; parse++) { + if (*parse < '0' || *parse > '9') { + continue; + } + sum += (*parse - '0'); + } + + snprintf(buffer, buflen, "%d", sum); + return 0; +} + static struct ast_custom_function math_function = { .name = "MATH", .read = math @@ -667,6 +710,11 @@ static struct ast_custom_function acf_abs = { .read_max = 12, }; +static struct ast_custom_function acf_digit_sum = { + .name = "DIGIT_SUM", + .read = acf_digit_sum_exec, +}; + #ifdef TEST_FRAMEWORK AST_TEST_DEFINE(test_MATH_function) { @@ -728,6 +776,7 @@ static int unload_module(void) res |= ast_custom_function_unregister(&acf_min); res |= ast_custom_function_unregister(&acf_max); res |= ast_custom_function_unregister(&acf_abs); + res |= ast_custom_function_unregister(&acf_digit_sum); AST_TEST_UNREGISTER(test_MATH_function); return res; @@ -743,6 +792,7 @@ static int load_module(void) res |= ast_custom_function_register(&acf_min); res |= ast_custom_function_register(&acf_max); res |= ast_custom_function_register(&acf_abs); + res |= ast_custom_function_register(&acf_digit_sum); AST_TEST_REGISTER(test_MATH_function); return res;