use std::fmt;
use std::sync::{Arc, LazyLock, OnceLock};
use regex_syntax::hir::{Class, HirKind};
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;
use crate::error::StructureError;
use crate::int::Int;
use crate::tree::{self, Along, Measure, Node, Shape};
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, Default)]
pub struct Text {
root: Option<Node<Run>>,
flat: Option<Arc<OnceLock<Arc<str>>>>,
}
#[derive(Clone, Debug)]
pub struct Run {
block: Block,
from: usize,
to: usize,
length: usize,
places: OnceLock<Places>,
}
#[derive(Clone, Debug)]
struct Places {
starts: Arc<[usize]>,
first: usize,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Span {
bytes: usize,
length: usize,
}
impl Measure for Span {
const EMPTY: Span = Span {
bytes: 0,
length: 0,
};
fn join(self, other: Span) -> Span {
Span {
bytes: self.bytes + other.bytes,
length: self.length + other.length,
}
}
}
const SHORT: usize = 64;
const STRIDE: usize = 64;
#[cfg(test)]
thread_local! {
pub(crate) static WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn walked(count: usize) {
#[cfg(test)]
WALKED.with(|walked| walked.set(walked.get() + count));
#[cfg(not(test))]
let _ = count;
}
impl Run {
fn new(block: Block, from: usize, to: usize, length: usize) -> Run {
Run {
block,
from,
to,
length,
places: OnceLock::new(),
}
}
fn whole(utf8: Arc<str>) -> Run {
let length = utf8.chars().count();
let to = utf8.len();
Run::new(Block(utf8), 0, to, length)
}
pub fn block(&self) -> &Block {
&self.block
}
pub fn from(&self) -> usize {
self.from
}
pub fn to(&self) -> usize {
self.to
}
pub fn as_str(&self) -> &str {
&self.block.0[self.from..self.to]
}
pub(crate) fn span(&self) -> Span {
Span {
bytes: self.to - self.from,
length: self.length,
}
}
fn piece(&self, from: usize, to: usize, skipped: usize, length: usize) -> Run {
let places = self.places.get().map(|places| Places {
starts: Arc::clone(&places.starts),
first: places.first + skipped,
});
Run {
block: self.block.clone(),
from: self.from + from,
to: self.from + to,
length,
places: places.map_or_else(OnceLock::new, OnceLock::from),
}
}
fn offset(&self, position: usize) -> usize {
let text = self.as_str();
if self.length == text.len() {
return position;
}
let places = self.places.get_or_init(|| {
walked(self.length);
Places {
starts: text
.char_indices()
.step_by(STRIDE)
.map(|(at, _)| self.from + at)
.collect(),
first: 0,
}
});
let at = places.first + position;
let Some(&near) = places.starts.get(at / STRIDE) else {
return text.len();
};
walked(at % STRIDE);
let block = self.block.as_str();
block[near..]
.char_indices()
.nth(at % STRIDE)
.map_or(self.to, |(found, _)| near + found)
- self.from
}
}
struct ByByte;
impl Along<Run> for ByByte {
fn node(&self, tree: &Node<Run>) -> usize {
tree.measure().bytes
}
fn item(&self, run: &Run) -> usize {
run.span().bytes
}
fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
let length = run.as_str().get(..at)?.chars().count();
Some((
run.piece(0, at, 0, length),
run.piece(at, run.span().bytes, length, run.length - length),
))
}
}
struct ByCodePoint;
impl Along<Run> for ByCodePoint {
fn node(&self, tree: &Node<Run>) -> usize {
tree.measure().length
}
fn item(&self, run: &Run) -> usize {
run.span().length
}
fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
let middle = run.offset(at);
Some((
run.piece(0, middle, 0, at),
run.piece(middle, run.span().bytes, at, run.length - at),
))
}
}
impl Text {
pub fn new(code_points: &str) -> Self {
Text::whole(Arc::from(code_points))
}
fn whole(utf8: Arc<str>) -> Self {
Text::of_run(Run::whole(utf8))
}
fn of_run(run: Run) -> Self {
Text::of((run.from < run.to).then(|| tree::leaf(vec![run])))
}
fn of(root: Option<Node<Run>>) -> Self {
let flat = root
.as_ref()
.is_some_and(|root| root.len() > 1)
.then(|| Arc::new(OnceLock::new()));
Text { root, flat }
}
pub fn root(&self) -> Option<&Node<Run>> {
self.root.as_ref()
}
pub fn run(&self) -> Option<&Run> {
match self.root.as_ref()?.shape() {
Shape::Leaf([run]) => Some(run),
Shape::Leaf(_) | Shape::Branch(..) => None,
}
}
fn span(&self) -> Span {
self.root.as_ref().map_or(Span::EMPTY, Node::measure)
}
pub fn as_str(&self) -> &str {
match (&self.flat, self.run()) {
(Some(flat), _) => self.flat(flat),
(None, Some(run)) => run.as_str(),
(None, None) => "",
}
}
fn flat<'a>(&self, flat: &'a OnceLock<Arc<str>>) -> &'a Arc<str> {
flat.get_or_init(|| Arc::from(self.blocks().collect::<String>()))
}
pub fn to_shared(&self) -> Arc<str> {
match (&self.flat, self.run()) {
(Some(flat), _) => Arc::clone(self.flat(flat)),
(None, Some(run)) if run.from == 0 && run.to == run.block.len() => {
Arc::clone(&run.block.0)
}
(None, Some(run)) => Arc::from(run.as_str()),
(None, None) => Arc::from(""),
}
}
pub fn blocks(&self) -> impl Iterator<Item = &str> {
let count = self.root.as_ref().map_or(0, Node::len);
tree::Iter::new(self.root.as_ref(), 0, count).map(Run::as_str)
}
pub fn len(&self) -> usize {
self.span().length
}
pub fn is_empty(&self) -> bool {
self.root.is_none()
}
pub fn byte_len(&self) -> usize {
self.span().bytes
}
pub fn of_block(block: Block, from: usize, to: usize) -> Result<Text, StructureError> {
let length = block
.0
.get(from..to)
.ok_or(StructureError::Run)?
.chars()
.count();
Ok(Text::of_run(Run::new(block, from, to, length)))
}
pub fn join_shared(left: Text, right: Text) -> Text {
match (left.root, right.root) {
(Some(left), Some(right)) => Text::of(Some(Node::branch(left, right))),
(left, right) => Text::of(left.or(right)),
}
}
pub fn byte_window(&self, from: usize, to: usize) -> Result<Text, StructureError> {
if from > to || to > self.byte_len() {
return Err(StructureError::Run);
}
self.part(from, to, &ByByte).ok_or(StructureError::Run)
}
pub(crate) fn id(&self) -> usize {
self.root.as_ref().map_or(0, Node::id)
}
#[must_use]
pub fn concat(&self, other: &Text) -> Text {
let (Some(left), Some(right)) = (&self.root, &other.root) else {
return if other.is_empty() {
self.clone()
} else {
other.clone()
};
};
let short = |left: &Node<Run>, right: &Node<Run>| {
(left.measure().bytes + right.measure().bytes <= SHORT).then(|| {
let copied = format!("{}{}", Text::from(left.clone()), Text::from(right.clone()));
tree::leaf(vec![Run::whole(Arc::from(copied))])
})
};
Text::of(Some(tree::join_with(left.clone(), right.clone(), &short)))
}
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.len() {
return None;
}
self.part(start, end, &ByCodePoint)
}
fn part(&self, start: usize, end: usize, along: &impl Along<Run>) -> Option<Text> {
let Some(root) = &self.root else {
return Some(Text::default());
};
if start == 0 && end == along.node(root) {
return Some(self.clone());
}
let (_, rest) = tree::cut(root.clone(), start, along)?;
let Some(rest) = rest else {
return Some(Text::default());
};
Some(Text::of(tree::cut(rest, end - start, along)?.0))
}
pub fn find_from(&self, needle: &Text, from: &Int) -> Option<usize> {
let from = from.to_index()?;
if from > self.len() {
return None;
}
let start = self.part(0, from, &ByCodePoint)?.byte_len();
let rest = &self.as_str()[start..];
let at = rest.find(needle.as_str())?;
Some(from + rest[..at].chars().count())
}
pub fn code_points(&self) -> Vec<Text> {
self.blocks()
.flat_map(str::chars)
.map(|code_point| Text::new(code_point.encode_utf8(&mut [0; 4])))
.collect()
}
pub fn graphemes(&self) -> Vec<Text> {
self.as_str().graphemes(true).map(Text::new).collect()
}
#[must_use]
pub fn normalize(&self) -> Text {
Text::from(self.blocks().flat_map(str::chars).nfc().collect::<String>())
}
#[must_use]
pub fn lowercase(&self) -> Text {
let utf8 = self.as_str();
let mut out = String::with_capacity(utf8.len());
for (at, code_point) in utf8.char_indices() {
if code_point == CAPITAL_SIGMA
&& after_a_cased_letter(&utf8[..at])
&& !before_a_cased_letter(&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.byte_len());
for code_point in self.blocks().flat_map(str::chars) {
push_mapped(
&mut out,
code_point,
&unicode_case_mapping::to_uppercase(code_point),
);
}
Text::from(out)
}
#[cfg(test)]
pub(crate) fn block_of(&self) -> Option<&Arc<str>> {
self.run().map(|run| &run.block.0)
}
pub fn to_bytes(&self) -> Bytes {
Bytes::new(self.as_str().as_bytes())
}
}
#[derive(Clone, Debug)]
pub struct Block(Arc<str>);
impl Block {
pub fn new(utf8: Arc<str>) -> Block {
Block(utf8)
}
pub fn id(&self) -> usize {
Arc::as_ptr(&self.0).cast::<u8>().addr()
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl PartialEq for Text {
fn eq(&self, other: &Text) -> bool {
self.id() == other.id()
|| (self.byte_len() == other.byte_len() && self.as_str() == other.as_str())
}
}
impl Eq for Text {}
impl PartialOrd for Text {
fn partial_cmp(&self, other: &Text) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Text {
fn cmp(&self, other: &Text) -> std::cmp::Ordering {
if self.id() == other.id() {
return std::cmp::Ordering::Equal;
}
self.as_str().cmp(other.as_str())
}
}
impl From<String> for Text {
fn from(code_points: String) -> Self {
Text::whole(Arc::from(code_points))
}
}
impl From<Node<Run>> for Text {
fn from(root: Node<Run>) -> Self {
Text::of(Some(root))
}
}
impl fmt::Display for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.blocks().try_for_each(|block| f.write_str(block))
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), 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(crate) fn id(&self) -> usize {
Arc::as_ptr(&self.0).cast::<u8>().addr()
}
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[usize::from(((group >> shift) & 0x3f).to_le_bytes()[0])])
};
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())
}
}