utils.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // My string-related utils library for now
  2. //
  3. // Written by: Test_User <hax@andrewyu.org>
  4. //
  5. // This is free and unencumbered software released into the public
  6. // domain.
  7. //
  8. // Anyone is free to copy, modify, publish, use, compile, sell, or
  9. // distribute this software, either in source code form or as a compiled
  10. // binary, for any purpose, commercial or non-commercial, and by any
  11. // means.
  12. //
  13. // In jurisdictions that recognize copyright laws, the author or authors
  14. // of this software dedicate any and all copyright interest in the
  15. // software to the public domain. We make this dedication for the benefit
  16. // of the public at large and to the detriment of our heirs and
  17. // successors. We intend this dedication to be an overt act of
  18. // relinquishment in perpetuity of all present and future rights to this
  19. // software under copyright law.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  24. // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  25. // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  26. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  27. // OTHER DEALINGS IN THE SOFTWARE.
  28. #include <stdint.h>
  29. #include "types.h"
  30. uint64_t str_to_unsigned(struct string str, char *err) {
  31. if (str.len == 0) {
  32. *err = 1;
  33. return 0;
  34. }
  35. uint64_t val = 0;
  36. while (str.len > 0) {
  37. switch(str.data[0]) {
  38. case '0':
  39. case '1':
  40. case '2':
  41. case '3':
  42. case '4':
  43. case '5':
  44. case '6':
  45. case '7':
  46. case '8':
  47. case '9':
  48. if (val > ((uint64_t)-1)/10) {
  49. *err = 1;
  50. return 0;
  51. }
  52. val *= 10;
  53. if (val > (-((uint64_t)((uint8_t)str.data[0] - 0x30) + 1))) {
  54. *err = 1;
  55. return 0;
  56. }
  57. val += (uint8_t)str.data[0] - 0x30;
  58. break;
  59. default:
  60. *err = 1;
  61. return 0;
  62. }
  63. str.data++;
  64. str.len--;
  65. }
  66. *err = 0;
  67. return val;
  68. }