1// SPDX-License-Identifier: MIT OR Apache-2.0
23use unicode_bidi::{bidi_class, BidiClass, BidiInfo, ParagraphInfo};
45/// An iterator over the paragraphs in the input text.
6/// It is equivalent to [`core::str::Lines`] but follows `unicode-bidi` behaviour.
7#[derive(Debug)]
8pub struct BidiParagraphs<'text> {
9 text: &'text str,
10 info: alloc::vec::IntoIter<ParagraphInfo>,
11}
1213impl<'text> BidiParagraphs<'text> {
14/// Create an iterator to split the input text into paragraphs
15 /// in accordance with `unicode-bidi` behaviour.
16pub fn new(text: &'text str) -> Self {
17let info = BidiInfo::new(text, None);
18let info = info.paragraphs.into_iter();
19Self { text, info }
20 }
21}
2223impl<'text> Iterator for BidiParagraphs<'text> {
24type Item = &'text str;
2526fn next(&mut self) -> Option<Self::Item> {
27let para = self.info.next()?;
28let paragraph = &self.text[para.range];
29// `para.range` includes the newline that splits the line, so remove it if present
30let mut char_indices = paragraph.char_indices();
31if let Some(i) = char_indices.next_back().and_then(|(i, c)| {
32// `BidiClass::B` is a Paragraph_Separator (various newline characters)
33(bidi_class(c) == BidiClass::B).then_some(i)
34 }) {
35Some(¶graph[0..i])
36 } else {
37Some(paragraph)
38 }
39 }
40}