From 5a97a67c736db4e3d3a5aec7005a7f055a4beaae Mon Sep 17 00:00:00 2001 From: Mauro Balbi Date: Sun, 6 Aug 2023 07:08:58 +0200 Subject: [PATCH] Improve readability --- crates/nil/src/vfs.rs | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/crates/nil/src/vfs.rs b/crates/nil/src/vfs.rs index c1cc5d4..83ba510 100644 --- a/crates/nil/src/vfs.rs +++ b/crates/nil/src/vfs.rs @@ -6,7 +6,7 @@ use nix_interop::nixos_options::NixosOptions; use slab::Slab; use std::collections::HashMap; use std::sync::Arc; -use std::{fmt, iter, mem}; +use std::{fmt, mem}; use text_size::{TextRange, TextSize}; /// Vfs stores file contents with line mapping, and a mapping between @@ -168,9 +168,8 @@ enum CodeUnitsDiff { impl LineMap { fn normalize(mut text: String) -> (String, Self) { - let text_len = text.len(); // Must be valid for `TextSize`. - u32::try_from(text_len).expect("Text too long"); + let text_len = u32::try_from(text.len()).expect("Text too long"); text.retain(|c| c != '\r'); let bytes = text.as_bytes(); @@ -186,13 +185,11 @@ impl LineMap { ) .collect::>(); - let ends = &line_starts[1..]; let mut char_diffs = HashMap::new(); - for ((&start, &end), i) in line_starts - .iter() - .zip(ends.iter().chain(iter::once(&(text_len as u32)))) - .zip(0u32..) - { + + let start_pos_iter = line_starts.iter().copied(); + let end_pos_iter = line_starts[1..].iter().copied().chain(Some(text_len)); + for ((start, end), i) in start_pos_iter.zip(end_pos_iter).zip(0u32..) { let mut diffs = Vec::new(); for (&b, pos) in bytes[start as usize..end as usize].iter().zip(0u32..) { let diff = match b { @@ -212,7 +209,7 @@ impl LineMap { let this = Self { line_starts, char_diffs, - len: text_len as u32, + len: text_len, }; (text, this) } @@ -254,16 +251,13 @@ impl LineMap { let mut len = if line + 1 >= self.line_starts.len() as u32 { self.len - self.line_starts[line as usize] } else { - self.line_starts[line as usize + 1] - self.line_starts[line as usize] + // Minus the trailing `\n` for non-last-lines. + self.line_starts[line as usize + 1] - self.line_starts[line as usize] - 1 }; if let Some(diffs) = self.char_diffs.get(&line) { len -= diffs.iter().map(|&(_, diff)| diff as u32).sum::(); } - // Lines except the last one has a trailing `\n`. - if line + 1 != self.line_starts.len() as u32 { - len -= 1; - } len } }