Skip to content

Commit 021e882

Browse files
authored
Rollup merge of #115190 - allaboutevemirolive:push_trailing, r=petrochenkov
Add comment to the push_trailing function ## Add comment to the `push_trailing` function for clarity. I improve the explanation by describing: - how the code handles unicode and emoji characters using `char_indices`, - how the code handles the absence of high indexes, and - what the code's overall aim is.
2 parents d4b6cff + a8827ee commit 021e882

File tree

1 file changed

+16
-2
lines changed
  • compiler/rustc_errors/src

1 file changed

+16
-2
lines changed

Diff for: compiler/rustc_errors/src/lib.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -197,31 +197,45 @@ impl CodeSuggestion {
197197

198198
use rustc_span::{CharPos, Pos};
199199

200-
/// Append to a buffer the remainder of the line of existing source code, and return the
201-
/// count of lines that have been added for accurate highlighting.
200+
/// Extracts a substring from the provided `line_opt` based on the specified low and high indices,
201+
/// appends it to the given buffer `buf`, and returns the count of newline characters in the substring
202+
/// for accurate highlighting.
203+
/// If `line_opt` is `None`, a newline character is appended to the buffer, and 0 is returned.
204+
///
205+
/// ## Returns
206+
///
207+
/// The count of newline characters in the extracted substring.
202208
fn push_trailing(
203209
buf: &mut String,
204210
line_opt: Option<&Cow<'_, str>>,
205211
lo: &Loc,
206212
hi_opt: Option<&Loc>,
207213
) -> usize {
208214
let mut line_count = 0;
215+
// Convert CharPos to Usize, as CharPose is character offset
216+
// Extract low index and high index
209217
let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
210218
if let Some(line) = line_opt {
211219
if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
220+
// Get high index while account for rare unicode and emoji with char_indices
212221
let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
213222
match hi_opt {
223+
// If high index exist, take string from low to high index
214224
Some(hi) if hi > lo => {
225+
// count how many '\n' exist
215226
line_count = line[lo..hi].matches('\n').count();
216227
buf.push_str(&line[lo..hi])
217228
}
218229
Some(_) => (),
230+
// If high index absence, take string from low index till end string.len
219231
None => {
232+
// count how many '\n' exist
220233
line_count = line[lo..].matches('\n').count();
221234
buf.push_str(&line[lo..])
222235
}
223236
}
224237
}
238+
// If high index is None
225239
if hi_opt.is_none() {
226240
buf.push('\n');
227241
}

0 commit comments

Comments
 (0)