A clone of btpd with my configuration changes.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

74 lignes
1.5 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->error = 0;
  15. iob->buf = malloc(size);
  16. if (iob->buf == NULL) {
  17. iob->error = ENOMEM;
  18. return ENOMEM;
  19. } else
  20. return 0;
  21. }
  22. int
  23. buf_grow(struct io_buffer *iob, size_t addlen)
  24. {
  25. if (iob->error)
  26. return iob->error;
  27. char *nbuf = realloc(iob->buf, iob->buf_len + addlen);
  28. if (nbuf == NULL) {
  29. iob->error = ENOMEM;
  30. return ENOMEM;
  31. } else {
  32. iob->buf = nbuf;
  33. iob->buf_len += addlen;
  34. return 0;
  35. }
  36. }
  37. int
  38. buf_print(struct io_buffer *iob, const char *fmt, ...)
  39. {
  40. if (iob->error)
  41. return iob->error;
  42. int np;
  43. va_list ap;
  44. va_start(ap, fmt);
  45. np = vsnprintf(NULL, 0, fmt, ap);
  46. va_end(ap);
  47. if (np + 1 > iob->buf_len - iob->buf_off)
  48. if (buf_grow(iob, (1 + (np + 1) / GROWLEN) * GROWLEN) != 0)
  49. return ENOMEM;
  50. va_start(ap, fmt);
  51. vsnprintf(iob->buf + iob->buf_off, np + 1, fmt, ap);
  52. va_end(ap);
  53. iob->buf_off += np;
  54. return 0;
  55. }
  56. int
  57. buf_write(struct io_buffer *iob, const void *buf, size_t len)
  58. {
  59. if (iob->error)
  60. return iob->error;
  61. if (len > iob->buf_len - iob->buf_off)
  62. if (buf_grow(iob, (1 + len / GROWLEN) * GROWLEN) != 0)
  63. return ENOMEM;
  64. bcopy(buf, iob->buf + iob->buf_off, len);
  65. iob->buf_off += len;
  66. return 0;
  67. }