array.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (C) 2014, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
  3. *
  4. * Released under the GPL v2. (and only v2, not any later version)
  5. */
  6. #include "array.h"
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <poll.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12. void fdarray__init(struct fdarray *fda, int nr_autogrow)
  13. {
  14. fda->entries = NULL;
  15. fda->nr = fda->nr_alloc = 0;
  16. fda->nr_autogrow = nr_autogrow;
  17. }
  18. int fdarray__grow(struct fdarray *fda, int nr)
  19. {
  20. int nr_alloc = fda->nr_alloc + nr;
  21. size_t size = sizeof(struct pollfd) * nr_alloc;
  22. struct pollfd *entries = realloc(fda->entries, size);
  23. if (entries == NULL)
  24. return -ENOMEM;
  25. fda->nr_alloc = nr_alloc;
  26. fda->entries = entries;
  27. return 0;
  28. }
  29. struct fdarray *fdarray__new(int nr_alloc, int nr_autogrow)
  30. {
  31. struct fdarray *fda = calloc(1, sizeof(*fda));
  32. if (fda != NULL) {
  33. if (fdarray__grow(fda, nr_alloc)) {
  34. free(fda);
  35. fda = NULL;
  36. } else {
  37. fda->nr_autogrow = nr_autogrow;
  38. }
  39. }
  40. return fda;
  41. }
  42. void fdarray__exit(struct fdarray *fda)
  43. {
  44. free(fda->entries);
  45. fdarray__init(fda, 0);
  46. }
  47. void fdarray__delete(struct fdarray *fda)
  48. {
  49. fdarray__exit(fda);
  50. free(fda);
  51. }
  52. int fdarray__add(struct fdarray *fda, int fd, short revents)
  53. {
  54. if (fda->nr == fda->nr_alloc &&
  55. fdarray__grow(fda, fda->nr_autogrow) < 0)
  56. return -ENOMEM;
  57. fda->entries[fda->nr].fd = fd;
  58. fda->entries[fda->nr].events = revents;
  59. fda->nr++;
  60. return 0;
  61. }
  62. int fdarray__filter(struct fdarray *fda, short revents)
  63. {
  64. int fd, nr = 0;
  65. if (fda->nr == 0)
  66. return 0;
  67. for (fd = 0; fd < fda->nr; ++fd) {
  68. if (fda->entries[fd].revents & revents)
  69. continue;
  70. if (fd != nr)
  71. fda->entries[nr] = fda->entries[fd];
  72. ++nr;
  73. }
  74. return fda->nr = nr;
  75. }
  76. int fdarray__poll(struct fdarray *fda, int timeout)
  77. {
  78. return poll(fda->entries, fda->nr, timeout);
  79. }
  80. int fdarray__fprintf(struct fdarray *fda, FILE *fp)
  81. {
  82. int fd, printed = fprintf(fp, "%d [ ", fda->nr);
  83. for (fd = 0; fd < fda->nr; ++fd)
  84. printed += fprintf(fp, "%s%d", fd ? ", " : "", fda->entries[fd].fd);
  85. return printed + fprintf(fp, " ]");
  86. }