Permalink
Browse files

delete and replace methods

  • Loading branch information...
1 parent 894a8ac commit c69711cf77e18cf5dfad2518198c7f0ef0c501cc Hakim Cassimally committed May 21, 2011
Showing with 50 additions and 1 deletion.
  1. +38 −1 scratch/perl/text-piecetable/lib/Text/PieceTable.pm
  2. +12 −0 scratch/perl/text-piecetable/t/01-basic.t
@@ -59,9 +59,16 @@ sub from_file {
sub piece_at_pos {
my ($self, $pos) = @_;
+ my @pieces = $self->all_pieces;
+
+ return _piece_at_pos( $pos, \@pieces);
+}
+sub _piece_at_pos {
+ my ($pos, $pieces) = @_;
+
my $i = 0;
my @before;
- my @pieces = $self->all_pieces;
+ my @pieces = @$pieces;
while (my $piece = shift @pieces) {
my $len = $piece->length;
@@ -77,12 +84,42 @@ sub piece_at_pos {
die "Invalid pos $pos";
}
+sub replace {
+ my ($self, $pos, $length, $text) = @_;
+ return $self->delete($pos, $length)->insert($pos, $text);
+}
+
sub insert {
my ($self, $pos, $text) = @_;
my $piece = $self->additional->append($text);
return $self->insert_piece($pos, $piece);
}
+sub delete {
+ my ($self, $pos, $len) = @_;
+
+ my ($piece, $i, $before, $after) =
+ $self->piece_at_pos($pos);
+
+ my ($pre,$post) = $piece->split_at($i);
+ my ($piece2, $j, undef, $after2) =
+ _piece_at_pos($len, [ $post, @$after ]);
+
+ my (undef, $post2) = $piece2->split_at($j);
+
+ my $pieces = [
+ @$before,
+ $pre ? $pre : (),
+ $post2 ? $post2 : (),
+ @$after2,
+ ];
+
+ return $self->new(
+ source => $self->source,
+ additional => $self->additional,
+ pieces => $pieces,
+ );
+}
sub insert_piece {
my ($self, $pos, $insert) = @_;
@@ -17,4 +17,16 @@ is $pt->as_string, 'the quick fox jumps over the lazy dog';
$pt = $pt->insert(10, 'brown ');
is $pt->as_string, 'the quick brown fox jumps over the lazy dog';
+$pt = $pt->delete(34, 5);
+is $pt->as_string, 'the quick brown fox jumps over the dog';
+
+$pt = $pt->delete(0, 10);
+is $pt->as_string, 'brown fox jumps over the dog';
+
+$pt = $pt->replace( 6, 3, 'vixen' );
+is $pt->as_string, 'brown vixen jumps over the dog';
+
+$pt = $pt->delete(0, $pt->length);
+is $pt->as_string, '';
+
done_testing;

0 comments on commit c69711c

Please sign in to comment.