Skip to content

Commit

Permalink
Reduce number of calls to pcre2_substitute
Browse files Browse the repository at this point in the history
  • Loading branch information
ltrzesniewski committed Oct 6, 2024
1 parent 125468b commit a30e675
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
9 changes: 7 additions & 2 deletions src/PCRE.NET.Native/pcrenet_substitute.c
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ typedef struct
replay_queue callout_queue;
} substitute_callout_data;

static size_t max_size(const size_t a, const size_t b)
{
return a > b ? a : b;
}

static void replay_queue_init(replay_queue* queue)
{
queue->buffer = NULL;
Expand Down Expand Up @@ -83,7 +88,7 @@ static void replay_queue_try_enqueue(replay_queue* queue, uint8_t result)

if (queue->count == queue->buffer_size)
{
const size_t new_size = max(64, 2 * queue->buffer_size);
const size_t new_size = max_size(64, 2 * queue->buffer_size);
uint8_t* new_buf = realloc(queue->buffer, new_size * sizeof(uint8_t));
if (!new_buf)
return;
Expand Down Expand Up @@ -279,7 +284,7 @@ static void substitute_with_callout(const pcrenet_substitute_input* input,
// Output buffer is too small
if (result->result_code == PCRE2_ERROR_NOMEMORY)
{
buffer_length *= 2;
buffer_length = max_size(2 * buffer_length, 2 * (size_t)input->subject_length);

if (!result->output_on_heap)
{
Expand Down
6 changes: 3 additions & 3 deletions src/PCRE.NET.Tests/PcreNet/SubstituteTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ public void should_execute_each_callout_once()

var execCount = 0;

var result = re.InternalRegex.Substitute(str.AsSpan(), null, "#".AsSpan(), PcreMatchSettings.Default, 0, (uint)PcreSubstituteOptions.SubstituteGlobal, data =>
var result = re.InternalRegex.Substitute(str.AsSpan(), null, "#:#:#:#".AsSpan(), PcreMatchSettings.Default, 0, (uint)PcreSubstituteOptions.SubstituteGlobal, data =>
{
++execCount;
Assert.That(data.SubstitutionCount, Is.EqualTo(execCount));
Expand All @@ -274,8 +274,8 @@ public void should_execute_each_callout_once()
}, out var substituteCallCount);

Assert.That(execCount, Is.EqualTo(str.Length));
Assert.That(result, Is.EqualTo(str.Replace("aaa", "aa#")));
Assert.That(substituteCallCount, Is.EqualTo(6));
Assert.That(result, Is.EqualTo(str.Replace("aaa", "aa#:#:#:#")));
Assert.That(substituteCallCount, Is.EqualTo(3));
}

[Test]
Expand Down

0 comments on commit a30e675

Please sign in to comment.