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
use alloc::vec::Vec;
use core::fmt;
/// The unit used for a zero-based source column.
///
/// Columns count source units, not terminal display cells. Tabs count as one
/// scalar or UTF-16 unit, and combining characters count separately.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ColumnEncoding {
/// Bytes, including offsets inside a multi-byte UTF-8 character.
Utf8,
/// Unicode scalar values (`char`s).
Scalar,
/// UTF-16 code units; supplementary characters occupy two units.
Utf16,
}
/// A zero-based physical source line and column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
/// The zero-based physical line number.
pub line: usize,
/// The zero-based column in the selected [`ColumnEncoding`].
pub column: usize,
}
impl Position {
/// Explicitly converts both coordinates to one-based display coordinates.
///
/// The returned value is for display, not input to [`LineIndex::to_offset`],
/// which always expects zero-based coordinates. Returns
/// [`PositionError::OutOfBounds`] if either addition overflows.
///
/// # Errors
/// Returns [`PositionError::OutOfBounds`] on coordinate overflow.
pub fn one_based(self) -> Result<Self, PositionError> {
Ok(Self {
line: self.line.checked_add(1).ok_or(PositionError::OutOfBounds)?,
column: self
.column
.checked_add(1)
.ok_or(PositionError::OutOfBounds)?,
})
}
}
/// A source position that cannot be represented in the requested encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PositionError {
/// An offset, line, or column is outside the source, or an addition overflows.
OutOfBounds,
/// A scalar or UTF-16 conversion starts inside a UTF-8 character.
InvalidUtf8Boundary,
/// A UTF-16 column splits a supplementary character's surrogate pair.
SplitSurrogate,
/// An offset lies between the carriage return and line feed of CRLF.
InsideCrLf,
}
impl fmt::Display for PositionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::OutOfBounds => "source position is out of bounds",
Self::InvalidUtf8Boundary => "source offset is not a UTF-8 character boundary",
Self::SplitSurrogate => "UTF-16 column splits a surrogate pair",
Self::InsideCrLf => "source offset lies inside a CRLF line ending",
})
}
}
impl core::error::Error for PositionError {}
#[derive(Debug, Clone, Copy)]
struct Line {
start: usize,
end: usize,
}
/// A physical-line index borrowing its original source text.
///
/// LF, CRLF, and lone CR each end a line, independently of parser syntax.
/// A terminal ending creates a final empty line; empty input has one empty
/// line. Line terminators do not contribute to columns: their first byte maps
/// to the preceding line's content end, while the interior of CRLF is rejected.
/// EOF is always a valid offset.
///
/// Construction stores only line boundaries, never a copy of the source.
/// Offset lookup uses binary search; scalar and UTF-16 conversions scan only
/// the selected line's relevant content. No conversion clamps its input.
#[derive(Debug, Clone)]
pub struct LineIndex<'src> {
source: &'src str,
lines: Vec<Line>,
}
impl<'src> LineIndex<'src> {
/// Indexes physical lines in `source`, borrowing it for the index's lifetime.
#[must_use]
pub fn new(source: &'src str) -> Self {
let bytes = source.as_bytes();
let mut lines = Vec::new();
let mut start = 0;
let mut offset = 0;
while offset < bytes.len() {
match bytes[offset] {
b'\r' | b'\n' => {
lines.push(Line { start, end: offset });
if bytes[offset] == b'\r' && bytes.get(offset + 1) == Some(&b'\n') {
offset += 2;
} else {
offset += 1;
}
start = offset;
}
_ => offset += 1,
}
}
lines.push(Line {
start,
end: source.len(),
});
Self { source, lines }
}
/// Returns the number of physical lines, including a terminal empty line.
#[must_use]
pub fn line_count(&self) -> usize {
self.lines.len()
}
/// Converts a byte offset to a zero-based position.
///
/// UTF-8 columns preserve every byte offset, even within a character.
/// Scalar and UTF-16 columns require a character boundary. Offsets past EOF
/// and the interior of a CRLF ending are errors in every encoding.
///
/// # Errors
/// Rejects offsets beyond EOF, inside CRLF, or inside UTF-8 characters when
/// the selected encoding requires scalar boundaries.
pub fn to_position(
&self,
offset: usize,
encoding: ColumnEncoding,
) -> Result<Position, PositionError> {
if offset > self.source.len() {
return Err(PositionError::OutOfBounds);
}
// There is always a line starting at zero, so subtraction cannot underflow.
let line = self.lines.partition_point(|line| line.start <= offset) - 1;
let bounds = self.lines[line];
if offset > bounds.end {
return Err(PositionError::InsideCrLf);
}
let column = match encoding {
ColumnEncoding::Utf8 => offset - bounds.start,
ColumnEncoding::Scalar | ColumnEncoding::Utf16 => {
if !self.source.is_char_boundary(offset) {
return Err(PositionError::InvalidUtf8Boundary);
}
let prefix = &self.source[bounds.start..offset];
match encoding {
ColumnEncoding::Scalar => prefix.chars().count(),
ColumnEncoding::Utf16 => prefix.chars().map(char::len_utf16).sum(),
ColumnEncoding::Utf8 => unreachable!(),
}
}
};
Ok(Position { line, column })
}
/// Converts a zero-based position to an exact byte offset.
///
/// Columns may reach the content end but never extend into a terminator or
/// beyond EOF. UTF-8 columns can select interior character bytes. UTF-16
/// columns that split a surrogate pair return [`PositionError::SplitSurrogate`].
///
/// # Errors
/// Rejects lines/columns outside content and UTF-16 columns that split a
/// surrogate pair. Terminators cannot be addressed as additional columns.
pub fn to_offset(
&self,
position: Position,
encoding: ColumnEncoding,
) -> Result<usize, PositionError> {
let line = self
.lines
.get(position.line)
.ok_or(PositionError::OutOfBounds)?;
let content = &self.source[line.start..line.end];
if position.column > content.len() {
return Err(PositionError::OutOfBounds);
}
if encoding == ColumnEncoding::Utf8 {
return Ok(line.start + position.column);
}
let mut column = 0;
for (offset, ch) in content.char_indices() {
if column == position.column {
return Ok(line.start + offset);
}
column += match encoding {
ColumnEncoding::Scalar => 1,
ColumnEncoding::Utf16 => ch.len_utf16(),
ColumnEncoding::Utf8 => unreachable!(),
};
if column > position.column {
return Err(PositionError::SplitSurrogate);
}
}
if column == position.column {
Ok(line.end)
} else {
Err(PositionError::OutOfBounds)
}
}
}