From 707572739ffc76cfbc8830a3783ce8c5bad6488e Mon Sep 17 00:00:00 2001 From: piyoppi Date: Mon, 4 Mar 2024 23:00:55 +0900 Subject: [PATCH] Fixed a range error when the removed string is empty. --- src/formatter/indent_remover.rs | 16 +++++++++++----- src/formatter/prev_line_break_remover.rs | 16 +++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/formatter/indent_remover.rs b/src/formatter/indent_remover.rs index 132e78b..5699a47 100644 --- a/src/formatter/indent_remover.rs +++ b/src/formatter/indent_remover.rs @@ -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); @@ -27,10 +31,6 @@ impl Formatter for IndentRemover { _ => break false, }; } - - if cursor == 0 { - break false; - } }; if found { @@ -105,5 +105,11 @@ mod tests { // | ^ let mut content = "+
+ あ + + foo
".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); } } diff --git a/src/formatter/prev_line_break_remover.rs b/src/formatter/prev_line_break_remover.rs index b13436b..abff1b9 100644 --- a/src/formatter/prev_line_break_remover.rs +++ b/src/formatter/prev_line_break_remover.rs @@ -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); @@ -21,10 +28,6 @@ impl Formatter for PrevLineBreakRemover { _ => break None, }; } - - if cursor == 0 { - break None; - } }; if let Some(line_break_pos) = line_break_pos { @@ -115,5 +118,8 @@ mod tests { content, "aaa+ あ".replace('+', "\n") ); + + let mut content = "\n".to_string(); + assert_eq!(remover.format(&mut content, 0), 0); } }