Skip to main content

php_std/
mb.rs

1//! Multibyte (mbstring) functions on UTF-8.
2//!
3//! Ported from PHP 8.5.11's `ext/mbstring` for the UTF-8 encoding (PHP's
4//! default internal encoding), including its handling of invalid UTF-8:
5//! the decoder turns each invalid sequence into one error marker (one
6//! "character" for `mb_strlen`), and functions that re-encode text write
7//! `?` (`mbstring.substitute_character`'s default) for it. Some functions
8//! work on bytes and never re-encode (`mb_strpos`); each function's docs say
9//! which.
10//!
11//! Lower-casing uses PHP's own Unicode tables ([`unicode`], generated from
12//! `unicode_data.h`), with PHP's final sigma rule.
13//!
14//! | PHP | Rust |
15//! |---|---|
16//! | `mb_strlen` | [`mb_strlen`], [`mb_strlen_in`] with [`Encoding`] (`'8bit'`) |
17//! | `mb_substr` | [`mb_substr`] |
18//! | `mb_strtolower` | [`mb_strtolower`] |
19//! | `mb_strpos` | [`mb_strpos`] |
20//! | `mb_check_encoding`, `mb_scrub`, `mb_convert_encoding($s, 'UTF-8')` | [`mb_check_encoding`], [`mb_scrub`] |
21//! | `mb_strimwidth($s, 0, $width)` | [`mb_strimwidth`] |
22//!
23//! # Unicode data
24//!
25//! `mb/unicode.rs` is generated by `data/unicode.py` from php-src's
26//! `ext/mbstring/unicode_data.h` at tag `php-8.5.11`: the lower case table
27//! (`_uccase_lower_table`, sorted by code point), `_uccase_extra_table`, and
28//! the `UC_CASED` and `UC_CASE_IGNORABLE` ranges of `_ucprop_ranges`.
29//! Regenerate it when PHP updates its Unicode version.
30
31mod unicode;
32mod width;
33
34use std::borrow::Cow;
35use std::sync::OnceLock;
36
37use crate::string::Error;
38
39/// mbstring's error marker for an invalid byte sequence (`MBFL_BAD_INPUT`).
40const BAD: u32 = u32::MAX;
41
42/// `mblen_table_utf8`: the length a lead byte announces (1 for anything else).
43fn utf8_len(b: u8) -> usize {
44    match b {
45        0xC2..=0xDF => 2,
46        0xE0..=0xEF => 3,
47        0xF0..=0xF4 => 4,
48        _ => 1,
49    }
50}
51
52fn is_continuation(b: u8) -> bool {
53    (0x80..=0xBF).contains(&b)
54}
55
56/// `mb_utf8_to_wchar` for one code point: decodes at `*pos` and advances;
57/// an invalid sequence yields [`BAD`] and consumes what PHP consumes.
58fn decode_one(s: &[u8], pos: &mut usize) -> u32 {
59    let e = s.len();
60    let mut p = *pos;
61    let c = s[p];
62    p += 1;
63    let w = if c < 0x80 {
64        c as u32
65    } else if c < 0xC2 {
66        BAD
67    } else if c <= 0xDF {
68        if p < e {
69            let c2 = s[p];
70            p += 1;
71            if c2 & 0xC0 != 0x80 {
72                p -= 1;
73                BAD
74            } else {
75                ((c as u32 & 0x1F) << 6) | (c2 as u32 & 0x3F)
76            }
77        } else {
78            BAD
79        }
80    } else if c <= 0xEF {
81        if e - p >= 2 {
82            let (c2, c3) = (s[p], s[p + 1]);
83            p += 2;
84            if c2 & 0xC0 != 0x80 || (c == 0xE0 && c2 < 0xA0) || (c == 0xED && c2 >= 0xA0) {
85                p -= 2;
86                BAD
87            } else if c3 & 0xC0 != 0x80 {
88                p -= 1;
89                BAD
90            } else {
91                ((c as u32 & 0xF) << 12) | ((c2 as u32 & 0x3F) << 6) | (c3 as u32 & 0x3F)
92            }
93        } else {
94            if p < e && (c != 0xE0 || s[p] >= 0xA0) && (c != 0xED || s[p] < 0xA0) && s[p] & 0xC0 == 0x80 {
95                p += 1;
96                if p < e && s[p] & 0xC0 == 0x80 {
97                    p += 1;
98                }
99            }
100            BAD
101        }
102    } else if c <= 0xF4 {
103        if e - p >= 3 {
104            let (c2, c3, c4) = (s[p], s[p + 1], s[p + 2]);
105            p += 3;
106            if c2 & 0xC0 != 0x80 || (c == 0xF0 && c2 < 0x90) || (c == 0xF4 && c2 >= 0x90) {
107                p -= 3;
108                BAD
109            } else if c3 & 0xC0 != 0x80 {
110                p -= 2;
111                BAD
112            } else if c4 & 0xC0 != 0x80 {
113                p -= 1;
114                BAD
115            } else {
116                ((c as u32 & 0x7) << 18) | ((c2 as u32 & 0x3F) << 12) | ((c3 as u32 & 0x3F) << 6) | (c4 as u32 & 0x3F)
117            }
118        } else {
119            if p < e {
120                let c2 = s[p];
121                if (c == 0xF0 && c2 >= 0x90) || (c == 0xF4 && c2 < 0x90) || (0xF1..=0xF3).contains(&c) {
122                    while p < e && s[p] & 0xC0 == 0x80 {
123                        p += 1;
124                    }
125                }
126            }
127            BAD
128        }
129    } else {
130        BAD
131    };
132    *pos = p;
133    w
134}
135
136/// The code points (and error markers) of `s`, as mbstring decodes UTF-8.
137fn decode(s: &[u8]) -> impl Iterator<Item = u32> + '_ {
138    let mut pos = 0;
139    std::iter::from_fn(move || if pos < s.len() { Some(decode_one(s, &mut pos)) } else { None })
140}
141
142/// `mb_wchar_to_utf8`: appends `w`, or `bad` for an error marker, a
143/// surrogate (an error since PHP 8.5.12; php-std never uses the internal
144/// BADUTF8 mode that keeps them) or a value beyond U+10FFFF.
145fn encode(out: &mut Vec<u8>, w: u32, bad: &[u8]) {
146    if w < 0x80 {
147        out.push(w as u8);
148    } else if w < 0x800 {
149        out.extend_from_slice(&[0xC0 | (w >> 6) as u8, 0x80 | (w & 0x3F) as u8]);
150    } else if (0xD800..=0xDFFF).contains(&w) {
151        out.extend_from_slice(bad);
152    } else if w < 0x10000 {
153        out.extend_from_slice(&[0xE0 | (w >> 12) as u8, 0x80 | ((w >> 6) & 0x3F) as u8, 0x80 | (w & 0x3F) as u8]);
154    } else if w < 0x110000 {
155        out.extend_from_slice(&[
156            0xF0 | (w >> 18) as u8,
157            0x80 | ((w >> 12) & 0x3F) as u8,
158            0x80 | ((w >> 6) & 0x3F) as u8,
159            0x80 | (w & 0x3F) as u8,
160        ]);
161    } else {
162        out.extend_from_slice(bad);
163    }
164}
165
166/// What PHP writes for an invalid sequence when it re-encodes text.
167const SUBSTITUTE: &[u8] = b"?";
168
169/// How many columns mbstring gives a character: 2 in its East Asian Width
170/// table ([`width::WIDE`]), 1 otherwise (error markers included).
171fn char_width(w: u32) -> usize {
172    if !(0x1100..=0x3FFFD).contains(&w) {
173        return 1;
174    }
175    let wide = width::WIDE
176        .binary_search_by(|&(lo, hi)| {
177            if hi < w {
178                std::cmp::Ordering::Less
179            } else if lo > w {
180                std::cmp::Ordering::Greater
181            } else {
182                std::cmp::Ordering::Equal
183            }
184        })
185        .is_ok();
186    if wide { 2 } else { 1 }
187}
188
189/// PHP `mb_strimwidth($string, 0, $width)` (no trim marker): the longest
190/// leading part of the string that fits in `width` columns. A string that
191/// fits is returned as it is, except that invalid sequences become `?`, as
192/// they do in a cut one.
193///
194/// ```
195/// use php_std::mb::mb_strimwidth;
196///
197/// assert_eq!(mb_strimwidth("你好".as_bytes(), 3).as_ref(), "你".as_bytes());
198/// assert_eq!(mb_strimwidth(b"abc", 5).as_ref(), b"abc");
199/// assert_eq!(mb_strimwidth(b"abc\xff\xfedef", 5).as_ref(), b"abc??");
200/// ```
201pub fn mb_strimwidth(s: &[u8], width: usize) -> Cow<'_, [u8]> {
202    let mut remaining = width;
203    let mut out = Vec::new();
204    let mut bad = false;
205    for w in decode(s) {
206        let columns = char_width(w);
207        if remaining < columns {
208            return Cow::Owned(out);
209        }
210        remaining -= columns;
211        bad |= w == BAD;
212        encode(&mut out, w, SUBSTITUTE);
213    }
214    if bad { Cow::Owned(out) } else { Cow::Borrowed(s) }
215}
216/// An encoding `mb_strlen` accepts.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub enum Encoding {
219    /// `UTF-8` (PHP's default internal encoding).
220    #[default]
221    Utf8,
222    /// `8bit` (alias `binary`): one character per byte.
223    EightBit,
224}
225
226impl Encoding {
227    /// The encoding for one of PHP's names (case-insensitive): `UTF-8`,
228    /// `UTF8`, `8bit`, `binary`. `None` for anything else (PHP's
229    /// `ValueError` for an unknown encoding, or an encoding not ported).
230    pub fn from_name(name: &str) -> Option<Self> {
231        match name.to_ascii_lowercase().as_str() {
232            "utf-8" | "utf8" => Some(Encoding::Utf8),
233            "8bit" | "binary" => Some(Encoding::EightBit),
234            _ => None,
235        }
236    }
237}
238
239/// PHP `mb_strlen($string)`: the number of characters; each invalid
240/// sequence counts as one.
241pub fn mb_strlen(s: &[u8]) -> usize {
242    let mut pos = 0;
243    let mut n = 0;
244    while pos < s.len() {
245        decode_one(s, &mut pos);
246        n += 1;
247    }
248    n
249}
250
251/// PHP `mb_strlen($string, $encoding)` for the encodings in [`Encoding`].
252pub fn mb_strlen_in(s: &[u8], encoding: Encoding) -> usize {
253    match encoding {
254        Encoding::Utf8 => mb_strlen(s),
255        Encoding::EightBit => s.len(),
256    }
257}
258
259/// PHP `mb_check_encoding($value, 'UTF-8')` on a string: strict UTF-8
260/// (no overlong forms, surrogates or code points above U+10FFFF).
261pub fn mb_check_encoding(s: &[u8]) -> bool {
262    std::str::from_utf8(s).is_ok()
263}
264
265/// PHP `mb_scrub($string)` and `mb_convert_encoding($string, 'UTF-8')`
266/// from UTF-8: each invalid sequence becomes `?`. Borrows valid input.
267pub fn mb_scrub(s: &[u8]) -> Cow<'_, [u8]> {
268    if mb_check_encoding(s) {
269        return Cow::Borrowed(s);
270    }
271    let mut out = Vec::with_capacity(s.len());
272    for w in decode(s) {
273        encode(&mut out, w, SUBSTITUTE);
274    }
275    Cow::Owned(out)
276}
277
278/// `mb_get_substr`: `len` characters from character `from`, re-encoded
279/// (invalid sequences become `?`).
280fn get_substr(s: &[u8], from: usize, len: usize) -> Vec<u8> {
281    if len == 0 || from >= s.len() {
282        return Vec::new();
283    }
284    let mut out = Vec::new();
285    for w in decode(s).skip(from).take(len) {
286        encode(&mut out, w, SUBSTITUTE);
287    }
288    out
289}
290
291/// PHP `mb_substr($string, $start, $length)`: characters from `start`
292/// (negative: from the end) for `length` characters (negative: stop that
293/// many before the end; `None`: to the end). Re-encodes: invalid sequences
294/// in the result become `?`. `PHP_INT_MIN` for either argument is PHP's
295/// `ValueError`.
296pub fn mb_substr(s: &[u8], start: i64, length: Option<i64>) -> Result<Vec<u8>, Error> {
297    let range_error = |n: u32, name: &str| {
298        Error::argument("mb_substr", n, name, &format!("must be between {} and {}", i64::MIN + 1, i64::MAX))
299    };
300    if start == i64::MIN {
301        return Err(range_error(2, "start"));
302    }
303    if length == Some(i64::MIN) {
304        return Err(range_error(3, "length"));
305    }
306    let mblen = if start < 0 || length.is_some_and(|l| l < 0) { mb_strlen(s) } else { 0 };
307    let from = if start >= 0 {
308        start as usize
309    } else if start.unsigned_abs() < mblen as u64 {
310        mblen - start.unsigned_abs() as usize
311    } else {
312        0
313    };
314    let len = match length {
315        None => usize::MAX,
316        Some(l) if l >= 0 => l as usize,
317        Some(l) if from < mblen && l.unsigned_abs() < (mblen - from) as u64 => mblen - from - l.unsigned_abs() as usize,
318        Some(_) => 0,
319    };
320    Ok(get_substr(s, from, len))
321}
322
323// ---------------------------------------------------------------------------
324// Case mapping
325// ---------------------------------------------------------------------------
326
327fn lookup(table: &[(u32, u32)], code: u32) -> Option<u32> {
328    table.binary_search_by_key(&code, |&(k, _)| k).ok().map(|i| table[i].1)
329}
330
331fn in_ranges(ranges: &[(u32, u32)], code: u32) -> bool {
332    match ranges.binary_search_by(|&(lo, _)| lo.cmp(&code)) {
333        Ok(_) => true,
334        Err(0) => false,
335        Err(i) => code <= ranges[i - 1].1,
336    }
337}
338
339fn is_cased(w: u32) -> bool {
340    in_ranges(unicode::CASED, w)
341}
342
343fn is_case_ignorable(w: u32) -> bool {
344    in_ranges(unicode::CASE_IGNORABLE, w)
345}
346
347fn tolower_raw(code: u32) -> u32 {
348    if code < 0xC0 {
349        if (0x41..=0x5A).contains(&code) { code + 0x20 } else { code }
350    } else {
351        lookup(unicode::LOWER, code).unwrap_or(code)
352    }
353}
354
355/// Writes a full mapping (`emit_special_casing_sequence`) or a code point.
356fn emit(raw: u32, out: &mut [u32; 192], p: &mut usize) {
357    if raw > 0xFFFFFF {
358        let len = (raw >> 24) as usize;
359        let at = (raw & 0xFFFFFF) as usize;
360        for &w in &unicode::EXTRA[at + 1..=at + len] {
361            out[*p] = w;
362            *p += 1;
363        }
364    } else {
365        out[*p] = raw;
366        *p += 1;
367    }
368}
369
370/// Whether the rest of the input, after the current chunk, continues with a
371/// cased letter (skipping case-ignorable characters).
372fn scan_ahead_for_cased(s: &[u8], mut pos: usize) -> bool {
373    while pos < s.len() {
374        let w = decode_one(s, &mut pos);
375        if is_cased(w) {
376            return true;
377        }
378        if !is_case_ignorable(w) {
379            return false;
380        }
381    }
382    false
383}
384
385/// `scan_back_for_cased_letter`: looks through what is left of the previous
386/// chunk's converted output (`converted[begin..end]`, backwards).
387fn scan_back_for_cased(converted: &[u32; 192], begin: usize, end: Option<usize>) -> bool {
388    let Some(mut e) = end else { return false };
389    while e > begin {
390        e -= 1;
391        let w = converted[e];
392        if is_cased(w) {
393            return true;
394        }
395        if !is_case_ignorable(w) {
396            return false;
397        }
398    }
399    false
400}
401
402/// Whether the capital sigma at `i` of the chunk ends a word (PHP's final
403/// sigma rule, with its chunk-limited look-behind).
404fn is_final_sigma(
405    wbuf: &[u32],
406    i: usize,
407    s: &[u8],
408    pos: usize,
409    converted: &[u32; 192],
410    p: usize,
411    converted_end: Option<usize>,
412) -> bool {
413    let mut j = i as isize - 1;
414    while j >= 0 && is_case_ignorable(wbuf[j as usize]) {
415        j -= 1;
416    }
417    let before = if j >= 0 { is_cased(wbuf[j as usize]) } else { scan_back_for_cased(converted, p, converted_end) };
418    if !before {
419        return false;
420    }
421    let mut j = i + 1;
422    while j < wbuf.len() && is_case_ignorable(wbuf[j]) {
423        j += 1;
424    }
425    if j >= wbuf.len() { !scan_ahead_for_cased(s, pos) } else { !is_cased(wbuf[j]) }
426}
427
428/// `php_unicode_convert_case` (`MB_CASE_LOWER`) for UTF-8 in and out, in
429/// chunks of 64 code points like PHP (the final-sigma look-behind depends on
430/// them).
431fn convert_case(s: &[u8], bad: &[u8]) -> Vec<u8> {
432    let mut out = Vec::with_capacity(s.len() + 1);
433    let mut converted = [0u32; 192];
434    let mut converted_end: Option<usize> = None;
435    let mut pos = 0;
436    let mut wbuf = [0u32; 64];
437    while pos < s.len() {
438        let mut n = 0;
439        while pos < s.len() && n < 64 {
440            wbuf[n] = decode_one(s, &mut pos);
441            n += 1;
442        }
443        let w_in = &wbuf[..n];
444        let mut p = 0;
445        for (i, &w) in w_in.iter().enumerate() {
446            if w > 0xFFFFFF {
447                converted[p] = w;
448                p += 1;
449                continue;
450            }
451            if w == 0x3A3 && is_final_sigma(w_in, i, s, pos, &converted, p, converted_end) {
452                converted[p] = 0x3C2;
453                p += 1;
454            } else {
455                emit(tolower_raw(w), &mut converted, &mut p);
456            }
457        }
458        converted_end = Some(p);
459        for &w in &converted[..p] {
460            encode(&mut out, w, bad);
461        }
462    }
463    out
464}
465
466/// PHP `mb_strtolower($string)`: full lower case with the final sigma rule
467/// (`MB_CASE_LOWER`).
468pub fn mb_strtolower(s: &[u8]) -> Vec<u8> {
469    map_case(s).unwrap_or_else(|| convert_case(s, SUBSTITUTE))
470}
471
472/// [`convert_case`] where each code point maps on its own: ASCII runs are
473/// converted in bulk, without the chunking. `None` for a capital sigma (the
474/// final sigma rule looks at its neighbours, within PHP's chunks).
475fn map_case(s: &[u8]) -> Option<Vec<u8>> {
476    // The raw mappings of the first code points (Latin, Greek, Cyrillic,
477    // Armenian, Hebrew), looked up directly instead of searched.
478    const DIRECT: usize = 0x600;
479    static TABLE: OnceLock<Vec<u32>> = OnceLock::new();
480    let direct = TABLE.get_or_init(|| (0..DIRECT as u32).map(tolower_raw).collect());
481    let mut out = Vec::with_capacity(s.len() + s.len() / 4 + 1);
482    let mut pos = 0;
483    while pos < s.len() {
484        let run = s[pos..].iter().position(|&c| c >= 0x80).map_or(s.len(), |n| pos + n);
485        out.extend(s[pos..run].iter().map(u8::to_ascii_lowercase));
486        pos = run;
487        if pos == s.len() {
488            break;
489        }
490        let w = decode_one(s, &mut pos);
491        if w > 0xFFFFFF {
492            encode(&mut out, w, SUBSTITUTE);
493            continue;
494        }
495        if w == 0x3A3 {
496            return None;
497        }
498        let raw = direct.get(w as usize).copied().unwrap_or_else(|| tolower_raw(w));
499        if raw > 0xFFFFFF {
500            let len = (raw >> 24) as usize;
501            let at = (raw & 0xFFFFFF) as usize;
502            for &w in &unicode::EXTRA[at + 1..=at + len] {
503                encode(&mut out, w, SUBSTITUTE);
504            }
505        } else {
506            encode(&mut out, raw, SUBSTITUTE);
507        }
508    }
509    Some(out)
510}
511
512// ---------------------------------------------------------------------------
513// Searching
514// ---------------------------------------------------------------------------
515
516/// `offset_to_pointer_utf8`: the byte position `offset` characters from the
517/// start (or from the end, when negative), counting characters by lead bytes.
518///
519/// A string that ends in a truncated sequence stops at its end (GH-23106,
520/// PHP 8.5.12: `pos > end` is clamped).
521fn offset_to_pointer(s: &[u8], offset: i64) -> Option<usize> {
522    if offset < 0 {
523        let mut pos = s.len();
524        let mut offset = offset;
525        while offset < 0 {
526            if pos == 0 {
527                return None;
528            }
529            pos -= 1;
530            if !is_continuation(s[pos]) {
531                offset += 1;
532            }
533        }
534        Some(pos)
535    } else {
536        let mut pos = 0;
537        let mut offset = offset;
538        while offset > 0 {
539            if pos >= s.len() {
540                return None;
541            }
542            pos += utf8_len(s[pos]);
543            offset -= 1;
544        }
545        Some(pos.min(s.len()))
546    }
547}
548
549/// `pointer_to_offset_utf8`: characters (non-continuation bytes) before `pos`.
550fn pointer_to_offset(s: &[u8], pos: usize) -> usize {
551    s[..pos].iter().filter(|&&b| !is_continuation(b)).count()
552}
553
554/// `mb_find_strpos` on UTF-8 bytes.
555fn find_strpos(function: &str, h: &[u8], n: &[u8], offset: i64, reverse: bool) -> Result<Option<usize>, Error> {
556    let op = offset_to_pointer(h, offset)
557        .ok_or_else(|| Error::argument(function, 3, "offset", "must be contained in argument #1 ($haystack)"))?;
558    if h.len() < n.len() {
559        return Ok(None);
560    }
561    let found = if !reverse {
562        crate::string::find(&h[op..], n).map(|i| i + op)
563    } else if offset >= 0 {
564        crate::string::rfind(&h[op..], n).map(|i| i + op)
565    } else {
566        let needle_chars = pointer_to_offset(n, n.len());
567        let end = offset_to_pointer(&h[op..], needle_chars as i64).map_or(h.len(), |e| op + e);
568        crate::string::rfind(&h[..end], n)
569    };
570    Ok(found.map(|p| pointer_to_offset(h, p)))
571}
572
573/// PHP `mb_strpos($haystack, $needle, $offset)`: character position of the
574/// first occurrence at or after `offset`. Matches bytes; positions count
575/// lead bytes. `None` is PHP's `false`.
576pub fn mb_strpos(haystack: &[u8], needle: &[u8], offset: i64) -> Result<Option<usize>, Error> {
577    find_strpos("mb_strpos", haystack, needle, offset, false)
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    #[test]
585    fn counts_invalid_sequences() {
586        assert_eq!(mb_strlen("héllo".as_bytes()), 5);
587        assert_eq!(mb_strlen(b"\xE2\x82"), 1);
588        assert_eq!(mb_strlen(b"\xF0\x9F\x98\x80\x80"), 2);
589    }
590
591    #[test]
592    fn cases_like_php() {
593        assert_eq!(mb_strtolower(b"A\xFFB\xE2\x82"), b"a?b?");
594        assert_eq!(mb_strtolower("ΣΑΣ.Σ".as_bytes()), "σασ.ς".as_bytes());
595    }
596
597    #[test]
598    fn substr_and_split() {
599        assert_eq!(mb_substr(b"a\xFFbc", 1, Some(2)).unwrap(), b"?b");
600    }
601}