Usually I don't pay much particular attention to how generic or flexible my code is. If it doesn't jump straight into sight as being something obviously reusable, I don't make it reusable. Mainly that's because I don't share the pervasive philosophy of the OOP culture of devising highly abstracted, generic constructs as much as you can. I don't care about building "flexible" code that may help solve a variety of problems I may or may not face in future; I want to solve my own current problem, now, and do it in a simple, clear and efficient manner.
Yet, because my "sight" is rather short -I have the literal proficiency of an imbecile monkey when it comes to programming- some "obvious" things often escape me.
For instance today I found myself writing this:
Code:
static const char *find_duplicate(const char *list, const char *items)
{
const unsigned listlen = (unsigned)strlen(list);
unsigned itemlen;
const char *start = items;
char *delimiter;
if (list == items)
{ while (*items)
{ delimiter = strchrnul(items, ',');
itemlen = (unsigned)(delimiter - items);
if ((items = text_contains(delimiter, listlen - (unsigned)(delimiter - start), items, itemlen) ) )
return (items);
items = delimiter + !!*delimiter;
}
}
else
{ while (*items)
{ delimiter = strchrnul(items, ',');
itemlen = (unsigned)(delimiter - items);
if ((items = text_contains(list, listlen, items, itemlen) ) ) //memmem wrapper with additional code to ensure exact rather than partial matches.
return (items);
items = delimiter + !!*delimiter;
}
}
return ((void*)0);
}
Later today, I found I needed to do the opposite: find the first differing, i.e non-duplicate, item of two strings. Which led me to revisit this code, and wonder if there is a good way to 1. merge both loops into one,in order to eliminate the awfully redundant code and 2. alter the function to instead, return the first non-duplicate item.
I came up with this untested solution but I'm not thrilled about it. I wonder what cool alternatives the great minds that roam these forums may come up with.
Code:
static const char *find_item
(const char *list, const char *items, const _Bool find_duplicate)
{
const unsigned listlen = (unsigned)strlen(list);
unsigned itemlen;
const char *start = items;
char *delimiter;
while (*items)
{ delimiter = strchrnul(items, ',');
itemlen = (unsigned)(delimiter - items);
if (list == start)
items = text_contains(delimiter, listlen - (unsigned)(delimiter - start), items, itemlen);
else
items = text_contains(list, listlen, items, itemlen); //memmem wrapper with additional code to ensure exact rather than partial matches.
if ((find_duplicate && items) || (!find_duplicate && !items) )
return (items);
items = delimiter + !!*delimiter;
}
return ((void*)0);
}