sr: session: Use realloc to resize source array

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 <lars@metafoo.de>
This commit is contained in:
Lars-Peter Clausen 2012-06-30 20:54:42 +02:00 committed by Uwe Hermann
parent 45c59c8bdd
commit 2bccd322bc
1 changed files with 19 additions and 24 deletions

View File

@ -505,18 +505,12 @@ SR_API int sr_session_source_add(int fd, int events, int timeout,
/* 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 (sources) {
memcpy(new_sources, sources,
sizeof(struct source) * num_sources);
g_free(sources);
}
s = &new_sources[num_sources++];
s->fd = fd;
s->events = events;
@ -553,28 +547,29 @@ SR_API int sr_session_source_remove(int fd)
return SR_ERR_BUG;
}
/* TODO: Check if 'fd' valid. */
for (old = 0; old < num_sources; old++) {
if (sources[old].fd == fd)
break;
}
new_sources = g_try_malloc0(sizeof(struct source) * num_sources);
if (!new_sources) {
/* 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));
}
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;
}
for (old = 0, new = 0; old < num_sources; old++) {
if (sources[old].fd != fd)
memcpy(&new_sources[new++], &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);
}
return SR_OK;
}