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.
 
 
 
 

46 lines
1.4 KiB

  1. #include "scan.h"
  2. /* this is cut and paste from scan_ulong instead of calling scan_ulong
  3. * because this way scan_ushort can abort scanning when the number would
  4. * not fit into an unsigned short (as opposed to not fitting in an
  5. * unsigned long) */
  6. size_t scan_ushort(const char* src,unsigned short* dest) {
  7. if (sizeof(unsigned short) == sizeof(unsigned int)) {
  8. /* a good optimizing compiler should remove the else clause when not
  9. * needed */
  10. return scan_uint(src,(unsigned int*)dest);
  11. } if (sizeof(unsigned short) < sizeof(unsigned long)) {
  12. /* this is the regular case */
  13. const char* cur;
  14. unsigned short l;
  15. for (cur=src,l=0; *cur>='0' && *cur<='9'; ++cur) {
  16. unsigned long tmp=l*10ul+*cur-'0';
  17. if ((unsigned short)tmp != tmp) break;
  18. l=tmp;
  19. }
  20. if (cur>src) *dest=l;
  21. return (size_t)(cur-src);
  22. } else {
  23. /* the C standard says that sizeof(short) <= sizeof(unsigned int) <=
  24. * sizeof(unsigned long); this can never happen. Provoke a compile
  25. * error if it does */
  26. char compileerror[sizeof(unsigned long)-sizeof(unsigned short)];
  27. (void)compileerror;
  28. }
  29. }
  30. #ifdef UNITTEST
  31. #include <assert.h>
  32. int main() {
  33. unsigned short i;
  34. assert(scan_ushort("1234",&i)==4 && i==1234);
  35. assert(scan_ushort("-1",&i)==0);
  36. if (sizeof(short)==2) {
  37. assert(scan_ushort("123456",&i)==5 && i==12345);
  38. }
  39. return 0;
  40. }
  41. #endif