use icu_properties::props::{EnumeratedProperty, BidiClass};
use crate::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub enum BidiDetail {
Ltr,
ForceLtr,
Rtl,
ForceAscii,
}
const AL : BidiClass = BidiClass::AL ;
const AN : BidiClass = BidiClass::AN ;
const BN : BidiClass = BidiClass::BN ;
const CS : BidiClass = BidiClass::CS ;
const EN : BidiClass = BidiClass::EN ;
const ES : BidiClass = BidiClass::ES ;
const ET : BidiClass = BidiClass::ET ;
const L : BidiClass = BidiClass::L ;
const NSM : BidiClass = BidiClass::NSM;
const ON : BidiClass = BidiClass::ON ;
const R : BidiClass = BidiClass::R ;
impl BidiDetail {
pub fn join(self, other: Self) -> Self {
match (self, other) {
(Self::Ltr, other) | (other, Self::Ltr) => other,
(Self::Rtl , Self::Rtl ) => Self::Rtl ,
(Self::ForceLtr, Self::ForceLtr) => Self::ForceLtr,
(Self::ForceAscii, _ ) | (_ , Self::ForceAscii) => Self::ForceAscii,
(Self::Rtl , Self::ForceLtr) | (Self::ForceLtr, Self::Rtl ) => Self::ForceAscii,
}
}
pub fn parse(value: &str) -> Self {
if let Some(ret) = Self::parse_ascii(value) {
return ret;
}
Self::parse_unicode(value)
}
pub fn parse_ascii(value: &str) -> Option<Self> {
let (x, mid, y) = match *value.as_bytes() {
[ ] => return Some(Self::Ltr),
[x ] => (x, b"".as_slice(), x),
[x, ref mid @ .., y] => (x, mid , y),
};
let c1 = DOMAIN_BYTE_CLASS_DATA[x as usize] ;
let c2 = mid.iter().fold(0, |acc, &b| acc | DOMAIN_BYTE_CLASS_DATA[b as usize]);
let c3 = DOMAIN_BYTE_CLASS_DATA[y as usize] ;
if (c1 & 0b0010_0000) | (c2 & 0b0100_0000) | (c3 & 0b1000_0000) == 0 {
Some(Self::Ltr)
} else if (c1 | c2 | c3) & 0b0100_0000 == 0 {
Some(Self::ForceLtr)
} else {
None
}
}
pub fn parse_unicode(value: &str) -> Self {
let mut classes = value.chars().map(BidiClass::for_char);
match classes.next() {
Some(R | AL) => {
let mut check3 = true;
let mut has_en = false;
let mut has_an = false;
for c in classes {
match c {
R | AL => check3 = true,
AN => {check3 = true; has_an = true;},
EN => {check3 = true; has_en = true;},
ES | CS | ET | ON | BN => check3 = false,
NSM => {}
_ => return Self::ForceAscii,
}
if has_an && has_en {
return Self::ForceAscii;
}
}
match check3 {
true => Self::Rtl,
false => Self::ForceAscii,
}
},
Some(L) => {
let mut check6 = true;
for c in classes {
match c {
L | EN => check6 = true,
ES | CS | ET | ON | BN => check6 = false,
NSM => {},
_ => return Self::ForceAscii,
}
}
match check6 {
true => Self::Ltr,
false => Self::ForceLtr,
}
},
Some(AN) => Self::ForceAscii,
Some(_) => match classes.any(|c| matches!(c, R | AL | AN)) {
true => Self::ForceAscii,
false => Self::ForceLtr,
},
None => Self::Ltr,
}
}
}
impl FromStr for BidiDetail {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::parse(s))
}
}
impl From<&str> for BidiDetail {
fn from(value: &str) -> Self {
Self::parse(value)
}
}