git.delta.rocks / jrsonnet / refs/commits / beff66c04fc2

difftreelog

test fix column offsets

Лач2020-07-19parent: #ea5e4ec.patch.diff
in: master

1 file changed

modifiedcrates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/trace/location.rs
1#[derive(Clone, PartialEq, Debug)]2pub struct CodeLocation {3	pub line: usize,4	pub column: usize,56	pub line_start_offset: usize,7	pub line_end_offset: usize,8}910pub fn offset_to_location(file: &str, offsets: &[usize]) -> Vec<CodeLocation> {11	if offsets.is_empty() {12		return vec![];13	}14	let mut line = 1;15	let mut column = 1;16	let max_offset = *offsets.iter().max().unwrap();1718	let mut offset_map = offsets19		.iter()20		.enumerate()21		.map(|(pos, offset)| (*offset, pos))22		.collect::<Vec<_>>();23	offset_map.sort_by_key(|v| v.0);24	offset_map.reverse();2526	let mut out = vec![27		CodeLocation {28			column: 0,29			line: 0,30			line_start_offset: 0,31			line_end_offset: 032		};33		offsets.len()34	];35	let mut with_no_known_line_ending = vec![];36	let mut this_line_offset = 0;37	for (pos, ch) in file.chars().enumerate() {38		column += 1;39		match offset_map.last() {40			Some(x) if x.0 == pos => {41				let out_idx = x.1;42				with_no_known_line_ending.push(out_idx);43				out[out_idx].line = line;44				out[out_idx].column = column;45				out[out_idx].line_start_offset = this_line_offset;46				offset_map.pop();47			}48			_ => {}49		}50		if ch == '\n' {51			line += 1;52			column = 1;5354			for idx in with_no_known_line_ending.drain(..) {55				out[idx].line_end_offset = pos;56			}57			this_line_offset = pos + 1;5859			if pos == max_offset + 1 {60				break;61			}62		}63	}64	let file_end = file.chars().count();65	for idx in with_no_known_line_ending {66		out[idx].line_end_offset = file_end;67	}6869	out70}7172#[cfg(test)]73pub mod tests {74	use super::{offset_to_location, CodeLocation};7576	#[test]77	fn test() {78		assert_eq!(79			offset_to_location(80				"hello world\n_______________________________________________________",81				&[0, 14]82			),83			vec![84				CodeLocation {85					line: 1,86					column: 1,87					line_start_offset: 0,88					line_end_offset: 1189				},90				CodeLocation {91					line: 2,92					column: 3,93					line_start_offset: 11,94					line_end_offset: 6795				}96			]97		)98	}99}