use std::fmt;
use std::sync::{Arc, LazyLock};
use regex_syntax::hir::{Class, HirKind};
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;
use crate::int::Int;
pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);
const CAPITAL_SIGMA: char = '\u{3a3}';
const FINAL_SIGMA: char = '\u{3c2}';
static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));
static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));
fn property(name: &str) -> Vec<(char, char)> {
let class = regex_syntax::Parser::new()
.parse(&format!(r"\p{{{name}}}"))
.map(regex_syntax::hir::Hir::into_kind);
match class {
Ok(HirKind::Class(Class::Unicode(class))) => class
.ranges()
.iter()
.map(|range| (range.start(), range.end()))
.collect(),
_ => unreachable!("regex-syntax knows the binary property {name}"),
}
}
fn has(ranges: &[(char, char)], code_point: char) -> bool {
ranges
.binary_search_by(|&(start, end)| {
if end < code_point {
std::cmp::Ordering::Less
} else if start > code_point {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
})
.is_ok()
}
fn after_a_cased_letter(before: &str) -> bool {
for code_point in before.chars().rev() {
if has(&CASED, code_point) {
return true;
}
if !has(&CASE_IGNORABLE, code_point) {
return false;
}
}
false
}
fn before_a_cased_letter(after: &str) -> bool {
for code_point in after.chars() {
if has(&CASED, code_point) {
return true;
}
if !has(&CASE_IGNORABLE, code_point) {
return false;
}
}
false
}
fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
if mapped[0] == 0 {
out.push(code_point);
} else {
out.extend(
mapped
.iter()
.take_while(|&&unit| unit != 0)
.filter_map(|&unit| char::from_u32(unit)),
);
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Text {
utf8: Arc<str>,
length: usize,
}
impl Text {
pub fn new(code_points: &str) -> Self {
Text {
utf8: Arc::from(code_points),
length: code_points.chars().count(),
}
}
pub fn as_str(&self) -> &str {
&self.utf8
}
pub fn len(&self) -> usize {
self.length
}
pub fn is_empty(&self) -> bool {
self.length == 0
}
#[must_use]
pub fn concat(&self, other: &Text) -> Text {
let mut joined = String::from(&*self.utf8);
joined.push_str(&other.utf8);
Text {
utf8: Arc::from(joined),
length: self.length + other.length,
}
}
pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
let start = start.to_index()?;
let end = end.to_index()?;
if start > end || end > self.length {
return None;
}
let from = self.byte_offset(start);
let to = self.byte_offset(end);
Some(Text {
utf8: Arc::from(&self.utf8[from..to]),
length: end - start,
})
}
pub fn code_points(&self) -> Vec<Text> {
let mut buffer = [0; 4];
self.utf8
.chars()
.map(|code_point| Text {
utf8: Arc::from(&*code_point.encode_utf8(&mut buffer)),
length: 1,
})
.collect()
}
pub fn graphemes(&self) -> Vec<Text> {
self.utf8.graphemes(true).map(Text::new).collect()
}
#[must_use]
pub fn normalize(&self) -> Text {
Text::from(self.utf8.nfc().collect::<String>())
}
#[must_use]
pub fn lowercase(&self) -> Text {
let mut out = String::with_capacity(self.utf8.len());
for (at, code_point) in self.utf8.char_indices() {
if code_point == CAPITAL_SIGMA
&& after_a_cased_letter(&self.utf8[..at])
&& !before_a_cased_letter(&self.utf8[at + CAPITAL_SIGMA.len_utf8()..])
{
out.push(FINAL_SIGMA);
} else {
push_mapped(
&mut out,
code_point,
&unicode_case_mapping::to_lowercase(code_point),
);
}
}
Text::from(out)
}
#[must_use]
pub fn uppercase(&self) -> Text {
let mut out = String::with_capacity(self.utf8.len());
for code_point in self.utf8.chars() {
push_mapped(
&mut out,
code_point,
&unicode_case_mapping::to_uppercase(code_point),
);
}
Text::from(out)
}
pub fn byte_len(&self) -> usize {
self.utf8.len()
}
pub fn to_bytes(&self) -> Bytes {
Bytes::new(self.utf8.as_bytes())
}
fn byte_offset(&self, position: usize) -> usize {
if self.length == self.utf8.len() {
return position;
}
self.utf8
.char_indices()
.nth(position)
.map_or(self.utf8.len(), |(offset, _)| offset)
}
}
impl From<String> for Text {
fn from(code_points: String) -> Self {
let length = code_points.chars().count();
Text {
utf8: Arc::from(code_points),
length,
}
}
}
impl fmt::Display for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.utf8)
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&*self.utf8, f)
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Bytes(Arc<[u8]>);
impl Bytes {
pub fn new(contents: &[u8]) -> Self {
Bytes(Arc::from(contents))
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn to_text(&self) -> Option<Text> {
std::str::from_utf8(&self.0).ok().map(Text::new)
}
pub fn to_base64(&self) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
for chunk in self.0.chunks(3) {
let first = chunk[0];
let second = chunk.get(1).copied();
let third = chunk.get(2).copied();
let group = (u32::from(first) << 16)
+ (u32::from(second.unwrap_or(0)) << 8)
+ u32::from(third.unwrap_or(0));
let sextet = |shift: u32| char::from(ALPHABET[((group >> shift) & 0x3f) as usize]);
out.push(sextet(18));
out.push(sextet(12));
out.push(second.map_or('=', |_| sextet(6)));
out.push(third.map_or('=', |_| sextet(0)));
}
out
}
}
impl From<Vec<u8>> for Bytes {
fn from(contents: Vec<u8>) -> Self {
Bytes(Arc::from(contents))
}
}
impl fmt::Debug for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "bytes({})", self.to_base64())
}
}