Skip to content

Commit

Permalink
Improve readability
Browse files Browse the repository at this point in the history
  • Loading branch information
maurobalbi committed Aug 6, 2023
1 parent f628bbf commit 5a97a67
Showing 1 changed file with 9 additions and 15 deletions.
24 changes: 9 additions & 15 deletions crates/nil/src/vfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand All @@ -186,13 +185,11 @@ impl LineMap {
)
.collect::<Vec<_>>();

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 {
Expand All @@ -212,7 +209,7 @@ impl LineMap {
let this = Self {
line_starts,
char_diffs,
len: text_len as u32,
len: text_len,
};
(text, this)
}
Expand Down Expand Up @@ -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::<u32>();
}
// Lines except the last one has a trailing `\n`.
if line + 1 != self.line_starts.len() as u32 {
len -= 1;
}
len
}
}
Expand Down

0 comments on commit 5a97a67

Please sign in to comment.