util.c 689 B

1234567891011121314151617181920212223242526272829303132333435
  1. #include <stdlib.h>
  2. #include <errno.h>
  3. #include "util.h"
  4. /*
  5. * Safer wrapper of strtoll. Return 0 on success, otherwise -1.
  6. * Idea from corosync-qdevice project
  7. */
  8. int
  9. util_strtonum(const char *str, long long int min_val, long long int max_val,
  10. long long int *res)
  11. {
  12. long long int tmp_ll;
  13. char *ep;
  14. if (min_val > max_val) {
  15. return (-1);
  16. }
  17. errno = 0;
  18. tmp_ll = strtoll(str, &ep, 10);
  19. if (ep == str || *ep != '\0' || errno != 0) {
  20. return (-1);
  21. }
  22. if (tmp_ll < min_val || tmp_ll > max_val) {
  23. return (-1);
  24. }
  25. *res = tmp_ll;
  26. return (0);
  27. }