Skip to content

Commit 3880eda

Browse files
committed
[rust] add support for accesing the list of newline offsets
1 parent 6881fd5 commit 3880eda

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

rust/ruby-prism/src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,17 @@ impl<'pr> ParseResult<'pr> {
600600
&self.source[start..end]
601601
}
602602

603+
/// Returns a slice containing the offsets of the newlines in the source string that
604+
/// was parsed. The slice is guaranteed to be non-empty as Prism considers the source
605+
/// string to start with a newline; thus the first offset will always be 0.
606+
#[must_use]
607+
pub fn newlines(&self) -> &'pr [usize] {
608+
unsafe {
609+
let list = &(*self.parser.as_ptr()).newline_list;
610+
std::slice::from_raw_parts(list.offsets, list.size)
611+
}
612+
}
613+
603614
/// Returns an iterator that can be used to iterate over the errors in the
604615
/// parse result.
605616
#[must_use]
@@ -723,6 +734,27 @@ mod tests {
723734
}
724735
}
725736

737+
#[test]
738+
fn newlines_test() {
739+
let source = "";
740+
let result = parse(source.as_ref());
741+
742+
let expected: [usize; 1] = [0];
743+
assert_eq!(expected, result.newlines());
744+
745+
let source = "1 + 1";
746+
let result = parse(source.as_ref());
747+
748+
let expected: [usize; 1] = [0];
749+
assert_eq!(expected, result.newlines());
750+
751+
let source = "begin\n1 + 1\n2 + 2\nend";
752+
let result = parse(source.as_ref());
753+
754+
let expected: [usize; 4] = [0, 6, 12, 18];
755+
assert_eq!(expected, result.newlines());
756+
}
757+
726758
#[test]
727759
fn magic_comments_test() {
728760
use crate::MagicComment;

0 commit comments

Comments
 (0)