Skip to content

Commit b4fb4cd

Browse files
committed
Support prepend
1 parent 6a516ad commit b4fb4cd

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

src/chunk.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,16 @@ impl<'s> Chunk<'s> {
2727
intro_iter.chain(Some(source_frag)).chain(outro_iter)
2828
}
2929

30-
pub fn append_outro(&mut self, frag: CowStr<'s>) {
30+
pub fn append(&mut self, frag: CowStr<'s>) {
3131
self.len += frag.len();
3232
self.outro.push(frag.into())
3333
}
3434

35+
pub fn prepend(&mut self, frag: CowStr<'s>) {
36+
self.len += frag.len();
37+
self.intro.push(frag.into())
38+
}
39+
3540
pub fn len(&self) -> usize {
3641
self.len
3742
}

src/magic_string.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,12 @@ impl<'s> MagicString<'s> {
4242
}
4343

4444
pub fn append(&mut self, source: impl Into<CowStr<'s>>) -> &mut Self {
45-
self.last_chunk_mut().append_outro(source.into());
45+
self.last_chunk_mut().append(source.into());
46+
self
47+
}
48+
49+
pub fn prepend(&mut self, source: impl Into<CowStr<'s>>) -> &mut Self {
50+
self.first_chunk_mut().prepend(source.into());
4651
self
4752
}
4853

@@ -99,6 +104,11 @@ impl<'s> MagicString<'s> {
99104
let idx = self.chunk_by_end.get(&(self.source_len)).unwrap();
100105
&mut self.chunks[*idx]
101106
}
107+
108+
fn first_chunk_mut(&mut self) -> &mut Chunk<'s> {
109+
let idx = self.chunk_by_start.get(&0).unwrap();
110+
&mut self.chunks[*idx]
111+
}
102112
}
103113

104114
struct ChunkIter<'a> {

tests/magic_string.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,17 @@ mod append {
2828
assert_eq!(s.to_string(), "abcdefghijklxyzxyz");
2929
}
3030
}
31+
32+
mod prepend {
33+
use super::*;
34+
35+
#[test]
36+
fn should_append_content() {
37+
// should append content
38+
let mut s = MagicString::new("abcdefghijkl");
39+
s.prepend("xyz");
40+
assert_eq!(s.to_string(), "xyzabcdefghijkl");
41+
s.prepend("xyz");
42+
assert_eq!(s.to_string(), "xyzxyzabcdefghijkl");
43+
}
44+
}

0 commit comments

Comments
 (0)