Skip to content

Commit cfcaa00

Browse files
committed
Remove polynomial time complexity in autolink extension
Cache the value computed by cmark_inline_parser_in_bracket so that it runs in O(1) time rather than O(n). This patch was contributed by @kevinbackhouse
1 parent 0578e1e commit cfcaa00

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/inlines.c

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ typedef struct bracket {
4141
bool image;
4242
bool active;
4343
bool bracket_after;
44+
bool in_bracket_image0;
45+
bool in_bracket_image1;
4446
} bracket;
4547

4648
typedef struct subject{
@@ -516,6 +518,8 @@ static void push_bracket(subject *subj, bool image, cmark_node *inl_text) {
516518
bracket *b = (bracket *)subj->mem->calloc(1, sizeof(bracket));
517519
if (subj->last_bracket != NULL) {
518520
subj->last_bracket->bracket_after = true;
521+
b->in_bracket_image0 = subj->last_bracket->in_bracket_image0;
522+
b->in_bracket_image1 = subj->last_bracket->in_bracket_image1;
519523
}
520524
b->image = image;
521525
b->active = true;
@@ -524,6 +528,11 @@ static void push_bracket(subject *subj, bool image, cmark_node *inl_text) {
524528
b->previous_delimiter = subj->last_delim;
525529
b->position = subj->pos;
526530
b->bracket_after = false;
531+
if (image) {
532+
b->in_bracket_image1 = true;
533+
} else {
534+
b->in_bracket_image0 = true;
535+
}
527536
subj->last_bracket = b;
528537
}
529538

@@ -1254,6 +1263,17 @@ static cmark_node *handle_close_bracket(cmark_parser *parser, subject *subj) {
12541263
}
12551264
opener = opener->previous;
12561265
}
1266+
bool in_bracket_image1 = false;
1267+
if (opener) {
1268+
in_bracket_image1 = opener->in_bracket_image1;
1269+
}
1270+
bracket *opener2 = subj->last_bracket;
1271+
while (opener2 != opener) {
1272+
if (opener2->image) {
1273+
opener2->in_bracket_image1 = in_bracket_image1;
1274+
}
1275+
opener2 = opener2->previous;
1276+
}
12571277
}
12581278

12591279
return NULL;
@@ -1662,10 +1682,15 @@ cmark_chunk *cmark_inline_parser_get_chunk(cmark_inline_parser *parser) {
16621682
}
16631683

16641684
int cmark_inline_parser_in_bracket(cmark_inline_parser *parser, int image) {
1665-
for (bracket *b = parser->last_bracket; b; b = b->previous)
1666-
if (b->active && b->image == (image != 0))
1667-
return 1;
1668-
return 0;
1685+
bracket *b = parser->last_bracket;
1686+
if (!b) {
1687+
return 0;
1688+
}
1689+
if (image != 0) {
1690+
return b->in_bracket_image1;
1691+
} else {
1692+
return b->in_bracket_image0;
1693+
}
16691694
}
16701695

16711696
void cmark_node_unput(cmark_node *node, int n) {

0 commit comments

Comments
 (0)