Simplify calling of rsindex() and strsearch()

Remove the 'how' parameter to rsindex(), making it reverse-search for only the first matching character,
as sindex() already does.  There are only two callers, and one already passed a hardcoded value of 1.

Also change rsindex() so that it starts searching at the character BEFORE the passed in position.  This
makes it easier to repeatedly call rsindex() in a loop to search for the Nth matching character, and
also fixes a technical instance of undefined behaviour where a pointer is decremented to point before
the start of the string.

Remove the 'mark' parameter to strsearch().  Instead, always forward-search from the beginning of the
string and reverse-search from the end of the string, as this is what the two callers want anyway.

Bump the module ABI version because these functions are exported to modules.
This commit is contained in:
Kevin Easton
2017-11-23 17:22:38 +11:00
parent de303ba554
commit ba1b9742ec
7 changed files with 36 additions and 49 deletions

View File

@@ -1117,41 +1117,32 @@ char *BX_sindex(const char *string, const char *group)
/* rsindex()
*
* Returns a pointer to the howmany'th last matching character in a string, or
* NULL if there are less than howmany matching characters. Returns NULL
* if howmany is zero.
* Returns a pointer to the last matching character that appears in a string BEFORE the
* initial search point (to search the entire string, set the initial search point to
* the terminating NUL). Returns NULL if no matching characters are found.
*
* The string to be searched starts at 'start' and the initial search point is 'ptr'.
*
* A matching character is any character in 'group', unless the first character of 'group'
* is a ^, in which case a matching character is any character NOT in 'group'.
*/
char *BX_rsindex(const char *string, const char *start, const char *group, int howmany)
char *BX_rsindex(const char *ptr, const char *start, const char *group)
{
const char *ptr;
if (howmany && string && start && group && start <= string)
if (ptr && start && group && start <= ptr)
{
int invert = 0;
if (*group == '^')
{
group++;
for (ptr = string; (ptr >= start) && howmany; ptr--)
{
if (!strchr(group, *ptr))
{
if (--howmany == 0)
return (char *)ptr;
}
}
invert = 1;
}
else
while (ptr > start)
{
for (ptr = string; (ptr >= start) && howmany; ptr--)
{
if (strchr(group, *ptr))
{
if (--howmany == 0)
return (char *)ptr;
}
}
ptr--;
if (invert == !strchr(group, *ptr))
return (char *)ptr;
}
}
return NULL;