1use unicode_bidi::{BidiInfo, ParagraphInfo};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ParagraphDirection {
19 LeftToRight,
21 RightToLeft,
23 Neutral,
25}
26
27#[must_use]
30pub fn paragraph_direction(text: &str) -> ParagraphDirection {
31 let info = BidiInfo::new(text, None);
32 if info.paragraphs.is_empty() {
33 return ParagraphDirection::Neutral;
34 }
35 let p: &ParagraphInfo = &info.paragraphs[0];
36 let level = p.level;
37 if level.is_rtl() {
38 ParagraphDirection::RightToLeft
39 } else if has_strong_ltr(text) {
40 ParagraphDirection::LeftToRight
41 } else {
42 ParagraphDirection::Neutral
43 }
44}
45
46#[must_use]
50pub fn level_at(text: &str, byte_offset: usize) -> Option<u8> {
51 if byte_offset > text.len() {
52 return None;
53 }
54 let info = BidiInfo::new(text, None);
55 info.levels.get(byte_offset).map(|l| l.number())
56}
57
58fn has_strong_ltr(text: &str) -> bool {
59 text.chars().any(|c| {
60 let class = unicode_bidi::bidi_class(c);
61 matches!(class, unicode_bidi::BidiClass::L)
62 })
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn empty_string_is_neutral() {
71 assert_eq!(paragraph_direction(""), ParagraphDirection::Neutral);
72 }
73
74 #[test]
75 fn pure_ascii_is_ltr() {
76 assert_eq!(
77 paragraph_direction("hello"),
78 ParagraphDirection::LeftToRight
79 );
80 }
81
82 #[test]
83 fn arabic_paragraph_is_rtl() {
84 assert_eq!(
86 paragraph_direction("مرحبا"),
87 ParagraphDirection::RightToLeft
88 );
89 }
90
91 #[test]
92 fn level_at_returns_run_level() {
93 let text = "hello مرحبا";
94 assert_eq!(level_at(text, 0), Some(0));
96 let arabic_byte = text.find('م').unwrap();
98 let level = level_at(text, arabic_byte).unwrap();
99 assert!(level % 2 == 1, "expected RTL level, got {level}");
100 }
101
102 #[test]
103 fn out_of_bounds_returns_none() {
104 assert_eq!(level_at("abc", 999), None);
105 }
106}