parse_number.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @file parse_number.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Numeric string parsing.
  25. */
  26. #ifndef BADVPN_MISC_PARSE_NUMBER_H
  27. #define BADVPN_MISC_PARSE_NUMBER_H
  28. #include <inttypes.h>
  29. #include <string.h>
  30. #include <stddef.h>
  31. #include <misc/debug.h>
  32. static int parse_unsigned_integer_bin (const char *str, size_t str_len, uintmax_t *out) WARN_UNUSED;
  33. static int parse_unsigned_integer (const char *str, uintmax_t *out) WARN_UNUSED;
  34. int parse_unsigned_integer_bin (const char *str, size_t str_len, uintmax_t *out)
  35. {
  36. uintmax_t n = 0;
  37. if (str_len == 0) {
  38. return 0;
  39. }
  40. while (str_len > 0) {
  41. if (*str < '0' || *str > '9') {
  42. return 0;
  43. }
  44. int digit = *str - '0';
  45. if (n > UINTMAX_MAX / 10) {
  46. return 0;
  47. }
  48. n *= 10;
  49. if (digit > UINTMAX_MAX - n) {
  50. return 0;
  51. }
  52. n += digit;
  53. str++;
  54. str_len--;
  55. }
  56. *out = n;
  57. return 1;
  58. }
  59. int parse_unsigned_integer (const char *str, uintmax_t *out)
  60. {
  61. return parse_unsigned_integer_bin(str, strlen(str), out);
  62. }
  63. #endif