Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
improved performance of contains method in Mojo::Asset::File signific…
…antly
  • Loading branch information
kraih committed Nov 9, 2012
1 parent 7f3b4ab commit b513934
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
2 changes: 2 additions & 0 deletions Changes
@@ -1,5 +1,7 @@

3.56 2012-11-09
- Improved performance of contains method in Mojo::Asset::File
significantly.
- Improved documentation.
- Improved tests.

Expand Down
20 changes: 9 additions & 11 deletions lib/Mojo/Asset/File.pm
Expand Up @@ -65,18 +65,16 @@ sub contains {

# Calculate window
my $end = $self->end_range // $self->size;
my $window_size = length($pattern) * 2;
$window_size = $end - $self->start_range
if $window_size > $end - $self->start_range;
my $read = $handle->sysread(my $window, $window_size);
my $offset = $read;
my $pattern_size = length $pattern;
my $range = $self->end_range;

# Moving window search
my $size = length($pattern) * 2;
$size = $size > 131072 ? $size : 131072;
$size = $end - $self->start_range if $size > $end - $self->start_range;
my $offset = $handle->sysread(my $window, $size);
my $range = $self->end_range;

# Sliding window search
while ($offset <= $end) {
return -1 if defined $range && ($pattern_size = $end + 1 - $offset) <= 0;
$read = $handle->sysread(my $buffer, $pattern_size);
return -1 if defined $range && ($size = $end + 1 - $offset) <= 0;
my $read = $handle->sysread(my $buffer, $size);
$offset += $read;
$window .= $buffer;
my $pos = index $window, $pattern;
Expand Down
16 changes: 16 additions & 0 deletions t/mojo/asset.t
Expand Up @@ -82,6 +82,22 @@ is $chunk, 'defghi', 'chunk from position 1';
$chunk = $mem->get_chunk(5);
is $chunk, 'hi', 'chunk from position 5';

# Huge file asset
$file = Mojo::Asset::File->new;
$file->add_chunk('a' x 131072);
$file->add_chunk('b');
$file->add_chunk('c' x 131072);
is $file->contains(''), 0, 'empty string at position 0';
is $file->contains('a'), 0, '"a" at position 0';
is $file->contains('b'), 131072, '"b" at position 131072';
is $file->contains('c'), 131073, '"c" at position 131073';
is $file->contains('abc'), 131071, '"abc" at position 131071';
is $file->contains('d'), -1, 'does not contain "d"';
is $file->contains('a' x 131072), 0, '"a" x 131072 at position 0';
is $file->contains('c' x 131072), 131073, '"c" x 131072 at position 131073';
is $file->contains('b' . ('c' x 131072)), 131072,
'"b" . ("c" x 131072) at position 131072';

# Move memory asset to file
$mem = Mojo::Asset::Memory->new->add_chunk('abc');
my $tmp = Mojo::Asset::File->new->add_chunk('x');
Expand Down

0 comments on commit b513934

Please sign in to comment.