A clone of btpd with my configuration changes.
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.

76 line
1.5 KiB

  1. #include <inttypes.h>
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "iobuf.h"
  7. #define GROWLEN (1 << 14)
  8. struct io_buffer
  9. buf_init(size_t size)
  10. {
  11. struct io_buffer iob;
  12. iob.off = 0;
  13. iob.len = size;
  14. iob.error = (iob.buf = malloc(size)) == NULL ? 1 : 0;
  15. return iob;
  16. }
  17. void
  18. buf_free(struct io_buffer *iob)
  19. {
  20. if (iob->buf != NULL)
  21. free(iob->buf);
  22. }
  23. int
  24. buf_grow(struct io_buffer *iob, size_t addlen)
  25. {
  26. if (iob->error)
  27. return iob->error;
  28. char *nbuf = realloc(iob->buf, iob->len + addlen);
  29. if (nbuf == NULL) {
  30. iob->error = 1;
  31. return 0;
  32. } else {
  33. iob->buf = nbuf;
  34. iob->len += addlen;
  35. return 1;
  36. }
  37. }
  38. int
  39. buf_print(struct io_buffer *iob, const char *fmt, ...)
  40. {
  41. if (iob->error)
  42. return 0;
  43. int np;
  44. va_list ap;
  45. va_start(ap, fmt);
  46. np = vsnprintf(NULL, 0, fmt, ap);
  47. va_end(ap);
  48. if (np + 1 > iob->len - iob->off)
  49. if (!buf_grow(iob, (1 + (np + 1) / GROWLEN) * GROWLEN))
  50. return 0;
  51. va_start(ap, fmt);
  52. vsnprintf(iob->buf + iob->off, np + 1, fmt, ap);
  53. va_end(ap);
  54. iob->off += np;
  55. return 1;
  56. }
  57. int
  58. buf_write(struct io_buffer *iob, const void *buf, size_t len)
  59. {
  60. if (iob->error)
  61. return 0;
  62. if (len > iob->len - iob->off)
  63. if (!buf_grow(iob, (1 + len / GROWLEN) * GROWLEN))
  64. return 0;
  65. bcopy(buf, iob->buf + iob->off, len);
  66. iob->off += len;
  67. return 1;
  68. }