Skip to content

Commit

Permalink
[codestring]: Add 'lineof' method for finding line numbers.
Browse files Browse the repository at this point in the history
git-svn-id: https://svn.parrot.org/parrot/trunk@37937 d31e2699-5ff4-0310-a27c-f18f2fbe73fe
  • Loading branch information
pmichaud committed Apr 7, 2009
1 parent 1758bb9 commit 0e12baa
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/pmc/codestring.pmc
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,33 @@ A newline is automatically added to the end of the fmt.
}


/*

=item lineof(INTVAL pos)

Return the line number of the line at offset C<pos>. This code
assumes that the first line is line number zero.

*/

METHOD lineof(INTVAL pos) {
STRING *str = SELF.get_string();
INTVAL line = 0;
INTVAL ipos = 0;
INTVAL jpos;

jpos = Parrot_str_find_cclass(INTERP, enum_cclass_newline, str, ipos, pos);
while (jpos < pos) {
line++;
ipos = jpos + 1;
/* treat \r\n as a single line separator */
ipos += (string_ord(INTERP, str, jpos) == 13
&& string_ord(INTERP, str, jpos+1) == 10);
jpos = Parrot_str_find_cclass(INTERP, enum_cclass_newline, str, ipos, pos);
}
RETURN(INTVAL line);
}


/*

Expand Down
37 changes: 36 additions & 1 deletion t/pmc/codestring.t
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Tests the CodeString class directly.

.sub main :main
.include 'test_more.pir'
plan(24)
plan(38)

create_codestring()
calls_to_unique()
Expand All @@ -32,6 +32,7 @@ Tests the CodeString class directly.
namespace_keys()
first_char_repl_regression()
ord_from_name()
lineof_tests()
.end

.sub create_codestring
Expand Down Expand Up @@ -189,6 +190,40 @@ CODE
is($I0, -1, '<no such symbol>')
.end
.sub 'lineof_tests'
$P0 = new 'CodeString'
$P0 = "0123\n5678\r0123\r\n678\n"
$I0 = $P0.'lineof'(0)
is($I0, 0, "lineof - beginning of string")
$I0 = $P0.'lineof'(1)
is($I0, 0, "lineof - char on first line")
$I0 = $P0.'lineof'(4)
is($I0, 0, "lineof - immediately before nl")
$I0 = $P0.'lineof'(5)
is($I0, 1, "lineof - immediately after nl")
$I0 = $P0.'lineof'(8)
is($I0, 1, "lineof - char before cr")
$I0 = $P0.'lineof'(9)
is($I0, 1, "lineof - immediately before cr")
$I0 = $P0.'lineof'(10)
is($I0, 2, "lineof - immediately after cr")
$I0 = $P0.'lineof'(11)
is($I0, 2, "lineof - char after cr")
$I0 = $P0.'lineof'(13)
is($I0, 2, "lineof - char before crnl")
$I0 = $P0.'lineof'(14)
is($I0, 2, "lineof - immediately before crnl")
$I0 = $P0.'lineof'(15)
is($I0, 3, "lineof - middle of crnl")
$I0 = $P0.'lineof'(16)
is($I0, 3, "lineof - immediately after crnl")
$I0 = $P0.'lineof'(19)
is($I0, 3, "lineof - immediately before final nl")
$I0 = $P0.'lineof'(20)
is($I0, 4, "lineof - immediately after final nl")
.end
# Local Variables:
# mode: pir
# fill-column: 100
Expand Down

0 comments on commit 0e12baa

Please sign in to comment.