_mxml_entity_cb: simplify binary search a bit

The loop invariant is that `last` is at least `first + 2`, which means that neither `entities[first]` nor `entities[last]` are ever accessed, so it's safe to have them outside the array bounds.
Another invariant is that `entities[first].name < name < entities[last].name`, so once `first + 1 == last`, it means there's no occurrence.

Also, `bsearch` could be used, which might be a more straightforward approach.
This commit is contained in:
Ignat Loskutov 2023-02-20 21:49:42 +01:00 committed by GitHub
parent 809204a305
commit d580e927ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -409,8 +409,8 @@ _mxml_entity_cb(const char *name) /* I - Entity name */
* Do a binary search for the named entity...
*/
first = 0;
last = (int)(sizeof(entities) / sizeof(entities[0]) - 1);
first = -1;
last = (int)(sizeof(entities) / sizeof(entities[0]));
while ((last - first) > 1)
{
@ -424,15 +424,5 @@ _mxml_entity_cb(const char *name) /* I - Entity name */
first = current;
}
/*
* If we get here, there is a small chance that there is still
* a match; check first and last...
*/
if (!strcmp(name, entities[first].name))
return (entities[first].val);
else if (!strcmp(name, entities[last].name))
return (entities[last].val);
else
return (-1);
}