Add Rope::delete_at_char_index()

This commit is contained in:
Matthew Gordon 2024-10-19 22:01:01 -03:00
parent c3ebef8fc1
commit 78f8bd5fc4
1 changed files with 36 additions and 4 deletions

View File

@ -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<Rope>, index: usize, text: impl Into<String>) -> Rc<Rope> {
pub fn insert_at_char_index(
self: &Rc<Rope>,
index: usize,
text: impl Into<String>,
) -> Rc<Rope> {
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<Rope>, start: usize, length: usize) -> Rc<Rope> {
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::<String>(), "The brown dog");
assert_eq!(rope1.iter_chars().collect::<String>(), "The quickbrown dog");
assert_eq!(rope2.iter_chars().collect::<String>(), "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::<String>(), "The quick brown dog jumps over the lazy fox.");
assert_eq!(
rope2.iter_chars().collect::<String>(),
"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::<String>(),
"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::<String>(), "The quick brown fox jumps over the lazy dog.");
assert_eq!(test.iter_chars().collect::<String>(), "The quick fox jumps over the lazy dog.");
let test = target.delete_at_char_index(0, 4);
assert_eq!(target.iter_chars().collect::<String>(), "The quick brown fox jumps over the lazy dog.");
assert_eq!(test.iter_chars().collect::<String>(), "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::<String>(), "The quick brown fox jumps over the lazy dog.");
assert_eq!(test.iter_chars().collect::<String>(), "The quick brown fox jumps over the lazy");
}
}