1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use std::cell::Cell;
use crate::Position;
/// Pre-calculated line position map for efficient offset-to-position conversion.
///
/// `LineMap` scans the input once to build a sorted list of line start offsets
/// plus a per-line ASCII flag, then provides `O(log n)` line lookups and
/// `O(1)` column computation for the common all-ASCII case.
///
/// # Key Properties
///
/// - **Immutable**: Safe for use in PEG action blocks and backtracking parsers
/// - **Efficient**: `O(n)` construction, `O(log n)` line lookup, `O(1)` column
/// for ASCII lines, `O(line_length)` column for lines with non-ASCII content
/// - **UTF-8 aware**: Handles multi-byte characters correctly by falling back
/// to `chars().count()` on lines that are not pure ASCII
///
/// # Usage
///
/// ```ignore
/// let line_map = LineMap::new(input);
/// let position = line_map.offset_to_position(byte_offset, input);
/// ```
#[derive(Debug, Clone)]
pub(crate) struct LineMap {
/// Byte offsets where each line starts in the input
line_starts: Vec<usize>,
/// Per-line flag: `true` when every byte of the line is ASCII (< 0x80).
/// For ASCII lines, column is just `offset - line_start_byte` (no scan).
/// Indexed by zero-based line number, same length as `line_starts`.
line_is_ascii: Vec<bool>,
/// Monotonic-access cache: the last resolved line index and the byte
/// range `[start, end)` of that line. PEG parsing advances mostly
/// forward, so consecutive lookups usually land on the same line or
/// the next one — letting us skip the `O(log n)` binary search.
/// Set to `None` before the first lookup.
last_line: Cell<Option<CachedLine>>,
}
#[derive(Debug, Clone, Copy)]
struct CachedLine {
line_idx: usize,
range_start: usize,
range_end: usize,
}
impl LineMap {
/// Build line map by scanning input once during initialization.
/// This is called once before parsing starts.
pub(crate) fn new(input: &str) -> Self {
let mut line_starts = vec![0]; // Line 1 starts at byte offset 0
let mut line_is_ascii = Vec::new();
let mut current_line_ascii = true;
// Iterate raw bytes rather than char_indices: `\n` is always a
// single-byte character in UTF-8, so we can't miss a line break,
// and we can incrementally track ASCII-ness per line without a
// second pass.
for (i, &b) in input.as_bytes().iter().enumerate() {
if b >= 0x80 {
current_line_ascii = false;
}
if b == b'\n' {
line_is_ascii.push(current_line_ascii);
line_starts.push(i + 1); // Next line starts after the newline
current_line_ascii = true;
}
}
// Flush the trailing line (or the only line, if there is no newline).
line_is_ascii.push(current_line_ascii);
Self {
line_starts,
line_is_ascii,
last_line: Cell::new(None),
}
}
/// Resolve `offset` to a 1-based line number.
///
/// Fast path: consecutive lookups on the same line hit the cache and skip
/// the binary search. When the cache misses, falls back to
/// `binary_search` and refreshes the cache so the next call on the same
/// (or adjacent) line is O(1).
fn line_for_offset(&self, offset: usize) -> (usize, usize) {
if let Some(cached) = self.last_line.get()
&& offset >= cached.range_start
&& offset < cached.range_end
{
return (cached.line_idx, cached.range_start);
}
let line = match self.line_starts.binary_search(&offset) {
Ok(line_idx) => line_idx + 1, // Exact match: start of this line
Err(line_idx) => line_idx, // Insert position: this line number
};
let line_idx = line.saturating_sub(1);
let range_start = self.line_starts.get(line_idx).copied().unwrap_or(0);
let range_end = self
.line_starts
.get(line_idx + 1)
.copied()
.unwrap_or(usize::MAX);
self.last_line.set(Some(CachedLine {
line_idx,
range_start,
range_end,
}));
(line_idx, range_start)
}
/// Convert byte offset to `Position` using binary search — `O(log n)`
/// line lookup, `O(1)` column for ASCII lines, `O(line_length)` column
/// for lines with non-ASCII content. Pure function, safe for use in PEG
/// action blocks.
#[tracing::instrument(level = "debug")]
pub(crate) fn offset_to_position(&self, offset: usize, input: &str) -> Position {
let (line_idx, line_start_byte) = self.line_for_offset(offset);
let line = line_idx + 1;
// Ensure the offset doesn't land in the middle of a multi-byte UTF-8 character.
// If it does, round backward to the start of the current character.
let adjusted_offset = if offset > input.len() {
input.len()
} else if input.is_char_boundary(offset) {
offset
} else {
// Find the previous valid character boundary (start of current char)
(0..=offset)
.rev()
.find(|&i| input.is_char_boundary(i))
.unwrap_or(0)
};
// Fast path: if the containing line is pure ASCII, char count equals
// byte count, so column is a subtraction. This avoids the per-call
// `is_ascii()` scan (which itself is O(line_length)) plus the
// `chars().count()` fallback scan — together the dominant hot spot
// in large-document parses, accounting for ~24% of parser self-time
// before this optimisation.
let chars_in_line = if self.line_is_ascii.get(line_idx).copied().unwrap_or(false) {
adjusted_offset - line_start_byte
} else {
input
.get(line_start_byte..adjusted_offset)
.map_or(0, |s| s.chars().count())
};
Position {
line,
column: chars_in_line + 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_line_map_single_line() {
let input = "Hello, World!";
let line_map = LineMap::new(input);
assert_eq!(line_map.line_starts, vec![0]);
// Start of input
let pos = line_map.offset_to_position(0, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 1);
// Middle of line
let pos = line_map.offset_to_position(7, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 8);
// End of line
let pos = line_map.offset_to_position(12, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 13);
}
#[test]
fn test_line_map_multiple_lines() {
let input = "Line 1\nLine 2\nLine 3";
let line_map = LineMap::new(input);
assert_eq!(line_map.line_starts, vec![0, 7, 14]);
// Start of first line
let pos = line_map.offset_to_position(0, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 1);
// End of first line (before newline)
let pos = line_map.offset_to_position(6, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 7);
// Start of second line
let pos = line_map.offset_to_position(7, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 1);
// Middle of second line
let pos = line_map.offset_to_position(10, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 4);
// Start of third line
let pos = line_map.offset_to_position(14, input);
assert_eq!(pos.line, 3);
assert_eq!(pos.column, 1);
}
#[test]
fn test_line_map_empty_lines() {
let input = "Line 1\n\nLine 3";
let line_map = LineMap::new(input);
assert_eq!(line_map.line_starts, vec![0, 7, 8]);
// Start of empty line
let pos = line_map.offset_to_position(7, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 1);
// Start of line after empty line
let pos = line_map.offset_to_position(8, input);
assert_eq!(pos.line, 3);
assert_eq!(pos.column, 1);
}
#[test]
fn test_line_map_asciidoc_example() {
let input = "= Document Title\nLorn_Kismet R. Lee <kismet@asciidoctor.org>\nv2.9, 01-09-2024: Fall incarnation\n:description: The document's description.\n:sectanchors:\n:url-repo: https://my-git-repo.com";
let line_map = LineMap::new(input);
// Title start (after "= ")
let pos = line_map.offset_to_position(2, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 3);
// Author line start (17 = length of "= Document Title\n")
let pos = line_map.offset_to_position(17, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 1);
// Revision line start (61 = 17 + 44, where 44 is length of author line + newline)
let pos = line_map.offset_to_position(61, input);
assert_eq!(pos.line, 3);
assert_eq!(pos.column, 1);
}
#[test]
fn test_line_map_beyond_input() {
let input = "Hello";
let line_map = LineMap::new(input);
// Beyond input: offset is clamped to input.len(), giving position after last character
let pos = line_map.offset_to_position(100, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 6); // After 5 characters, column is 6
}
#[test]
fn test_line_map_empty_input() {
let input = "";
let line_map = LineMap::new(input);
assert_eq!(line_map.line_starts, vec![0]);
let pos = line_map.offset_to_position(0, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 1);
}
#[test]
fn test_line_map_utf8_content() {
// "é" is 2 bytes in UTF-8 (0xC3 0xA9). Line 1 is non-ASCII, line 2 is ASCII.
// Bytes: c(0) a(1) f(2) é(3,4) \n(5) b(6) a(7) r(8)
let input = "caf\u{00e9}\nbar";
let line_map = LineMap::new(input);
// Slow path: non-ASCII line, column via `chars().count()`.
// Offset 5 = byte just past "café" (the '\n'); binary_search Err(1).
let pos = line_map.offset_to_position(5, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 5); // 4 chars in "café" + 1
// Fast path on the line *after* a non-ASCII line: line_is_ascii[1] is true.
let pos = line_map.offset_to_position(8, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 3);
// Mid-char offset: offset 4 lands inside the 2-byte 'é' and must
// round back to byte 3 before counting chars.
let pos = line_map.offset_to_position(4, input);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 4); // "caf" = 3 chars + 1
// Exact match on a line start that follows a non-ASCII line
// (binary_search Ok arm, guarding line-index arithmetic).
let pos = line_map.offset_to_position(6, input);
assert_eq!(pos.line, 2);
assert_eq!(pos.column, 1);
}
}