atoi.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* SPDX-License-Identifier: MIT */
  2. /*
  3. * Copyright © 2005-2014 Rich Felker, et al.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining
  6. * a copy of this software and associated documentation files (the
  7. * "Software"), to deal in the Software without restriction, including
  8. * without limitation the rights to use, copy, modify, merge, publish,
  9. * distribute, sublicense, and/or sell copies of the Software, and to
  10. * permit persons to whom the Software is furnished to do so, subject to
  11. * the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. /* From: http://fossies.org/dox/musl-1.0.5/atoi_8c_source.html */
  25. #include <stdlib.h>
  26. #include <ctype.h>
  27. int atoi(const char *s)
  28. {
  29. int n = 0;
  30. int neg = 0;
  31. while (isspace(*s)) {
  32. s++;
  33. }
  34. switch (*s) {
  35. case '-':
  36. neg = 1;
  37. s++;
  38. break; /* artifact to quiet coverity warning */
  39. case '+':
  40. s++;
  41. default:
  42. /* Add an empty default with break, this is a defensive programming.
  43. * Static analysis tool won't raise a violation if default is empty,
  44. * but has that comment.
  45. */
  46. break;
  47. }
  48. /* Compute n as a negative number to avoid overflow on INT_MIN */
  49. while (isdigit(*s)) {
  50. n = 10*n - (*s++ - '0');
  51. }
  52. return neg ? n : -n;
  53. }