From d274092131e0e8efa8a8e713ad19e25ed56636a1 Mon Sep 17 00:00:00 2001 From: Tim Wiederhake Date: Mon, 1 Feb 2021 12:27:47 +0100 Subject: [PATCH] commandhelper: Simplify envsort This saves two invocations of each `strndup` and `free`. Signed-off-by: Tim Wiederhake Reviewed-by: Peter Krempa --- tests/commandhelper.c | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/tests/commandhelper.c b/tests/commandhelper.c index 2b937979c0..22835302b8 100644 --- a/tests/commandhelper.c +++ b/tests/commandhelper.c @@ -37,24 +37,19 @@ extern char **environ; static int envsort(const void *a, const void *b) { - const char *const*astrptr = a; - const char *const*bstrptr = b; - const char *astr = *astrptr; - const char *bstr = *bstrptr; - char *aeq = strchr(astr, '='); - char *beq = strchr(bstr, '='); - char *akey; - char *bkey; - int ret; + const char *astr = *(const char**)a; + const char *bstr = *(const char**)b; - if (!(akey = strndup(astr, aeq - astr))) - abort(); - if (!(bkey = strndup(bstr, beq - bstr))) - abort(); - ret = strcmp(akey, bkey); - free(akey); - free(bkey); - return ret; + while (true) { + char achar = (*astr == '=') ? '\0' : *astr; + char bchar = (*bstr == '=') ? '\0' : *bstr; + + if ((achar == '\0') || (achar != bchar)) + return achar - bchar; + + astr++; + bstr++; + } } int main(int argc, char **argv) {