Raw Reader with uint32_t parsing


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <inttypes.h>
  6.  
  7. typedef unsigned int uint_t;
  8.  
  9. class RawReader
  10. {
  11. static const uint_t RBUF_SIZE = 8192;
  12. char rbuf[RBUF_SIZE];
  13.  
  14. char *rlim, *rpos;
  15. int rrlen, reof;
  16.  
  17. char* read_more(char *rpos)
  18. {
  19. int l, s, t;
  20. char *p;
  21.  
  22. if (reof)
  23. return rpos;
  24.  
  25. l = rrlen - (rpos - rbuf);
  26. if (rpos != rbuf)
  27. memmove(rbuf, rpos, l);
  28. rpos = rbuf;
  29. p = rbuf + l;
  30. t = sizeof(rbuf) - l;
  31. s = read(0, p, t);
  32. if (s < 0)
  33. s = 0;
  34. rrlen = l + s;
  35. rlim = rpos + rrlen;
  36. if (s <= 0) {
  37. reof = 1;
  38. }
  39.  
  40. return rpos;
  41. }
  42.  
  43. public:
  44. void init(void)
  45. {
  46. rrlen = 0;
  47. reof = 0;
  48. rlim = rbuf;
  49. rpos = rbuf;
  50. }
  51.  
  52. inline int rnextf() { return *rpos++; }
  53.  
  54. inline int rnext()
  55. {
  56. if (rlim - rpos <= 0)
  57. rpos = read_more(rpos);
  58. return (rlim - rpos > 0) ? rnextf() : -1;
  59. }
  60.  
  61. inline uint32_t getu32()
  62. {
  63. if (rlim - rpos < 12)
  64. rpos = read_more(rpos);
  65.  
  66. uint32_t v;
  67. do {
  68. v = rnextf() - '0';
  69. } while (v >= 10);
  70.  
  71. uint32_t res = v;
  72.  
  73. for (;;) {
  74. v = rnextf() - '0';
  75. if (v >= 10)
  76. break;
  77. res = res * 10 + v;
  78. }
  79.  
  80. return res;
  81. }
  82.  
  83. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.