Skip to content

Commit

Permalink
Implement Array.cow (for copy-on-write)
Browse files Browse the repository at this point in the history
This is basically just to get it out there and may be revoked at any
time before the next release.

It basically creates a copy of Array with aliases to the values:

  my @A = ^10;
  my @b = @a.cow;   # values are shared
  @b[5] = 42;       # element #5 no longer shared

This as a result of a question at The Perl Conference:
  Can you do "Copy-On-Write" in Perl 6?

I thought this could be useful.
  • Loading branch information
lizmat committed Jun 25, 2016
1 parent 0e4a643 commit da5278a
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/core/Array.pm
Expand Up @@ -40,6 +40,21 @@ my class Array { # declared in BOOTSTRAP
}
}

method cow() {
my int $elems = self.elems; # ensure reification
my $src := nqp::getattr(self,List,'$!reified');
my $cow := nqp::setelems(nqp::list,$elems);
my int $i = -1;

nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
nqp::bindpos($cow,$i,nqp::p6scalarfromdesc($!descriptor) =
nqp::decont(nqp::atpos($src,$i)))
);

nqp::p6bindattrinvres(nqp::create(Array),List,'$!reified',$cow)
}

method iterator(Array:D:) {

# something to iterate over in the future
Expand Down

0 comments on commit da5278a

Please sign in to comment.