Re: [RFC][PATCH] string.h: Add strncmp_prefix() helper macro

From: Steven Rostedt
Date: Wed Dec 19 2018 - 20:43:51 EST


[ Sending now as myself and not my daughter :-p ]

On Wed, Dec 19, 2018 at 01:54:57PM -0800, Joe Perches wrote:
> On Wed, 2018-12-19 at 16:32 -0500, Bryana Rostedt wrote:
> >
> > +/*
> > + * A common way to test a prefix of a string is to do:
> > + * strncmp(str, prefix, sizeof(prefix) - 1)
> > + *
> > + * But this can lead to bugs due to typos, or if prefix is a pointer
> > + * and not a constant. Instead use strncmp_prefix().
> > + */
> > +#define strncmp_prefix(str, prefix) \e
> > + ({ \
> > + int ____strcmp_prefix_ret____; \
> > + char *____strcmp_prefix____ = prefix; \
>
> This creates a warning and discards any const from prefix when used like
>
> static const char foo[] = "bar";
>
> strncmp_prefix(str, foo);
>
> > + if (__builtin_constant_p(&prefix)) \
> > + ____strcmp_prefix_ret____ = \
> > + strncmp(str, prefix, sizeof(prefix) - 1); \
> > + else \
> > + ____strcmp_prefix_ret____ = \
> > + strncmp(str, ____strcmp_prefix____, \
> > + strlen(____strcmp_prefix____)); \
> > + ____strcmp_prefix_ret____; \
> > + })
> > +
>
> Perhaps
>
> #define strncmp_prefix(str, prefix) \
> ({ \
> typeof(prefix) p = (prefix); \
> strncmp(str, p, strlen(p)); \


I'll have to see how all supported gcc optimizes that.

I could just move the prefix assignment in the else part, which gets compiled
out on constants anyway, just to be safe, and also shows exactly what is
happening and not worrying about gcc doing the "right" thing.

-- Steve


> })
>