Re: [PATCH] Refactor "if(strspn(str, ...) == strlen(str)" code

From: Geoff Winkless <pgsqladmin(at)geoff(dot)dj>
To: Aleksander Alekseev <a(dot)alekseev(at)postgrespro(dot)ru>
Cc: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: [PATCH] Refactor "if(strspn(str, ...) == strlen(str)" code
Date: 2016-12-08 16:10:26
Message-ID: CAEzk6ffaryoC=REYR=9fyGq9WEN-bqyDfzzVrY1xzeyZT5o2LA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 8 December 2016 at 15:54, Aleksander Alekseev
<a(dot)alekseev(at)postgrespro(dot)ru> wrote:
> Hi.
>
> I noticed that there is a lot of repeating code like this:
>
> ```
> if (strspn(str, " \t\n\r\f") == strlen(str))
> ```
>
> I personally don't find it particularly readable, not mentioning that
> traversing a string twice doesn't look as a good idea (you can check
> using objdump that latest GCC 6.2 doesn't optimize this code).

You could just change it to

if (str[strspn(str, " \t\n\r\f")] == '\0')

to mitigate calling strlen. It's safe to do so because strspn will
only return values from 0 to strlen(str).

Geoff

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Asif Naeem 2016-12-08 16:11:42 Re: pgcrypto compilation error due to stack-allocated EVP_CIPHER_CTX
Previous Message Heikki Linnakangas 2016-12-08 16:04:37 Re: Use EVP API pgcrypto encryption, dropping support for OpenSSL 0.9.6 and older