1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
|
package RecvUntil;
use strict;
use warnings;
sub recv_until {
my ($pat) = @_;
my $len = length $pat;
my @backtracks;
for (my $i = 1; $i <= $len - 1; $i++) {
my $matched_prefix_len = 1;
while ($matched_prefix_len <= $len - $i - 1) {
#while (1) {
#my $left = $len - $i;
#warn "left: $i: $len: ", $len - 1 - $i, "\n";
#warn "matched_prefix_len: $matched_prefix_len\n";
#while (1) {
my $prefix = substr($pat, 0, $matched_prefix_len);
my $next = substr($pat, $matched_prefix_len, 1);
my $prefix2 = substr($pat, $i, $matched_prefix_len);
my $next2 = substr($pat, $i + $matched_prefix_len, 1);
#warn "$i: global prefix $prefix $next\n";
#warn "$i: local prefix $prefix2 $next2\n";
if ($prefix2 eq $prefix) {
if ($next2 eq $next) {
$matched_prefix_len++;
next;
}
#warn "$matched_prefix_len: $prefix: found match at $i (next $next, next2 $next2)\n";
my $cur_state = $i + $matched_prefix_len;
my $new_state = $matched_prefix_len + 1;
my $matched = substr($pat, 0, $cur_state);
my $chain = $backtracks[$cur_state - 2];
if (!$chain) {
$chain = [];
$backtracks[$cur_state - 2] = $chain;
}
my $found = 0;
for my $rec (@$chain) {
if ($rec->{char} eq $next) {
$found = 1;
if ($rec->{new_state} < $new_state) {
warn "overriding...\n";
$rec->{new_state} = $new_state;
}
}
}
if (!$found) {
warn "on state $cur_state ($matched), if next is '$next', ",
"then backtrack to state $new_state ($prefix$next)\n";
push @$chain, { char => $next, new_state => $new_state };
}
#if ($matched_prefix_len > 1) {
#$i += $matched_prefix_len - 1;
#}
last;
}
last;
}
}
return sub {
my ($txt) = @_;
my $max_state = length $pat;
my $len = length $txt;
my $state = 0;
my $ret = '';
for (my $i = 0; $i < $len; $i++) {
# read the char
my $c = substr($txt, $i, 1);
#warn "$state: read char at $i: $c\n";
#warn "matched: $ret\n";
my $expected = substr($pat, $state, 1);
if ($expected eq $c) {
#warn "matched the char in pattern.\n";
$state++;
if ($state == $max_state) {
last;
}
next;
}
if ($state == 0) {
#warn "did not match the first char in pattern\n";
$ret .= $c;
next;
}
my $old_state;
my $matched;
my $chain = $backtracks[$state - 2];
for my $rec (@$chain) {
if ($rec->{char} eq $c) {
$old_state = $state;
$state = $rec->{new_state};
#warn "matched the char for backtracking to state $state\n";
$matched = 1;
last;
}
}
if (!$matched) {
$ret .= substr($pat, 0, $state);
$state = 0;
redo;
}
$ret .= substr($pat, 0, $old_state + 1 - $state);
next;
}
return $ret;
};
}
1;
|