From 4d7ec58ecd17483f12447bea502757891270d55f Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Fri, 12 Jan 2024 21:42:34 -0800 Subject: Simplify the code a little bit. --- src/rope.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) (limited to 'src/rope.rs') diff --git a/src/rope.rs b/src/rope.rs index 62c6a89..56f53d0 100644 --- a/src/rope.rs +++ b/src/rope.rs @@ -105,17 +105,15 @@ impl Rope { fn concat_height(&self, self_height: usize, other: &Rope, other_height: usize) -> Insert { if let (Rope(Node::Leaf(l)), Rope(Node::Leaf(r))) = (self, other) { if self.len() + other.len() <= MAX_NODE_SIZE { - let mut buf: Rc<[u8]> = Rc::from(vec![0; self.len() + other.len()]); - let buf_m = Rc::get_mut(&mut buf) - .expect("r was just created, so there can't be any other references"); - buf_m[..self.len()].copy_from_slice(l.bytes()); - buf_m[self.len()..].copy_from_slice(r.bytes()); - return Insert::Node(Rope::leaf(buf)); + let mut buf = Vec::with_capacity(self.len() + other.len()); + buf.extend_from_slice(l.bytes()); + buf.extend_from_slice(r.bytes()); + return Insert::Node(Rope::leaf(Rc::from(buf))); } if self.len() < MAX_NODE_SIZE / 2 || other.len() < MAX_NODE_SIZE / 2 { - let mut buf = vec![0; self.len() + other.len()]; - buf[..self.len()].copy_from_slice(l.bytes()); - buf[self.len()..].copy_from_slice(r.bytes()); + let mut buf = Vec::with_capacity(self.len() + other.len()); + buf.extend_from_slice(l.bytes()); + buf.extend_from_slice(r.bytes()); return Insert::Split( Rope::leaf(Rc::from(&buf[..buf.len() / 2])), Rope::leaf(Rc::from(&buf[buf.len() / 2..])), @@ -214,16 +212,14 @@ impl Rope { } pub fn read(r: &mut dyn Read) -> Result { + let mut buf = vec![0; MAX_NODE_SIZE]; let mut rope = Rope::empty(); loop { - let mut buf = Rc::new([0; MAX_NODE_SIZE]); - let buf_m = Rc::get_mut(&mut buf) - .expect("buf was just created, so there should be no other references"); - let n = r.read(buf_m)?; + let n = r.read(&mut buf)?; if n == 0 { break; } - rope = rope.concat(&Rope::from_slice(buf, 0, n)); + rope = rope.concat(&Rope::leaf(Rc::from(&buf[..n]))); } Ok(rope) } -- cgit v1.3.1