2 * Copyright (C) 2014, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4 * Released under the GPL v2. (and only v2, not any later version)
13 void fdarray__init(struct fdarray
*fda
, int nr_autogrow
)
17 fda
->nr
= fda
->nr_alloc
= 0;
18 fda
->nr_autogrow
= nr_autogrow
;
21 int fdarray__grow(struct fdarray
*fda
, int nr
)
24 int nr_alloc
= fda
->nr_alloc
+ nr
;
25 size_t psize
= sizeof(fda
->priv
[0]) * nr_alloc
;
26 size_t size
= sizeof(struct pollfd
) * nr_alloc
;
27 struct pollfd
*entries
= realloc(fda
->entries
, size
);
32 priv
= realloc(fda
->priv
, psize
);
38 fda
->nr_alloc
= nr_alloc
;
39 fda
->entries
= entries
;
44 struct fdarray
*fdarray__new(int nr_alloc
, int nr_autogrow
)
46 struct fdarray
*fda
= calloc(1, sizeof(*fda
));
49 if (fdarray__grow(fda
, nr_alloc
)) {
53 fda
->nr_autogrow
= nr_autogrow
;
60 void fdarray__exit(struct fdarray
*fda
)
64 fdarray__init(fda
, 0);
67 void fdarray__delete(struct fdarray
*fda
)
73 int fdarray__add(struct fdarray
*fda
, int fd
, short revents
)
77 if (fda
->nr
== fda
->nr_alloc
&&
78 fdarray__grow(fda
, fda
->nr_autogrow
) < 0)
81 fda
->entries
[fda
->nr
].fd
= fd
;
82 fda
->entries
[fda
->nr
].events
= revents
;
87 int fdarray__filter(struct fdarray
*fda
, short revents
,
88 void (*entry_destructor
)(struct fdarray
*fda
, int fd
, void *arg
),
96 for (fd
= 0; fd
< fda
->nr
; ++fd
) {
97 if (fda
->entries
[fd
].revents
& revents
) {
99 entry_destructor(fda
, fd
, arg
);
105 fda
->entries
[nr
] = fda
->entries
[fd
];
106 fda
->priv
[nr
] = fda
->priv
[fd
];
115 int fdarray__poll(struct fdarray
*fda
, int timeout
)
117 return poll(fda
->entries
, fda
->nr
, timeout
);
120 int fdarray__fprintf(struct fdarray
*fda
, FILE *fp
)
122 int fd
, printed
= fprintf(fp
, "%d [ ", fda
->nr
);
124 for (fd
= 0; fd
< fda
->nr
; ++fd
)
125 printed
+= fprintf(fp
, "%s%d", fd
? ", " : "", fda
->entries
[fd
].fd
);
127 return printed
+ fprintf(fp
, " ]");