diff --git a/core/src/lib.rs b/core/src/lib.rs index f3bfd10..7b4afd1 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -1,2 +1,2 @@ mod text_buffer; -pub use text_buffer::{TextBuffer, TextBufferReader}; +pub use text_buffer::{TextBuffer, TextBufferReader, TextBufferWriter}; diff --git a/core/src/text_buffer/mod.rs b/core/src/text_buffer/mod.rs index 937b9fc..cce7d14 100644 --- a/core/src/text_buffer/mod.rs +++ b/core/src/text_buffer/mod.rs @@ -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, } diff --git a/core/src/text_buffer/writer.rs b/core/src/text_buffer/writer.rs new file mode 100644 index 0000000..1f1dcf4 --- /dev/null +++ b/core/src/text_buffer/writer.rs @@ -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 { + 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); + } +}