1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2014, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
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 memset(&entries
[fda
->nr_alloc
], 0, sizeof(struct pollfd
) * nr
);
39 memset(&priv
[fda
->nr_alloc
], 0, sizeof(fda
->priv
[0]) * nr
);
41 fda
->nr_alloc
= nr_alloc
;
42 fda
->entries
= entries
;
47 struct fdarray
*fdarray__new(int nr_alloc
, int nr_autogrow
)
49 struct fdarray
*fda
= calloc(1, sizeof(*fda
));
52 if (fdarray__grow(fda
, nr_alloc
)) {
56 fda
->nr_autogrow
= nr_autogrow
;
63 void fdarray__exit(struct fdarray
*fda
)
67 fdarray__init(fda
, 0);
70 void fdarray__delete(struct fdarray
*fda
)
76 int fdarray__add(struct fdarray
*fda
, int fd
, short revents
, enum fdarray_flags flags
)
80 if (fda
->nr
== fda
->nr_alloc
&&
81 fdarray__grow(fda
, fda
->nr_autogrow
) < 0)
84 fda
->entries
[fda
->nr
].fd
= fd
;
85 fda
->entries
[fda
->nr
].events
= revents
;
86 fda
->priv
[fda
->nr
].flags
= flags
;
91 int fdarray__dup_entry_from(struct fdarray
*fda
, int pos
, struct fdarray
*from
)
99 entry
= &from
->entries
[pos
];
101 npos
= fdarray__add(fda
, entry
->fd
, entry
->events
, from
->priv
[pos
].flags
);
103 fda
->priv
[npos
] = from
->priv
[pos
];
108 int fdarray__filter(struct fdarray
*fda
, short revents
,
109 void (*entry_destructor
)(struct fdarray
*fda
, int fd
, void *arg
),
117 for (fd
= 0; fd
< fda
->nr
; ++fd
) {
118 if (!fda
->entries
[fd
].events
)
121 if (fda
->entries
[fd
].revents
& revents
) {
122 if (entry_destructor
)
123 entry_destructor(fda
, fd
, arg
);
125 fda
->entries
[fd
].revents
= fda
->entries
[fd
].events
= 0;
129 if (!(fda
->priv
[fd
].flags
& fdarray_flag__nonfilterable
))
136 int fdarray__poll(struct fdarray
*fda
, int timeout
)
138 return poll(fda
->entries
, fda
->nr
, timeout
);
141 int fdarray__fprintf(struct fdarray
*fda
, FILE *fp
)
143 int fd
, printed
= fprintf(fp
, "%d [ ", fda
->nr
);
145 for (fd
= 0; fd
< fda
->nr
; ++fd
)
146 printed
+= fprintf(fp
, "%s%d", fd
? ", " : "", fda
->entries
[fd
].fd
);
148 return printed
+ fprintf(fp
, " ]");