diff --git a/src/core/rope.rs b/src/core/rope.rs index 5286a16..ff314a4 100644 --- a/src/core/rope.rs +++ b/src/core/rope.rs @@ -101,7 +101,11 @@ impl Rope { } /// Insert new text into the rope at a given character index. - pub fn insert_at_char_index(self: &Rc, index: usize, text: impl Into) -> Rc { + pub fn insert_at_char_index( + self: &Rc, + index: usize, + text: impl Into, + ) -> Rc { let new_node = Rope::new(text); let total_chars = self.total_chars(); if index == 0 { @@ -116,6 +120,13 @@ impl Rope { } } + /// Return a new rope with `length` characters removed after `start`. + pub fn delete_at_char_index(self: &Rc, start: usize, length: usize) -> Rc { + let (beginning, rest) = self.split_at_char_index(start); + let (_, end) = rest.split_at_char_index(length); + beginning.concat(end) + } + /// Split the rope in two at character `index`. /// /// The result is two Ropes—one containing the first 'i' characters of the @@ -554,8 +565,29 @@ mod tests { let rope2 = rope1.insert_at_char_index(9, " "); assert_eq!(target.iter_chars().collect::(), "The brown dog"); assert_eq!(rope1.iter_chars().collect::(), "The quickbrown dog"); - assert_eq!(rope2.iter_chars().collect::(), "The quick brown dog"); - let rope3 = rope2.insert_at_char_index("The quick brown dog".len(), " jumps over the lazy fox."); - assert_eq!(rope3.iter_chars().collect::(), "The quick brown dog jumps over the lazy fox."); + assert_eq!( + rope2.iter_chars().collect::(), + "The quick brown dog" + ); + let rope3 = + rope2.insert_at_char_index("The quick brown dog".len(), " jumps over the lazy fox."); + assert_eq!( + rope3.iter_chars().collect::(), + "The quick brown dog jumps over the lazy fox." + ); + } + + #[test] + fn delete_at_char_index() { + let target = Rope::new("The quick brown fox jumps over the lazy dog."); + let test = target.delete_at_char_index(10, 6); + assert_eq!(target.iter_chars().collect::(), "The quick brown fox jumps over the lazy dog."); + assert_eq!(test.iter_chars().collect::(), "The quick fox jumps over the lazy dog."); + let test = target.delete_at_char_index(0, 4); + assert_eq!(target.iter_chars().collect::(), "The quick brown fox jumps over the lazy dog."); + assert_eq!(test.iter_chars().collect::(), "quick brown fox jumps over the lazy dog."); + let test = target.delete_at_char_index("The quick brown fox jumps over the lazy dog.".len()-5, 5); + assert_eq!(target.iter_chars().collect::(), "The quick brown fox jumps over the lazy dog."); + assert_eq!(test.iter_chars().collect::(), "The quick brown fox jumps over the lazy"); } }