Add TextBufferWriter

This commit is contained in:
Matthew Gordon 2025-11-10 13:20:38 -04:00
parent d95ab09180
commit e01210f679
3 changed files with 46 additions and 1 deletions

View File

@ -1,2 +1,2 @@
mod text_buffer;
pub use text_buffer::{TextBuffer, TextBufferReader};
pub use text_buffer::{TextBuffer, TextBufferReader, TextBufferWriter};

View File

@ -7,6 +7,9 @@ pub use rope::{CharIterator, CharWithPointIterator};
mod reader;
pub use reader::TextBufferReader;
mod writer;
pub use writer::TextBufferWriter;
pub struct TextBuffer {
contents: Rc<Rope>,
}

View File

@ -0,0 +1,42 @@
use super::{Point, TextBuffer};
pub struct TextBufferWriter<'a> {
text_buffer: &'a mut TextBuffer,
}
impl<'a> TextBufferWriter<'a> {
pub fn new(text_buffer: &'a mut TextBuffer) -> Self {
Self { text_buffer }
}
}
impl<'a> std::io::Write for TextBufferWriter<'a> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.text_buffer.insert_text(
str::from_utf8(buf).map_err(std::io::Error::other)?,
Point::End,
);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn write_string_into_text_buffer() {
let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
let mut text_buffer = TextBuffer::new();
let mut target = TextBufferWriter::new(&mut text_buffer);
target.write_all(text.as_bytes()).unwrap();
let output_text: String = text_buffer.iter_chars().collect();
assert_eq!(text, output_text);
}
}