parse_number.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. static int parse_unsigned_integer (const char *str, uintmax_t *out);
  30. int parse_unsigned_integer (const char *str, uintmax_t *out)
  31. {
  32. uintmax_t n = 0;
  33. if (!*str) {
  34. return 0;
  35. }
  36. while (*str) {
  37. if (*str < '0' || *str > '9') {
  38. return 0;
  39. }
  40. int digit = *str - '0';
  41. if (n > UINTMAX_MAX / 10) {
  42. return 0;
  43. }
  44. n *= 10;
  45. if (digit > UINTMAX_MAX - n) {
  46. return 0;
  47. }
  48. n += digit;
  49. str++;
  50. }
  51. *out = n;
  52. return 1;
  53. }
  54. #endif