A clone of btpd with my configuration changes.
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.3 KiB

  1. #include <errno.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. #define GROWLEN (1 << 14)
  9. int
  10. buf_init(struct io_buffer *iob, size_t size)
  11. {
  12. iob->buf_off = 0;
  13. iob->buf_len = size;
  14. iob->buf = malloc(size);
  15. if (iob->buf == NULL)
  16. return ENOMEM;
  17. else
  18. return 0;
  19. }
  20. int
  21. buf_grow(struct io_buffer *iob, size_t addlen)
  22. {
  23. char *nbuf = realloc(iob->buf, iob->buf_len + addlen);
  24. if (nbuf == NULL)
  25. return ENOMEM;
  26. else {
  27. iob->buf = nbuf;
  28. iob->buf_len += addlen;
  29. return 0;
  30. }
  31. }
  32. int
  33. buf_print(struct io_buffer *iob, const char *fmt, ...)
  34. {
  35. int np;
  36. va_list ap;
  37. va_start(ap, fmt);
  38. np = vsnprintf(NULL, 0, fmt, ap);
  39. va_end(ap);
  40. while (np + 1 > iob->buf_len - iob->buf_off)
  41. if (buf_grow(iob, GROWLEN) != 0)
  42. return ENOMEM;
  43. va_start(ap, fmt);
  44. vsnprintf(iob->buf + iob->buf_off, np + 1, fmt, ap);
  45. va_end(ap);
  46. iob->buf_off += np;
  47. return 0;
  48. }
  49. int
  50. buf_write(struct io_buffer *iob, const void *buf, size_t len)
  51. {
  52. while (iob->buf_len - iob->buf_off < len)
  53. if (buf_grow(iob, GROWLEN) != 0)
  54. return ENOMEM;
  55. bcopy(buf, iob->buf + iob->buf_off, len);
  56. iob->buf_off += len;
  57. return 0;
  58. }