wcstol.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "stdio_impl.h"
  2. #include "intscan.h"
  3. #include "shgetc.h"
  4. /* This read function heavily cheats. It knows:
  5. * (1) len will always be 1
  6. * (2) non-ascii characters don't matter */
  7. static size_t do_read(FILE *f, unsigned char *buf, size_t len)
  8. {
  9. size_t i;
  10. const wchar_t *wcs = f->cookie;
  11. for (i=0; i<f->buf_size && wcs[i]; i++)
  12. f->buf[i] = wcs[i] < 128 ? wcs[i] : '@';
  13. f->rpos = f->buf;
  14. f->rend = f->buf + i;
  15. f->cookie = (void *)(wcs+i);
  16. if (i && len) {
  17. *buf = *f->rpos++;
  18. return 1;
  19. }
  20. return 0;
  21. }
  22. static unsigned long long wcstox(const wchar_t *s, wchar_t **p, int base, unsigned long long lim)
  23. {
  24. unsigned char buf[64];
  25. FILE f = {0};
  26. f.flags = 0;
  27. f.rpos = f.rend = 0;
  28. f.buf = buf;
  29. f.buf_size = sizeof buf;
  30. f.lock = -1;
  31. f.read = do_read;
  32. f.cookie = (void *)s;
  33. shlim(&f, 0);
  34. unsigned long long y = __intscan(&f, base, 1, lim);
  35. if (p) {
  36. size_t cnt = shcnt(&f);
  37. *p = (wchar_t *)s + cnt;
  38. }
  39. return y;
  40. }
  41. unsigned long long wcstoull(const wchar_t *s, wchar_t **p, int base)
  42. {
  43. return wcstox(s, p, base, ULLONG_MAX);
  44. }
  45. long long wcstoll(const wchar_t *s, wchar_t **p, int base)
  46. {
  47. return wcstox(s, p, base, LLONG_MIN);
  48. }
  49. unsigned long wcstoul(const wchar_t *s, wchar_t **p, int base)
  50. {
  51. return wcstox(s, p, base, ULONG_MAX);
  52. }
  53. long wcstol(const wchar_t *s, wchar_t **p, int base)
  54. {
  55. return wcstox(s, p, base, 0UL+LONG_MIN);
  56. }
  57. intmax_t wcstoimax(const wchar_t *s, wchar_t **p, int base)
  58. {
  59. return wcstoll(s, p, base);
  60. }
  61. uintmax_t wcstoumax(const wchar_t *s, wchar_t **p, int base)
  62. {
  63. return wcstoull(s, p, base);
  64. }