Skip to content

Commit a060b21

Browse files
committedFeb 23, 2024
Refactor pm_node_list_insert to use a binary search
·
v1.4.0v0.25.0
1 parent 865b0d5 commit a060b21

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed
 

‎src/static_literals.c

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,32 @@
66
*/
77
static pm_node_t *
88
pm_node_list_insert(const pm_parser_t *parser, pm_node_list_t *list, pm_node_t *node, int (*compare)(const pm_parser_t *parser, const pm_node_t *left, const pm_node_t *right)) {
9-
// TODO: This would be much more efficient with a binary search.
10-
size_t index = 0;
11-
while (index < list->size) {
12-
int result = compare(parser, list->nodes[index], node);
9+
size_t low = 0;
10+
size_t high = list->size;
1311

14-
// If we find a match, then replace the node and return the old one.
12+
while (low < high) {
13+
size_t mid = (low + high) / 2;
14+
int result = compare(parser, list->nodes[mid], node);
15+
16+
// If we find a match, then replace the old node with the new one and
17+
// return the old one.
1518
if (result == 0) {
16-
pm_node_t *result = list->nodes[index];
17-
list->nodes[index] = node;
19+
pm_node_t *result = list->nodes[mid];
20+
list->nodes[mid] = node;
1821
return result;
1922
}
2023

21-
if (result > 0) break;
22-
index++;
24+
if (result < 0) {
25+
low = mid + 1;
26+
} else {
27+
high = mid;
28+
}
2329
}
2430

2531
pm_node_list_grow(list);
26-
memmove(&list->nodes[index + 1], &list->nodes[index], (list->size - index) * sizeof(pm_node_t *));
32+
memmove(&list->nodes[low + 1], &list->nodes[low], (list->size - low) * sizeof(pm_node_t *));
2733

28-
list->nodes[index] = node;
34+
list->nodes[low] = node;
2935
list->size++;
3036

3137
return NULL;

0 commit comments

Comments
 (0)
Please sign in to comment.