Skip to content

Commit 16674e5

Browse files
froydnjkddnewton
authored andcommitted
[rust] add support for accesing the list of line offsets
1 parent 80b7402 commit 16674e5

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

rust/ruby-prism/src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,27 @@ mod tests {
6565
}
6666
}
6767

68+
#[test]
69+
fn line_offsets_test() {
70+
let source = "";
71+
let result = parse(source.as_ref());
72+
73+
let expected: [u32; 1] = [0];
74+
assert_eq!(expected, result.line_offsets());
75+
76+
let source = "1 + 1";
77+
let result = parse(source.as_ref());
78+
79+
let expected: [u32; 1] = [0];
80+
assert_eq!(expected, result.line_offsets());
81+
82+
let source = "begin\n1 + 1\n2 + 2\nend";
83+
let result = parse(source.as_ref());
84+
85+
let expected: [u32; 4] = [0, 6, 12, 18];
86+
assert_eq!(expected, result.line_offsets());
87+
}
88+
6889
#[test]
6990
fn magic_comments_test() {
7091
use crate::MagicComment;

rust/ruby-prism/src/parse_result/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,15 @@ impl<'pr> ParseResult<'pr> {
119119
&self.source[start..end]
120120
}
121121

122+
/// Returns a slice containing the offsets of the start of each line in the source string
123+
/// that was parsed.
124+
#[must_use]
125+
pub fn line_offsets(&self) -> &'pr [u32] {
126+
unsafe {
127+
let list = &(*self.parser.as_ptr()).line_offsets;
128+
std::slice::from_raw_parts(list.offsets, list.size)
129+
}
130+
}
122131
/// Returns an iterator that can be used to iterate over the errors in the
123132
/// parse result.
124133
#[must_use]

0 commit comments

Comments
 (0)