From 82913ff77a7fc8a4489128cc61b23c1b18b31690 Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Wed, 27 Dec 2023 08:40:32 -0800 Subject: Fix a bug in how unicode is printed. Technically a single character can be split across multiple chunks, so we can just join all the chunks before printing. It's not the most efficient, but this is only for debugging. --- src/rope.rs | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) (limited to 'src/rope.rs') diff --git a/src/rope.rs b/src/rope.rs index 437d5e3..f26457c 100644 --- a/src/rope.rs +++ b/src/rope.rs @@ -4,7 +4,8 @@ use std::io::{ErrorKind, Read}; use std::path::Path; use std::rc::Rc; -const MAX_NODE_SIZE: usize = 512; +// Set to a small value to help identify bugs in the implementation. +const MAX_NODE_SIZE: usize = 4; struct Branch { len: usize, @@ -17,40 +18,37 @@ enum Node { Branch(Branch), } -impl Display for Node { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { +impl Node { + fn len(&self) -> usize { + return match self { + Node::Leaf(v) => v.len(), + Node::Branch(b) => b.len, + }; + } + + fn write(&self, out: &mut Vec) { match self { - Node::Leaf(s) => { - return write!(f, "{}", String::from_utf8_lossy(s)); + Node::Leaf(v) => { + out.extend(v); } Node::Branch(b) => { - if let Err(err) = write!(f, "{}", b.left) { - return Err(err); - } - return write!(f, "{}", b.right); + b.left.write(out); + b.right.write(out); } } } } -impl Node { - fn len(&self) -> usize { - return match self { - Node::Leaf(v) => v.len(), - Node::Branch(b) => b.len, - }; +impl Display for Node { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + let mut buf = Vec::new(); + self.write(&mut buf); + return write!(f, "{}", String::from_utf8_lossy(&buf)); } } pub struct Rope(Rc); -impl Display for Rope { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { - let Rope(n) = self; - return write!(f, "{}", n); - } -} - impl Rope { fn concat(self, Rope(other): Rope) -> Rope { let Rope(me) = self; @@ -94,3 +92,10 @@ impl Rope { return Ok(rope); } } + +impl Display for Rope { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { + let Rope(n) = self; + return write!(f, "{}", n); + } +} -- cgit v1.3.1