diff options
| author | Rose Hogenson <rosehogenson@posteo.net> | 2024-01-07 00:47:06 -0800 |
|---|---|---|
| committer | Rose Hogenson <rosehogenson@posteo.net> | 2024-01-07 00:47:06 -0800 |
| commit | 6f085692209f06c3427c475322786be06e45160f (patch) | |
| tree | 8f2ef0679b280dc9ca31571fa998324c9c8f9345 | |
| parent | 3ab0bd82badcb86a08f21aa48f2825c7fcdd0525 (diff) | |
| download | editor-6f085692209f06c3427c475322786be06e45160f.tar.zst | |
Avoid an extra copy.
| -rw-r--r-- | src/rope.rs | 18 |
1 files changed, 7 insertions, 11 deletions
diff --git a/src/rope.rs b/src/rope.rs index 6c1cad6..60a3fe8 100644 --- a/src/rope.rs +++ b/src/rope.rs @@ -73,7 +73,7 @@ enum Node { #[derive(Debug, Clone)] pub struct Rope(Node); -fn leaf(buf: Vec<u8>) -> Rope { +fn leaf(buf: &[u8]) -> Rope { let len = buf.len(); return Rope(Node::Leaf(Leaf { buf: Rc::from(buf), @@ -221,17 +221,13 @@ impl Rope { let mut buf = Vec::new(); buf.extend_from_slice(&l.bytes()); buf.extend_from_slice(&r.bytes()); - return Insert::Node(leaf(buf)); + return Insert::Node(leaf(&buf)); } if self.len() < MAX_NODE_SIZE / 2 || other.len() < MAX_NODE_SIZE / 2 { let mut buf = Vec::new(); buf.extend_from_slice(&l.bytes()); buf.extend_from_slice(&r.bytes()); - let mut buf1 = Vec::new(); - buf1.extend_from_slice(&buf[..buf.len() / 2]); - let mut buf2 = Vec::new(); - buf2.extend_from_slice(&buf[buf.len() / 2..]); - return Insert::Split(leaf(buf1), leaf(buf2)); + return Insert::Split(leaf(&buf[..buf.len() / 2]), leaf(&buf[buf.len() / 2..])); } } if self.height() == other.height() { @@ -290,7 +286,7 @@ impl Rope { pub fn insert(&self, pos: usize, c: u8) -> Rope { let res = self .slice(0, pos) - .concat(&leaf(vec![c])) + .concat(&leaf(&vec![c])) .concat(&self.slice(pos, self.len())); return res; } @@ -319,7 +315,7 @@ impl Rope { Rope(Node::Branch(b)) => { let mut start = start; let mut end = end; - let mut slice = leaf(Vec::new()); + let mut slice = leaf(&Vec::new()); for child in b.children() { if start < child.len() { slice = slice.concat(&child.slice(start, std::cmp::min(end, child.len()))); @@ -340,7 +336,7 @@ impl Rope { pub fn open(path: &Path) -> Result<Rope, Box<dyn Error>> { let mut f = File::open(path).map_err(|err| format!("open file {}: {}", path.display(), err))?; - let mut rope = leaf(Vec::new()); + let mut rope = leaf(&Vec::new()); loop { let mut buf = vec![0; MAX_NODE_SIZE]; let n = match f.read(&mut buf) { @@ -356,7 +352,7 @@ impl Rope { break; } buf.truncate(n); - rope = rope.concat(&leaf(buf)); + rope = rope.concat(&leaf(&buf)); } return Ok(rope); } |
