Skip to content

Commit

Permalink
Make .head(*-1)/.head(*-1) on native arrays faster
Browse files Browse the repository at this point in the history
About 4x as fast for both.  This now also returns a native array of
the same type, rather than a Seq.

Also fix an off-by-one in .head(N).
  • Loading branch information
lizmat committed May 21, 2022
1 parent 3c47f1d commit 73b43e5
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/core.c/native_array.pm6
Expand Up @@ -38,16 +38,28 @@ my class array does Iterable does Positional {

multi method head(array:D: Int:D $n) {
my int $end = $n - 1;
nqp::isgt_i($end,nqp::elems(self))
nqp::isge_i($end,nqp::elems(self))
?? nqp::clone(self)
!! nqp::slice(self,0,$end)
}
multi method head(array:D: Callable:D $calculator) {
my int $end = $calculator(nqp::elems(self)) - 1;
nqp::islt_i($end,0)
?? nqp::create(self.WHAT)
!! nqp::slice(self,0,$end)
}
multi method tail(array:D: Int:D $n) {
my int $start = nqp::elems(self) - $n;
nqp::islt_i($start,0)
?? nqp::clone(self)
!! nqp::slice(self,$start,nqp::sub_i(nqp::elems(self),1))
}
multi method tail(array:D: Callable:D $calculator) {
my int $start = $calculator(nqp::elems(self));
nqp::isge_i($start,nqp::elems(self))
?? nqp::create(self.WHAT)
!! nqp::slice(self,$start,nqp::sub_i(nqp::elems(self),1))
}

sub INDEX_OUT_OF_RANGE(Int:D $got --> Nil) {
X::OutOfRange.new(what => "Index", :$got, range => "0..^Inf").throw
Expand Down

0 comments on commit 73b43e5

Please sign in to comment.