From 3ff476e9efd44fac747cc1049ecef486519a1554 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Wed, 30 Mar 2022 10:02:56 +0200 Subject: [PATCH] MINOR: tools: add strordered() to check whether strings are ordered When trying to sort sets of strings, it's often needed to required to compare 3 strings to see if the chosen one fits well between the two others. That's what this function does, in addition to being able to ignore extremities when they're NULL (typically for the first iteration for example). --- include/haproxy/tools.h | 2 ++ src/tools.c | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/include/haproxy/tools.h b/include/haproxy/tools.h index 1a1751597..6e3848f49 100644 --- a/include/haproxy/tools.h +++ b/include/haproxy/tools.h @@ -915,6 +915,8 @@ void calltrace(char *fmt, ...); /* same as strstr() but case-insensitive */ const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2); +int strordered(const char *s1, const char *s2, const char *s3); + /* after increasing a pointer value, it can exceed the first buffer * size. This function transform the value of according with * the expected position. is an array of the one or two diff --git a/src/tools.c b/src/tools.c index 34f86321c..5d5e1b02d 100644 --- a/src/tools.c +++ b/src/tools.c @@ -4363,6 +4363,15 @@ const char *strnistr(const char *str1, int len_str1, const char *str2, int len_s return NULL; } +/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and + * in this case only non-null strings are compared. This allows to pass initial + * values in iterators and in sort functions. + */ +int strordered(const char *s1, const char *s2, const char *s3) +{ + return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0); +} + /* This function read the next valid utf8 char. * is the byte srray to be decode, is its length. * The function returns decoded char encoded like this: