6 int atoi(const char *str)
8 return strtol(str, 0, 10);
11 long atol(const char *str)
13 return strtol(str, 0, 10);
16 long strtol(const char *str, char **endp, int base)
21 const char *start = str;
23 while(isspace(*str)) str++;
27 if(str[1] == 'x' || str[1] == 'X') {
39 } else if(*str == '-') {
46 char c = tolower(*str);
50 } else if(c >= 'a' && c <= 'f') {
60 acc = acc * base + val;
65 *endp = (char*)(valid ? str : start);
68 return sign > 0 ? acc : -acc;
71 void itoa(int val, char *buf, int base)
77 if(base <= 0) base = 10;
89 int digit = val % base;
90 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
106 void xtoa(unsigned int val, char *buf)
116 unsigned int digit = val & 0xf;
117 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
129 void utoa(unsigned int val, char *buf, int base)
131 static char rbuf[16];
139 if(base <= 0) base = 10;
146 unsigned int digit = val % base;
147 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
159 #define QSORT_THRESHOLD 4
160 #define ITEM(idx) ((char*)arr + (idx) * itemsz)
174 static void ins_sort(void *arr, size_t count, size_t itemsz, int (*cmp)(const void*, const void*))
179 if(count <= 1) return;
181 it = (char*)arr + itemsz;
182 for(i=1; i<count; i++) {
185 while(a > (char*)arr && cmp(a, (b = a - itemsz)) < 0) {
192 void qsort(void *arr, size_t count, size_t itemsz, int (*cmp)(const void*, const void*))
194 char *ma, *mb, *mc, *left, *right;
195 size_t sepidx, nleft, nright;
197 if(count <= 1) return;
199 if(count < QSORT_THRESHOLD) {
200 ins_sort(arr, count, itemsz, cmp);
205 mb = ITEM(count / 2);
206 mc = ITEM(count - 1);
207 if(cmp(ma, mb) < 0) SWAP(ma, mb);
208 if(cmp(mc, ma) < 0) SWAP(mc, ma);
213 while(cmp(left, ma) < 0) left += itemsz;
214 while(cmp(ma, right) < 0) right -= itemsz;
215 if(left >= right) break;
219 sepidx = (right - (char*)arr) / itemsz;
221 nright = count - nleft - 1;
223 qsort(ma, nleft, itemsz, cmp);
224 qsort(right + itemsz, nright, itemsz, cmp);