[RFC/PATCH v2 3/5] libbb: add ends_with() function
Rich Felker
dalias at libc.org
Fri Aug 21 22:30:11 UTC 2015
On Fri, Aug 21, 2015 at 06:26:27PM +0200, walter harms wrote:
>
>
> Am 21.08.2015 16:23, schrieb Bartosz Golaszewski:
> > This function checks if given key can be found at the end of the string.
> >
> > Signed-off-by: Bartosz Golaszewski <bartekgola at gmail.com>
> > ---
> > include/libbb.h | 1 +
> > libbb/compare_string_array.c | 30 ++++++++++++++++++++++++++++++
> > 2 files changed, 31 insertions(+)
> >
> > diff --git a/include/libbb.h b/include/libbb.h
> > index a56b684..7b41c9b 100644
> > --- a/include/libbb.h
> > +++ b/include/libbb.h
> > @@ -422,6 +422,7 @@ const char *bb_basename(const char *name) FAST_FUNC;
> > char *last_char_is(const char *s, int c) FAST_FUNC;
> > const char* endofname(const char *name) FAST_FUNC;
> > char *is_prefixed_with(const char *string, const char *key) FAST_FUNC;
> > +int ends_with(const char *str, const char *key) FAST_FUNC;
> >
> > int ndelay_on(int fd) FAST_FUNC;
> > int ndelay_off(int fd) FAST_FUNC;
> > diff --git a/libbb/compare_string_array.c b/libbb/compare_string_array.c
> > index e24815a..a2d77c7 100644
> > --- a/libbb/compare_string_array.c
> > +++ b/libbb/compare_string_array.c
> > @@ -23,6 +23,19 @@ char* FAST_FUNC is_prefixed_with(const char *string, const char *key)
> > #endif
> > }
> >
> > +int FAST_FUNC ends_with(const char *str, const char *key)
> > +{
> > + size_t str_len = strlen(str), key_len = strlen(key);
> > +
> > + if (str_len >= key_len) {
> > + if (strcmp(str + str_len - key_len, key) == 0) {
> > + return 1;
> > + }
> > + }
> > +
> > + return 0;
> > +}
> > +
>
> maybe its a bit late but ...
>
> the function name is a bit unfortunate whats about has_suffix() ?
>
> you can improve readability by returning strcmp directly and calculating
> the len immediately.
>
> int has_suffix(const char *str, const char *key)
> {
> size_t len = strlen(str)-strlen(key);
>
> if (len < 0 )
> return -1;
No you can't. len<0 is always false because len is unsigned. The
original code in the patch was correct; your version is buggy.
Rich
More information about the busybox
mailing list