mod unicode;
mod width;
use std::borrow::Cow;
use std::sync::OnceLock;
use crate::string::Error;
const BAD: u32 = u32::MAX;
fn utf8_len(b: u8) -> usize {
match b {
0xC2..=0xDF => 2,
0xE0..=0xEF => 3,
0xF0..=0xF4 => 4,
_ => 1,
}
}
fn is_continuation(b: u8) -> bool {
(0x80..=0xBF).contains(&b)
}
fn decode_one(s: &[u8], pos: &mut usize) -> u32 {
let e = s.len();
let mut p = *pos;
let c = s[p];
p += 1;
let w = if c < 0x80 {
c as u32
} else if c < 0xC2 {
BAD
} else if c <= 0xDF {
if p < e {
let c2 = s[p];
p += 1;
if c2 & 0xC0 != 0x80 {
p -= 1;
BAD
} else {
((c as u32 & 0x1F) << 6) | (c2 as u32 & 0x3F)
}
} else {
BAD
}
} else if c <= 0xEF {
if e - p >= 2 {
let (c2, c3) = (s[p], s[p + 1]);
p += 2;
if c2 & 0xC0 != 0x80 || (c == 0xE0 && c2 < 0xA0) || (c == 0xED && c2 >= 0xA0) {
p -= 2;
BAD
} else if c3 & 0xC0 != 0x80 {
p -= 1;
BAD
} else {
((c as u32 & 0xF) << 12) | ((c2 as u32 & 0x3F) << 6) | (c3 as u32 & 0x3F)
}
} else {
if p < e && (c != 0xE0 || s[p] >= 0xA0) && (c != 0xED || s[p] < 0xA0) && s[p] & 0xC0 == 0x80 {
p += 1;
if p < e && s[p] & 0xC0 == 0x80 {
p += 1;
}
}
BAD
}
} else if c <= 0xF4 {
if e - p >= 3 {
let (c2, c3, c4) = (s[p], s[p + 1], s[p + 2]);
p += 3;
if c2 & 0xC0 != 0x80 || (c == 0xF0 && c2 < 0x90) || (c == 0xF4 && c2 >= 0x90) {
p -= 3;
BAD
} else if c3 & 0xC0 != 0x80 {
p -= 2;
BAD
} else if c4 & 0xC0 != 0x80 {
p -= 1;
BAD
} else {
((c as u32 & 0x7) << 18) | ((c2 as u32 & 0x3F) << 12) | ((c3 as u32 & 0x3F) << 6) | (c4 as u32 & 0x3F)
}
} else {
if p < e {
let c2 = s[p];
if (c == 0xF0 && c2 >= 0x90) || (c == 0xF4 && c2 < 0x90) || (0xF1..=0xF3).contains(&c) {
while p < e && s[p] & 0xC0 == 0x80 {
p += 1;
}
}
}
BAD
}
} else {
BAD
};
*pos = p;
w
}
fn decode(s: &[u8]) -> impl Iterator<Item = u32> + '_ {
let mut pos = 0;
std::iter::from_fn(move || if pos < s.len() { Some(decode_one(s, &mut pos)) } else { None })
}
fn encode(out: &mut Vec<u8>, w: u32, bad: &[u8]) {
if w < 0x80 {
out.push(w as u8);
} else if w < 0x800 {
out.extend_from_slice(&[0xC0 | (w >> 6) as u8, 0x80 | (w & 0x3F) as u8]);
} else if (0xD800..=0xDFFF).contains(&w) {
out.extend_from_slice(bad);
} else if w < 0x10000 {
out.extend_from_slice(&[0xE0 | (w >> 12) as u8, 0x80 | ((w >> 6) & 0x3F) as u8, 0x80 | (w & 0x3F) as u8]);
} else if w < 0x110000 {
out.extend_from_slice(&[
0xF0 | (w >> 18) as u8,
0x80 | ((w >> 12) & 0x3F) as u8,
0x80 | ((w >> 6) & 0x3F) as u8,
0x80 | (w & 0x3F) as u8,
]);
} else {
out.extend_from_slice(bad);
}
}
const SUBSTITUTE: &[u8] = b"?";
fn char_width(w: u32) -> usize {
if !(0x1100..=0x3FFFD).contains(&w) {
return 1;
}
let wide = width::WIDE
.binary_search_by(|&(lo, hi)| {
if hi < w {
std::cmp::Ordering::Less
} else if lo > w {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
})
.is_ok();
if wide { 2 } else { 1 }
}
pub fn mb_strimwidth(s: &[u8], width: usize) -> Cow<'_, [u8]> {
let mut remaining = width;
let mut out = Vec::new();
let mut bad = false;
for w in decode(s) {
let columns = char_width(w);
if remaining < columns {
return Cow::Owned(out);
}
remaining -= columns;
bad |= w == BAD;
encode(&mut out, w, SUBSTITUTE);
}
if bad { Cow::Owned(out) } else { Cow::Borrowed(s) }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Encoding {
#[default]
Utf8,
EightBit,
}
impl Encoding {
pub fn from_name(name: &str) -> Option<Self> {
match name.to_ascii_lowercase().as_str() {
"utf-8" | "utf8" => Some(Encoding::Utf8),
"8bit" | "binary" => Some(Encoding::EightBit),
_ => None,
}
}
}
pub fn mb_strlen(s: &[u8]) -> usize {
let mut pos = 0;
let mut n = 0;
while pos < s.len() {
decode_one(s, &mut pos);
n += 1;
}
n
}
pub fn mb_strlen_in(s: &[u8], encoding: Encoding) -> usize {
match encoding {
Encoding::Utf8 => mb_strlen(s),
Encoding::EightBit => s.len(),
}
}
pub fn mb_check_encoding(s: &[u8]) -> bool {
std::str::from_utf8(s).is_ok()
}
pub fn mb_scrub(s: &[u8]) -> Cow<'_, [u8]> {
if mb_check_encoding(s) {
return Cow::Borrowed(s);
}
let mut out = Vec::with_capacity(s.len());
for w in decode(s) {
encode(&mut out, w, SUBSTITUTE);
}
Cow::Owned(out)
}
fn get_substr(s: &[u8], from: usize, len: usize) -> Vec<u8> {
if len == 0 || from >= s.len() {
return Vec::new();
}
let mut out = Vec::new();
for w in decode(s).skip(from).take(len) {
encode(&mut out, w, SUBSTITUTE);
}
out
}
pub fn mb_substr(s: &[u8], start: i64, length: Option<i64>) -> Result<Vec<u8>, Error> {
let range_error = |n: u32, name: &str| {
Error::argument("mb_substr", n, name, &format!("must be between {} and {}", i64::MIN + 1, i64::MAX))
};
if start == i64::MIN {
return Err(range_error(2, "start"));
}
if length == Some(i64::MIN) {
return Err(range_error(3, "length"));
}
let mblen = if start < 0 || length.is_some_and(|l| l < 0) { mb_strlen(s) } else { 0 };
let from = if start >= 0 {
start as usize
} else if start.unsigned_abs() < mblen as u64 {
mblen - start.unsigned_abs() as usize
} else {
0
};
let len = match length {
None => usize::MAX,
Some(l) if l >= 0 => l as usize,
Some(l) if from < mblen && l.unsigned_abs() < (mblen - from) as u64 => mblen - from - l.unsigned_abs() as usize,
Some(_) => 0,
};
Ok(get_substr(s, from, len))
}
fn lookup(table: &[(u32, u32)], code: u32) -> Option<u32> {
table.binary_search_by_key(&code, |&(k, _)| k).ok().map(|i| table[i].1)
}
fn in_ranges(ranges: &[(u32, u32)], code: u32) -> bool {
match ranges.binary_search_by(|&(lo, _)| lo.cmp(&code)) {
Ok(_) => true,
Err(0) => false,
Err(i) => code <= ranges[i - 1].1,
}
}
fn is_cased(w: u32) -> bool {
in_ranges(unicode::CASED, w)
}
fn is_case_ignorable(w: u32) -> bool {
in_ranges(unicode::CASE_IGNORABLE, w)
}
fn tolower_raw(code: u32) -> u32 {
if code < 0xC0 {
if (0x41..=0x5A).contains(&code) { code + 0x20 } else { code }
} else {
lookup(unicode::LOWER, code).unwrap_or(code)
}
}
fn emit(raw: u32, out: &mut [u32; 192], p: &mut usize) {
if raw > 0xFFFFFF {
let len = (raw >> 24) as usize;
let at = (raw & 0xFFFFFF) as usize;
for &w in &unicode::EXTRA[at + 1..=at + len] {
out[*p] = w;
*p += 1;
}
} else {
out[*p] = raw;
*p += 1;
}
}
fn scan_ahead_for_cased(s: &[u8], mut pos: usize) -> bool {
while pos < s.len() {
let w = decode_one(s, &mut pos);
if is_cased(w) {
return true;
}
if !is_case_ignorable(w) {
return false;
}
}
false
}
fn scan_back_for_cased(converted: &[u32; 192], begin: usize, end: Option<usize>) -> bool {
let Some(mut e) = end else { return false };
while e > begin {
e -= 1;
let w = converted[e];
if is_cased(w) {
return true;
}
if !is_case_ignorable(w) {
return false;
}
}
false
}
fn is_final_sigma(
wbuf: &[u32],
i: usize,
s: &[u8],
pos: usize,
converted: &[u32; 192],
p: usize,
converted_end: Option<usize>,
) -> bool {
let mut j = i as isize - 1;
while j >= 0 && is_case_ignorable(wbuf[j as usize]) {
j -= 1;
}
let before = if j >= 0 { is_cased(wbuf[j as usize]) } else { scan_back_for_cased(converted, p, converted_end) };
if !before {
return false;
}
let mut j = i + 1;
while j < wbuf.len() && is_case_ignorable(wbuf[j]) {
j += 1;
}
if j >= wbuf.len() { !scan_ahead_for_cased(s, pos) } else { !is_cased(wbuf[j]) }
}
fn convert_case(s: &[u8], bad: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len() + 1);
let mut converted = [0u32; 192];
let mut converted_end: Option<usize> = None;
let mut pos = 0;
let mut wbuf = [0u32; 64];
while pos < s.len() {
let mut n = 0;
while pos < s.len() && n < 64 {
wbuf[n] = decode_one(s, &mut pos);
n += 1;
}
let w_in = &wbuf[..n];
let mut p = 0;
for (i, &w) in w_in.iter().enumerate() {
if w > 0xFFFFFF {
converted[p] = w;
p += 1;
continue;
}
if w == 0x3A3 && is_final_sigma(w_in, i, s, pos, &converted, p, converted_end) {
converted[p] = 0x3C2;
p += 1;
} else {
emit(tolower_raw(w), &mut converted, &mut p);
}
}
converted_end = Some(p);
for &w in &converted[..p] {
encode(&mut out, w, bad);
}
}
out
}
pub fn mb_strtolower(s: &[u8]) -> Vec<u8> {
map_case(s).unwrap_or_else(|| convert_case(s, SUBSTITUTE))
}
fn map_case(s: &[u8]) -> Option<Vec<u8>> {
const DIRECT: usize = 0x600;
static TABLE: OnceLock<Vec<u32>> = OnceLock::new();
let direct = TABLE.get_or_init(|| (0..DIRECT as u32).map(tolower_raw).collect());
let mut out = Vec::with_capacity(s.len() + s.len() / 4 + 1);
let mut pos = 0;
while pos < s.len() {
let run = s[pos..].iter().position(|&c| c >= 0x80).map_or(s.len(), |n| pos + n);
out.extend(s[pos..run].iter().map(u8::to_ascii_lowercase));
pos = run;
if pos == s.len() {
break;
}
let w = decode_one(s, &mut pos);
if w > 0xFFFFFF {
encode(&mut out, w, SUBSTITUTE);
continue;
}
if w == 0x3A3 {
return None;
}
let raw = direct.get(w as usize).copied().unwrap_or_else(|| tolower_raw(w));
if raw > 0xFFFFFF {
let len = (raw >> 24) as usize;
let at = (raw & 0xFFFFFF) as usize;
for &w in &unicode::EXTRA[at + 1..=at + len] {
encode(&mut out, w, SUBSTITUTE);
}
} else {
encode(&mut out, raw, SUBSTITUTE);
}
}
Some(out)
}
fn offset_to_pointer(s: &[u8], offset: i64) -> Option<usize> {
if offset < 0 {
let mut pos = s.len();
let mut offset = offset;
while offset < 0 {
if pos == 0 {
return None;
}
pos -= 1;
if !is_continuation(s[pos]) {
offset += 1;
}
}
Some(pos)
} else {
let mut pos = 0;
let mut offset = offset;
while offset > 0 {
if pos >= s.len() {
return None;
}
pos += utf8_len(s[pos]);
offset -= 1;
}
Some(pos.min(s.len()))
}
}
fn pointer_to_offset(s: &[u8], pos: usize) -> usize {
s[..pos].iter().filter(|&&b| !is_continuation(b)).count()
}
fn find_strpos(function: &str, h: &[u8], n: &[u8], offset: i64, reverse: bool) -> Result<Option<usize>, Error> {
let op = offset_to_pointer(h, offset)
.ok_or_else(|| Error::argument(function, 3, "offset", "must be contained in argument #1 ($haystack)"))?;
if h.len() < n.len() {
return Ok(None);
}
let found = if !reverse {
crate::string::find(&h[op..], n).map(|i| i + op)
} else if offset >= 0 {
crate::string::rfind(&h[op..], n).map(|i| i + op)
} else {
let needle_chars = pointer_to_offset(n, n.len());
let end = offset_to_pointer(&h[op..], needle_chars as i64).map_or(h.len(), |e| op + e);
crate::string::rfind(&h[..end], n)
};
Ok(found.map(|p| pointer_to_offset(h, p)))
}
pub fn mb_strpos(haystack: &[u8], needle: &[u8], offset: i64) -> Result<Option<usize>, Error> {
find_strpos("mb_strpos", haystack, needle, offset, false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counts_invalid_sequences() {
assert_eq!(mb_strlen("héllo".as_bytes()), 5);
assert_eq!(mb_strlen(b"\xE2\x82"), 1);
assert_eq!(mb_strlen(b"\xF0\x9F\x98\x80\x80"), 2);
}
#[test]
fn cases_like_php() {
assert_eq!(mb_strtolower(b"A\xFFB\xE2\x82"), b"a?b?");
assert_eq!(mb_strtolower("ΣΑΣ.Σ".as_bytes()), "σασ.ς".as_bytes());
}
#[test]
fn substr_and_split() {
assert_eq!(mb_substr(b"a\xFFbc", 1, Some(2)).unwrap(), b"?b");
}
}