ocfs2: fix a tiny case that inode can not removed
[linux/fpc-iii.git] / tools / lib / api / fd / array.c
blob0e636c4339b89887b805413a5bc3509585b9d346
1 /*
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)
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>
13 void fdarray__init(struct fdarray *fda, int nr_autogrow)
15 fda->entries = NULL;
16 fda->priv = NULL;
17 fda->nr = fda->nr_alloc = 0;
18 fda->nr_autogrow = nr_autogrow;
21 int fdarray__grow(struct fdarray *fda, int nr)
23 void *priv;
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);
29 if (entries == NULL)
30 return -ENOMEM;
32 priv = realloc(fda->priv, psize);
33 if (priv == NULL) {
34 free(entries);
35 return -ENOMEM;
38 fda->nr_alloc = nr_alloc;
39 fda->entries = entries;
40 fda->priv = priv;
41 return 0;
44 struct fdarray *fdarray__new(int nr_alloc, int nr_autogrow)
46 struct fdarray *fda = calloc(1, sizeof(*fda));
48 if (fda != NULL) {
49 if (fdarray__grow(fda, nr_alloc)) {
50 free(fda);
51 fda = NULL;
52 } else {
53 fda->nr_autogrow = nr_autogrow;
57 return fda;
60 void fdarray__exit(struct fdarray *fda)
62 free(fda->entries);
63 free(fda->priv);
64 fdarray__init(fda, 0);
67 void fdarray__delete(struct fdarray *fda)
69 fdarray__exit(fda);
70 free(fda);
73 int fdarray__add(struct fdarray *fda, int fd, short revents)
75 int pos = fda->nr;
77 if (fda->nr == fda->nr_alloc &&
78 fdarray__grow(fda, fda->nr_autogrow) < 0)
79 return -ENOMEM;
81 fda->entries[fda->nr].fd = fd;
82 fda->entries[fda->nr].events = revents;
83 fda->nr++;
84 return pos;
87 int fdarray__filter(struct fdarray *fda, short revents,
88 void (*entry_destructor)(struct fdarray *fda, int fd))
90 int fd, nr = 0;
92 if (fda->nr == 0)
93 return 0;
95 for (fd = 0; fd < fda->nr; ++fd) {
96 if (fda->entries[fd].revents & revents) {
97 if (entry_destructor)
98 entry_destructor(fda, fd);
100 continue;
103 if (fd != nr) {
104 fda->entries[nr] = fda->entries[fd];
105 fda->priv[nr] = fda->priv[fd];
108 ++nr;
111 return fda->nr = nr;
114 int fdarray__poll(struct fdarray *fda, int timeout)
116 return poll(fda->entries, fda->nr, timeout);
119 int fdarray__fprintf(struct fdarray *fda, FILE *fp)
121 int fd, printed = fprintf(fp, "%d [ ", fda->nr);
123 for (fd = 0; fd < fda->nr; ++fd)
124 printed += fprintf(fp, "%s%d", fd ? ", " : "", fda->entries[fd].fd);
126 return printed + fprintf(fp, " ]");