Use realloc to resize the source array when adding or removing a source. This
makes the code a bit smaller. In the remove function we now check whether the fd
is valid before doing anything else and if it is not simply do nothing. If it is
valid use memove to move the elements following the source one element down in
the array. Only after that has been done the array is re-allocated.
Signed-off-by: Lars-Peter Clausen <redacted>
/* Note: cb_data can be NULL, that's not a bug. */
/* Note: cb_data can be NULL, that's not a bug. */
- new_sources = g_try_malloc0(sizeof(struct source) * (num_sources + 1));
+ new_sources = g_try_realloc(sources, sizeof(struct source) * (num_sources + 1));
if (!new_sources) {
sr_err("session: %s: new_sources malloc failed", __func__);
return SR_ERR_MALLOC;
}
if (!new_sources) {
sr_err("session: %s: new_sources malloc failed", __func__);
return SR_ERR_MALLOC;
}
- if (sources) {
- memcpy(new_sources, sources,
- sizeof(struct source) * num_sources);
- g_free(sources);
- }
-
s = &new_sources[num_sources++];
s->fd = fd;
s->events = events;
s = &new_sources[num_sources++];
s->fd = fd;
s->events = events;
- /* TODO: Check if 'fd' valid. */
-
- new_sources = g_try_malloc0(sizeof(struct source) * num_sources);
- if (!new_sources) {
- sr_err("session: %s: new_sources malloc failed", __func__);
- return SR_ERR_MALLOC;
+ for (old = 0; old < num_sources; old++) {
+ if (sources[old].fd == fd)
+ break;
- for (old = 0, new = 0; old < num_sources; old++) {
- if (sources[old].fd != fd)
- memcpy(&new_sources[new++], &sources[old],
- sizeof(struct source));
+ /* fd not found, nothing to do */
+ if (old == num_sources)
+ return SR_OK;
+
+ num_sources -= 1;
+
+ if (old != num_sources) {
+ memmove(&sources[old], &sources[old+1],
+ (num_sources - old) * sizeof(struct source));
- if (old != new) {
- g_free(sources);
- sources = new_sources;
- num_sources--;
- } else {
- /* Target fd was not found. */
- g_free(new_sources);
+ new_sources = g_try_realloc(sources, sizeof(struct source) * (num_sources - 1));
+ if (!new_sources && num_sources > 0) {
+ sr_err("session: %s: new_sources malloc failed", __func__);
+ return SR_ERR_MALLOC;
+ sources = new_sources;
+