diff --git a/README.md b/README.md index c94d58e..78d86ea 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,14 @@ let mut text: String = ...; let mut textarea = TextARea::from(text.lines()); ``` +`TextArea` also implements `FromIterator>`. `Iterator::collect()` can collect strings as an editor +instance. This allows to create `TextArea` reading lines from file efficiently using `io::BufReader`. + +```rust +let file = fs::File::open(path)?; +let mut textarea: TextArea = io::BufReader::new(file).lines().collect::>()?; +``` + ### Get text contents from `TextArea` `TextArea::lines()` returns text lines as `&[String]`. It borrows text contents temporarily. diff --git a/src/textarea.rs b/src/textarea.rs index 4cbf6cb..b3dc739 100644 --- a/src/textarea.rs +++ b/src/textarea.rs @@ -77,6 +77,26 @@ where } } +/// Collect line texts from iterator as [`TextArea`]. It is useful when creating a textarea with text read from a file. +/// [`Iterator::collect`] handles errors which may happen on reading each lines. The following example reads text from +/// a file efficiently line-by-line. +/// ```no_run +/// use std::fs; +/// use std::io::{self, BufRead}; +/// use std::path::Path; +/// use tui_textarea::TextArea; +/// +/// fn read_from_file<'a>(path: impl AsRef) -> io::Result> { +/// let file = fs::File::open(path.as_ref())?; +/// io::BufReader::new(file).lines().collect() +/// } +/// ``` +impl<'a, S: Into> FromIterator for TextArea<'a> { + fn from_iter>(iter: I) -> Self { + iter.into() + } +} + impl<'a> Default for TextArea<'a> { /// Create [`TextArea`] instance with empty text content. /// ```