From 6f085692209f06c3427c475322786be06e45160f Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Sun, 7 Jan 2024 00:47:06 -0800 Subject: Avoid an extra copy. --- src/rope.rs | 18 +++++++----------- 1 file 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) -> 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> { 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); } -- cgit v1.3.1