Skip to content

Instantly share code, notes, and snippets.

@japhb
Created October 28, 2011 07:58
Show Gist options
  • Save japhb/1321836 to your computer and use it in GitHub Desktop.
Save japhb/1321836 to your computer and use it in GitHub Desktop.
Three variants of RANGEPOS() from Rakudo's src/core/Str.pm
# Three versions of the sub: the original, a native-types and nqp-heavy version that
# should run faster, and a native-types but nqp-light version that is easier to read.
# Anyone have more improvements to either of the latter two?
# ORIGINAL
my sub RANGEPOS($str) {
my $pos = $str.chars;
while $pos > 0 {
$pos--;
my str $ch = nqp::substr(nqp::unbox_s($str), nqp::unbox_i($pos), 1);
if nqp::isge_i(nqp::index(nqp::unbox_s($RANGECHAR), $ch, 0), 0) {
my $end = $pos;
while $pos > 0 {
$pos--;
$ch = nqp::substr(nqp::unbox_s($str), nqp::unbox_i($pos), 1);
last if nqp::iseq_s($ch, '.');
return ($pos+1, $end)
unless nqp::isge_i(nqp::index(nqp::unbox_s($RANGECHAR), $ch, 0), 0);
}
return ($pos, $end) unless nqp::iseq_s($ch, '.');
}
}
return (0, -1);
}
# FASTER
my sub RANGEPOS(str $str) {
my int $pos = nqp::chars($str);
my str $rangechar = nqp::unbox_s($RANGECHAR);
while nqp::isgt_i($pos, 0) {
$pos = $pos - 1;
my str $ch = nqp::substr($str, $pos, 1);
if nqp::isge_i(nqp::index($rangechar, $ch, 0), 0) {
my int $end = $pos;
while nqp::isgt_i($pos, 0) {
$pos = $pos - 1;
$ch = nqp::substr($str, $pos, 1);
last if nqp::iseq_s($ch, '.');
return (p6box_i($pos + 1), p6box_i($end))
unless nqp::isge_i(nqp::index($rangechar, $ch, 0), 0);
}
return (p6box_i($pos), p6box_i($end)) unless nqp::iseq_s($ch, '.');
}
}
return (0, -1);
}
# CLEANER
my sub RANGEPOS(str $str) {
my int $pos = nqp::chars($str);
my str $rangechar = nqp::unbox_s($RANGECHAR);
while $pos > 0 {
$pos = $pos - 1;
my str $ch = nqp::substr($str, $pos, 1);
if nqp::index($rangechar, $ch, 0) >= 0 {
my int $end = $pos;
while $pos > 0 {
$pos = $pos - 1;
$ch = nqp::substr($str, $pos, 1);
last if $ch eq '.';
return (p6box_i($pos + 1), p6box_i($end))
unless nqp::index($rangechar, $ch, 0) >= 0;
}
return (p6box_i($pos), p6box_i($end)) unless $ch eq '.';
}
}
return (0, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment