diff options
Diffstat (limited to 'src/tools/mhd_tool_str_to_uint.h')
-rw-r--r-- | src/tools/mhd_tool_str_to_uint.h | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/tools/mhd_tool_str_to_uint.h b/src/tools/mhd_tool_str_to_uint.h new file mode 100644 index 00000000..5fc91b58 --- /dev/null +++ b/src/tools/mhd_tool_str_to_uint.h | |||
@@ -0,0 +1,69 @@ | |||
1 | /* | ||
2 | This file is part of GNU libmicrohttpd | ||
3 | Copyright (C) 2023 Evgeny Grin (Karlson2k) | ||
4 | |||
5 | This library is free software; you can redistribute it and/or | ||
6 | modify it under the terms of the GNU Lesser General Public | ||
7 | License as published by the Free Software Foundation; either | ||
8 | version 2.1 of the License, or (at your option) any later version. | ||
9 | |||
10 | This library is distributed in the hope that it will be useful, | ||
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
13 | Lesser General Public License for more details. | ||
14 | |||
15 | You should have received a copy of the GNU Lesser General Public | ||
16 | License along with this library; if not, write to the Free Software | ||
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA | ||
18 | */ | ||
19 | |||
20 | /** | ||
21 | * @file tools/mhd_tool_str_to_uint.c | ||
22 | * @brief Implementation of HTTP server optimised for fast replies | ||
23 | * based on MHD. | ||
24 | * @author Karlson2k (Evgeny Grin) | ||
25 | */ | ||
26 | |||
27 | #ifndef MHD_TOOL_STR_TO_UINT_H_ | ||
28 | #define MHD_TOOL_STR_TO_UINT_H_ | ||
29 | |||
30 | #include <stddef.h> | ||
31 | |||
32 | /** | ||
33 | * Convert decimal string to unsigned int. | ||
34 | * Function stops at the end of the string or on first non-digit character. | ||
35 | * @param str the string to convert | ||
36 | * @param[out] value the pointer to put the result | ||
37 | * @return return the number of digits converted or | ||
38 | * zero if no digits found or result would overflow the output | ||
39 | * variable (the output set to UINT_MAX in this case). | ||
40 | */ | ||
41 | static size_t | ||
42 | mhd_tool_str_to_uint (const char *str, unsigned int *value) | ||
43 | { | ||
44 | size_t i; | ||
45 | unsigned int v = 0; | ||
46 | *value = 0; | ||
47 | |||
48 | for (i = 0; 0 != str[i]; ++i) | ||
49 | { | ||
50 | const char chr = str[i]; | ||
51 | unsigned int digit; | ||
52 | if (('0' > chr) || ('9' < chr)) | ||
53 | break; | ||
54 | digit = (unsigned char) (chr - '0'); | ||
55 | if ((((0U - 1) / 10) < v) || ((v * 10 + digit) < v)) | ||
56 | { | ||
57 | /* Overflow */ | ||
58 | *value = 0U - 1; | ||
59 | return 0; | ||
60 | } | ||
61 | v *= 10; | ||
62 | v += digit; | ||
63 | } | ||
64 | *value = v; | ||
65 | return i; | ||
66 | } | ||
67 | |||
68 | |||
69 | #endif /* MHD_TOOL_STR_TO_UINT_H_ */ | ||