precalculate_sizes: don't malloc needlessly

This commit is contained in:
Orestis Floros 2018-08-24 03:02:15 +03:00
parent 7b9318a541
commit ea43507bed
No known key found for this signature in database
GPG Key ID: E9AD9F32E401E38F
1 changed files with 21 additions and 19 deletions

View File

@ -183,26 +183,28 @@ free_params:
} }
static int *precalculate_sizes(Con *con, render_params *p) { static int *precalculate_sizes(Con *con, render_params *p) {
int *sizes = smalloc(p->children * sizeof(int)); if ((con->layout != L_SPLITH && con->layout != L_SPLITV) || p->children <= 0) {
if ((con->layout == L_SPLITH || con->layout == L_SPLITV) && p->children > 0) { return NULL;
assert(!TAILQ_EMPTY(&con->nodes_head)); }
Con *child; int *sizes = smalloc(p->children * sizeof(int));
int i = 0, assigned = 0; assert(!TAILQ_EMPTY(&con->nodes_head));
int total = con_orientation(con) == HORIZ ? p->rect.width : p->rect.height;
TAILQ_FOREACH(child, &(con->nodes_head), nodes) { Con *child;
double percentage = child->percent > 0.0 ? child->percent : 1.0 / p->children; int i = 0, assigned = 0;
assigned += sizes[i++] = lround(percentage * total); int total = con_orientation(con) == HORIZ ? p->rect.width : p->rect.height;
} TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
assert(assigned == total || double percentage = child->percent > 0.0 ? child->percent : 1.0 / p->children;
(assigned > total && assigned - total <= p->children * 2) || assigned += sizes[i++] = lround(percentage * total);
(assigned < total && total - assigned <= p->children * 2)); }
int signal = assigned < total ? 1 : -1; assert(assigned == total ||
while (assigned != total) { (assigned > total && assigned - total <= p->children * 2) ||
for (i = 0; i < p->children && assigned != total; ++i) { (assigned < total && total - assigned <= p->children * 2));
sizes[i] += signal; int signal = assigned < total ? 1 : -1;
assigned += signal; while (assigned != total) {
} for (i = 0; i < p->children && assigned != total; ++i) {
sizes[i] += signal;
assigned += signal;
} }
} }