Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

40 lines
1.1 KiB

  1. #include "scan.h"
  2. static const unsigned long maxlong = ((unsigned long)-1)>>1;
  3. size_t scan_longn(const char *src,size_t n,long *dest) {
  4. register const char *tmp;
  5. register long int l;
  6. register unsigned char c;
  7. unsigned int neg;
  8. int ok;
  9. if (!n--) return 0;
  10. tmp=src; l=0; ok=0; neg=0;
  11. switch (*tmp) {
  12. case '-': neg=1; /* fall through */
  13. case '+': ++tmp;
  14. }
  15. while (n-->0 && (c=(unsigned char)(*tmp-'0'))<10) {
  16. unsigned long int n;
  17. /* we want to do: l=l*10+c
  18. * but we need to check for integer overflow.
  19. * to check whether l*10 overflows, we could do
  20. * if ((l*10)/10 != l)
  21. * however, multiplication and division are expensive.
  22. * so instead of *10 we do (l<<3) (i.e. *8) + (l<<1) (i.e. *2)
  23. * and check for overflow on all the intermediate steps */
  24. n=(unsigned long)l<<3; if ((n>>3)!=(unsigned long)l) break;
  25. if (n+((unsigned long)l<<1) < n) break;
  26. n+=(unsigned long)l<<1;
  27. if (n+c < n) break;
  28. n+=c;
  29. if (n > maxlong+neg) break;
  30. l=(long)n;
  31. ++tmp;
  32. ok=1;
  33. }
  34. if (!ok) return 0;
  35. *dest=(neg?-l:l);
  36. return (size_t)(tmp-src);
  37. }