use crate::grapheme::Graphemes;
use crate::{Ambiguous, Width};
const CJK: Width = Width::DEFAULT.ambiguous(Ambiguous::Wide);
mod private {
pub trait Sealed {}
impl Sealed for str {}
impl Sealed for char {}
}
pub trait UnicodeWidthStr: private::Sealed {
fn width(&self) -> usize;
fn width_cjk(&self) -> usize;
}
impl UnicodeWidthStr for str {
#[inline]
fn width(&self) -> usize {
Width::DEFAULT.of(self)
}
#[inline]
fn width_cjk(&self) -> usize {
CJK.of(self)
}
}
pub trait UnicodeWidthChar: private::Sealed {
fn width(self) -> Option<usize>;
fn width_cjk(self) -> Option<usize>;
}
impl UnicodeWidthChar for char {
#[inline]
fn width(self) -> Option<usize> {
if self.is_control() {
None
} else {
Some(Width::DEFAULT.of_char(self))
}
}
#[inline]
fn width_cjk(self) -> Option<usize> {
if self.is_control() {
None
} else {
Some(CJK.of_char(self))
}
}
}
pub trait UnicodeSegmentation: private::Sealed {
fn graphemes(&self, is_extended: bool) -> Graphemes<'_>;
fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices<'_>;
}
impl UnicodeSegmentation for str {
#[inline]
fn graphemes(&self, is_extended: bool) -> Graphemes<'_> {
if is_extended {
Graphemes::new(self)
} else {
Graphemes::new_legacy(self)
}
}
#[inline]
fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices<'_> {
GraphemeIndices {
inner: self.graphemes(is_extended),
pos: 0,
}
}
}
#[derive(Clone)]
pub struct GraphemeIndices<'a> {
inner: Graphemes<'a>,
pos: usize,
}
impl<'a> Iterator for GraphemeIndices<'a> {
type Item = (usize, &'a str);
fn next(&mut self) -> Option<(usize, &'a str)> {
let cluster = self.inner.next()?;
let at = self.pos;
self.pos += cluster.len();
Some((at, cluster))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl core::iter::FusedIterator for GraphemeIndices<'_> {}