Merged revisions 121078 via svnmerge from
[asterisk-bristuff.git] / funcs / func_rand.c
bloba3db21d26b0b761d86ae71b33086a7ea9c456f2d
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2006, Digium, Inc.
5 * Copyright (C) 2006, Claude Patry
7 * See http://www.asterisk.org for more information about
8 * the Asterisk project. Please do not directly contact
9 * any of the maintainers of this project for assistance;
10 * the project provides a web site, mailing lists and IRC
11 * channels for your use.
13 * This program is free software, distributed under the terms of
14 * the GNU General Public License Version 2. See the LICENSE file
15 * at the top of the source tree.
18 /*! \file
20 * \brief Generate Random Number
22 * \author Claude Patry <cpatry@gmail.com>
23 * \author Tilghman Lesher ( http://asterisk.drunkcoder.com/ )
24 * \ingroup functions
27 #include "asterisk.h"
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31 #include "asterisk/module.h"
32 #include "asterisk/channel.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/utils.h"
35 #include "asterisk/app.h"
37 static int acf_rand_exec(struct ast_channel *chan, const char *cmd,
38 char *parse, char *buffer, size_t buflen)
40 int min_int, response_int, max_int;
41 AST_DECLARE_APP_ARGS(args,
42 AST_APP_ARG(min);
43 AST_APP_ARG(max);
46 AST_STANDARD_APP_ARGS(args, parse);
48 if (ast_strlen_zero(args.min) || sscanf(args.min, "%d", &min_int) != 1)
49 min_int = 0;
51 if (ast_strlen_zero(args.max) || sscanf(args.max, "%d", &max_int) != 1)
52 max_int = RAND_MAX;
54 if (max_int < min_int) {
55 int tmp = max_int;
57 max_int = min_int;
58 min_int = tmp;
59 ast_debug(1, "max<min\n");
62 response_int = min_int + (ast_random() % (max_int - min_int + 1));
63 ast_debug(1, "%d was the lucky number in range [%d,%d]\n", response_int, min_int, max_int);
64 snprintf(buffer, buflen, "%d", response_int);
66 return 0;
69 static struct ast_custom_function acf_rand = {
70 .name = "RAND",
71 .synopsis = "Choose a random number in a range",
72 .syntax = "RAND([min][,max])",
73 .desc =
74 "Choose a random number between min and max. Min defaults to 0, if not\n"
75 "specified, while max defaults to RAND_MAX (2147483647 on many systems).\n"
76 " Example: Set(junky=${RAND(1,8)}); \n"
77 " Sets junky to a random number between 1 and 8, inclusive.\n",
78 .read = acf_rand_exec,
81 static int unload_module(void)
83 ast_custom_function_unregister(&acf_rand);
85 return 0;
88 static int load_module(void)
90 return ast_custom_function_register(&acf_rand);
93 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Random number dialplan function");