Skip to content

Instantly share code, notes, and snippets.

@kaleidawave
Created April 12, 2023 16:42
Show Gist options
  • Select an option

  • Save kaleidawave/de39f36c22c330a124dbd8b214e355d0 to your computer and use it in GitHub Desktop.

Select an option

Save kaleidawave/de39f36c22c330a124dbd8b214e355d0 to your computer and use it in GitHub Desktop.
rust-positions
/// Returns `(line, column)`. Return is zero based
fn get_line_column_from_string_and_idx(end: u32, char_indices: &mut CharIndices) -> (u32, u32) {
let (mut line, mut column) = (0, 0);
for (_, chr) in char_indices.take_while(|(idx, _)| *idx < end.try_into().unwrap()) {
if chr == '\n' {
line += 1;
column = 0;
} else {
column += chr.len_utf8() as u32;
}
}
(line, column)
}
/// Converts line and column to index in string
///
/// Line and column are zero based
///
/// Inverse of [get_line_column_from_string_and_idx]
fn line_column_position_to_position(
mut line: u32,
column: u32,
char_indices: &mut CharIndices,
full_length: usize,
) -> usize {
while line > 0 {
// TODO unwrap
if '\n' == char_indices.next().unwrap().1 {
line -= 1;
}
}
char_indices
.next()
.map(|(idx, _)| idx)
.unwrap_or(full_length)
+ column as usize
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment