1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use crate::error::Error;
use crate::chunk_list::ChunkList;
use alloc::string::String;
pub struct RefactoryString<'a> {
chunks: ChunkList<'a>
}
impl<'a> RefactoryString<'a> {
pub fn new(content: &'a str) -> RefactoryString<'a> {
RefactoryString {
chunks:ChunkList::new(content)
}
}
pub fn len(&self) -> usize {
self.chunks.iter().fold(0, |a,x| a + x.len())
}
pub fn to_string(&self) -> String {
let mut s = String::new();
for it in self.chunks.iter() {
s.push_str(&it.to_string());
}
s
}
#[inline]
fn do_insert(
&mut self,
index: usize,
content: &str,
left: bool,
append: bool,
) -> Result<(), Error> {
let (l, r) = self.chunks.split(index)?;
if append {
if left {
l.append_right(content)
} else {
r.append_left(content)
}
} else {
if left {
l.prepend_right(content)
} else {
r.prepend_left(content)
}
}
}
pub fn append_left(&mut self, index: usize, content: &str) -> Result<(), Error> {
self.do_insert(index, content, true, true)
}
pub fn prepend_left(&mut self, index: usize, content: &str) -> Result<(), Error> {
self.do_insert(index, content, true, false)
}
pub fn append_right(&mut self, index: usize, content: &str) -> Result<(), Error> {
self.do_insert(index, content, false, true)
}
pub fn prepend_right(&mut self, index: usize, content: &str) -> Result<(), Error> {
self.do_insert(index, content, false,false)
}
pub fn prepend(&mut self, content: &str) -> Result<(), Error> {
self.prepend_left(0, content)
}
pub fn append(&mut self, content: &str) -> Result<(), Error> {
self.append_right(self.len(), content)
}
pub fn overwrite(&mut self, start: usize, end: usize, content: &str) -> Result<(), Error> {
self.remove(start, end)?;
self.append_left(start, content)?;
Ok(())
}
pub fn remove(&mut self, start: usize, end: usize) -> Result<(), Error> {
self.chunks.remove(start, end)
}
}