Skip to content

Commit

Permalink
Fixed a range error when the removed string is empty.
Browse files Browse the repository at this point in the history
  • Loading branch information
piyoppi committed Mar 4, 2024
1 parent 60a5ef0 commit 7075727
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
16 changes: 11 additions & 5 deletions src/formatter/indent_remover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ impl Formatter for IndentRemover {
let mut cursor = byte_pos;
let bytes = content.as_bytes();

if !content.is_char_boundary(cursor) || bytes[cursor] != b'\n' {
if cursor >= bytes.len() || !content.is_char_boundary(cursor) || bytes[cursor] != b'\n' {
return cursor;
}

let found = loop {
if cursor == 0 {
break false;
}

cursor = cursor - 1;

let current = bytes.get(cursor);
Expand All @@ -27,10 +31,6 @@ impl Formatter for IndentRemover {
_ => break false,
};
}

if cursor == 0 {
break false;
}
};

if found {
Expand Down Expand Up @@ -105,5 +105,11 @@ mod tests {
// | ^
let mut content = "+<div>+ あ + + foo</div>".replace('+', "\n");
assert_eq!(remover.format(&mut content, 10), 10);

let mut content = "".to_string();
assert_eq!(remover.format(&mut content, 0), 0);

let mut content = "\n".to_string();
assert_eq!(remover.format(&mut content, 0), 0);
}
}
16 changes: 11 additions & 5 deletions src/formatter/prev_line_break_remover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@ pub struct PrevLineBreakRemover {}
impl Formatter for PrevLineBreakRemover {
fn format(&self, content: &mut String, byte_pos: usize) -> usize {
let mut cursor = byte_pos;

let bytes = content.as_bytes();

if cursor >= bytes.len() {
return cursor;
}

let line_break_pos = loop {
if cursor == 0 {
break None;
}

cursor = cursor - 1;

let current = bytes.get(cursor);
Expand All @@ -21,10 +28,6 @@ impl Formatter for PrevLineBreakRemover {
_ => break None,
};
}

if cursor == 0 {
break None;
}
};

if let Some(line_break_pos) = line_break_pos {
Expand Down Expand Up @@ -115,5 +118,8 @@ mod tests {
content,
"aaa+ あ</div>".replace('+', "\n")
);

let mut content = "\n".to_string();
assert_eq!(remover.format(&mut content, 0), 0);
}
}

0 comments on commit 7075727

Please sign in to comment.