A clone of btpd with my configuration changes.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

103 lines
2.0 KiB

  1. #include <assert.h>
  2. #include <inttypes.h>
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include "iobuf.h"
  8. #include "subr.h"
  9. struct iobuf
  10. iobuf_init(size_t size)
  11. {
  12. struct iobuf iob;
  13. iob.size = size;
  14. iob.off = 0;
  15. iob.skip = 0;
  16. iob.error = (iob.buf = malloc(size)) == NULL ? 1 : 0;
  17. return iob;
  18. }
  19. void
  20. iobuf_free(struct iobuf *iob)
  21. {
  22. if (iob->buf != NULL)
  23. free(iob->buf - iob->skip);
  24. iob->buf = NULL;
  25. iob->error = 1;
  26. }
  27. void
  28. iobuf_consumed(struct iobuf *iob, size_t count)
  29. {
  30. if (iob->error)
  31. return;
  32. assert(count <= iob->off);
  33. iob->skip += count;
  34. iob->buf += count;
  35. iob->off -= count;
  36. }
  37. int
  38. iobuf_accommodate(struct iobuf *iob, size_t count)
  39. {
  40. if (iob->error)
  41. return 0;
  42. size_t esize = iob->size - (iob->skip + iob->off);
  43. if (esize >= count)
  44. return 1;
  45. else if (esize + iob->skip >= count) {
  46. bcopy(iob->buf, iob->buf - iob->skip, iob->off);
  47. iob->buf -= iob->skip;
  48. iob->skip = 0;
  49. return 1;
  50. } else {
  51. uint8_t *nbuf = realloc(iob->buf - iob->skip, iob->size + count);
  52. if (nbuf == NULL) {
  53. iob->error = 1;
  54. return 0;
  55. }
  56. iob->buf = nbuf + iob->skip;
  57. iob->size += count;
  58. return 1;
  59. }
  60. }
  61. int
  62. iobuf_print(struct iobuf *iob, const char *fmt, ...)
  63. {
  64. if (iob->error)
  65. return 0;
  66. int np;
  67. va_list ap;
  68. va_start(ap, fmt);
  69. np = vsnprintf(NULL, 0, fmt, ap);
  70. va_end(ap);
  71. if (!iobuf_accommodate(iob, np + 1))
  72. return 0;
  73. va_start(ap, fmt);
  74. vsnprintf(iob->buf + iob->off, np + 1, fmt, ap);
  75. va_end(ap);
  76. iob->off += np;
  77. return 1;
  78. }
  79. int
  80. iobuf_write(struct iobuf *iob, const void *buf, size_t count)
  81. {
  82. if (iob->error)
  83. return 0;
  84. if (!iobuf_accommodate(iob, count))
  85. return 0;
  86. bcopy(buf, iob->buf + iob->off, count);
  87. iob->off += count;
  88. return 1;
  89. }
  90. void *
  91. iobuf_find(struct iobuf *iob, const void *p, size_t plen)
  92. {
  93. return iob->error ? NULL : memfind(p, plen, iob->buf, iob->off);
  94. }