phplang 0.2.17

PHP as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PhpHost heap — the first compiled standalone PHP runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
//! PHP standard-library `mbstring` functions. Part of the `stdlib` chain; see
//! `src/stdlib/mod.rs`. `dispatch` returns `None` for names it does not handle.
//!
//! Every function here is codepoint-aware: it operates on Unicode scalar values
//! (`char`), not bytes, which is the defining difference from the core byte-
//! oriented `str_*` builtins. `mb_strlen`, `mb_substr`, `mb_strtoupper` and
//! `mb_strtolower` already live in the `strings` module and are intentionally
//! absent here.
//!
//! Encoding scope: phplang stores `Value::Str` as a Rust `String` (always valid
//! UTF-8), so the multibyte machine is UTF-8. `mb_convert_encoding` therefore
//! supports the UTF-8 <-> ASCII / ISO-8859-1 / Latin-1 basics at the character
//! level; a true single-byte Latin-1 output (raw bytes 0x80..0xFF) cannot be
//! represented in a UTF-8 `String`, so the codepoint is preserved instead of the
//! byte. Untranslatable characters become `?`, matching PHP's substitution.
//!
//! `mb_internal_encoding` keeps module-local (thread-local) state. Caveat: that
//! state is NOT reset between separate script evaluations that run on the same
//! thread, so a setter call leaks into a later run in the same worker thread.

use crate::host::with_host;
use crate::stdlib::common::*;
use fusevm::Value;
use std::cell::RefCell;

thread_local! {
    /// Configured internal encoding; PHP defaults to "UTF-8".
    static INTERNAL_ENCODING: RefCell<String> = RefCell::new("UTF-8".to_string());
    /// Set while [`dispatch_decoded`] runs a function on already-decoded
    /// arguments, so [`dispatch`] does not decode them a second time.
    static DECODED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Functions that decode their string arguments to characters, print every
/// invalid sequence as `?`, and return text — measured against the reference
/// one by one (`mb_str_pad`, `mb_str_split` and `mb_ucfirst` copy an invalid
/// sequence through instead and are not listed).
const TEXT_FUNCTIONS: &[&str] = &[
    "mb_convert_case",
    "mb_stripos",
    "mb_strripos",
    "mb_substr_count",
    "mb_scrub",
    "mb_convert_kana",
    "mb_strwidth",
    "mb_trim",
    "mb_ltrim",
    "mb_rtrim",
    "mb_strstr",
    "mb_stristr",
    "mb_strrchr",
    "mb_strrichr",
    "mb_strimwidth",
    "mb_encode_numericentity",
    "mb_decode_numericentity",
];

/// A [`TEXT_FUNCTIONS`] member run on its decoded arguments, its result stored
/// as text.
fn dispatch_decoded(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    // The decoded text of each string argument (a character in the escape
    // range becomes itself), and the result stored back as text.
    let text_args: Vec<Value> = args
        .iter()
        .map(|a| match a {
            Value::Str(s) if crate::bytes::has_raw(s) => {
                Value::str(crate::bytes::mb_text(s).into_owned())
            }
            other => other.clone(),
        })
        .collect();
    DECODED.set(true);
    let result = dispatch(name, &text_args);
    DECODED.set(false);
    result.map(|r| {
        r.map(|v| match v {
            Value::Str(s) => text_value(&s),
            other => other,
        })
    })
}

/// Dispatch a `mbstring`-category PHP function by lowercased name.
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    if TEXT_FUNCTIONS.contains(&name) && !DECODED.get() {
        return dispatch_decoded(name, args);
    }
    let v = match name {
        "mb_str_split" => return Some(mb_str_split(args)),
        "mb_convert_case" => Value::str(mb_convert_case(args)),
        "mb_strpos" => return Some(mb_strpos(args, false)),
        "mb_stripos" => return Some(mb_strpos(args, true)),
        "mb_strrpos" => return Some(mb_strrpos(args, false)),
        "mb_strripos" => return Some(mb_strrpos(args, true)),
        "mb_substr_count" => return Some(mb_substr_count(args)),
        "mb_str_pad" => return Some(mb_str_pad(args)),
        "mb_ord" => return Some(mb_ord(args)),
        "mb_chr" => mb_chr(args),
        "mb_lcfirst" => Value::str(mb_lcfirst(&str_arg(args, 0))),
        "mb_ucfirst" => Value::str(mb_ucfirst(&str_arg(args, 0))),
        // phplang strings are always valid UTF-8, so there is never an ill-formed
        // sequence to substitute; mb_scrub returns the input unchanged.
        "mb_scrub" => Value::str(str_arg(args, 0)),
        "mb_strcut" => Value::str(mb_strcut(args)),
        "mb_split" => mb_split(args),
        "mb_convert_kana" => Value::str(mb_convert_kana(args)),
        "mb_strwidth" => Value::int(mb_strwidth(&str_arg(args, 0)) as i64),
        "mb_convert_encoding" => return Some(mb_convert_encoding(args)),
        "mb_detect_encoding" => mb_detect_encoding(args),
        "mb_check_encoding" => Value::bool(mb_check_encoding(args)),
        "mb_internal_encoding" => mb_internal_encoding(args),
        "mb_trim" => return Some(mb_trim(args, "mb_trim", true, true)),
        "mb_ltrim" => return Some(mb_trim(args, "mb_ltrim", true, false)),
        "mb_rtrim" => return Some(mb_trim(args, "mb_rtrim", false, true)),
        "mb_strstr" => return Some(mb_strstr(args, "mb_strstr", false, false)),
        "mb_stristr" => return Some(mb_strstr(args, "mb_stristr", true, false)),
        "mb_strrchr" => return Some(mb_strstr(args, "mb_strrchr", false, true)),
        "mb_strrichr" => return Some(mb_strstr(args, "mb_strrichr", true, true)),
        "mb_strimwidth" => return Some(mb_strimwidth(args)),
        "mb_encode_numericentity" => return Some(mb_encode_numericentity(args)),
        "mb_decode_numericentity" => return Some(mb_decode_numericentity(args)),
        _ => return None,
    };
    Some(Ok(v))
}

// ── splitting ────────────────────────────────────────────────────────────────

/// `mb_str_split($string, $length = 1, $encoding = null)`: split into an array of
/// codepoint chunks of `$length` characters each. PHP 8 raises a `ValueError` for
/// `$length < 1` and returns an empty array for an empty string.
fn mb_str_split(args: &[Value]) -> Result<Value, String> {
    let s = str_arg(args, 0);
    let length = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => v.to_int(),
        _ => 1,
    };
    if length < 1 {
        return Err(throws(
            "ValueError",
            "mb_str_split(): Argument #2 ($length) must be greater than 0",
        ));
    }
    // An invalid sequence is one character, copied through as its bytes.
    let bytes = crate::bytes::to_bytes(&s);
    let units = crate::bytes::mb_units(&bytes);
    let out: Vec<Value> = units
        .chunks(usize::try_from(length).unwrap_or(usize::MAX))
        .map(|c| Value::str(c.iter().map(|u| u.stored()).collect::<String>()))
        .collect();
    Ok(make_list(out))
}

// ── case conversion ──────────────────────────────────────────────────────────

/// `mb_convert_case($string, $mode, $encoding = null)`. `$mode` is
/// `MB_CASE_UPPER` (0), `MB_CASE_LOWER` (1) or `MB_CASE_TITLE` (2), passed either
/// as the integer or (phplang has no constant table) as the constant name string.
fn mb_convert_case(args: &[Value]) -> String {
    let s = str_arg(args, 0);
    match resolve_mode(&arg(args, 1)) {
        1 => s.to_lowercase(),
        2 => title_case(&s),
        // 0 (MB_CASE_UPPER) and any unknown mode default to upper, matching the
        // most common call and avoiding a silent wrong-case for a bad constant.
        _ => s.to_uppercase(),
    }
}

/// Resolve a case-mode argument to its integer: accepts the canonical PHP integer
/// or the bareword constant name (which reaches us as its string).
fn resolve_mode(v: &Value) -> i64 {
    if let Value::Str(name) = v {
        match name.as_str() {
            "MB_CASE_UPPER" => return 0,
            "MB_CASE_LOWER" => return 1,
            "MB_CASE_TITLE" => return 2,
            _ => {}
        }
    }
    v.to_int()
}

/// Unicode title-casing: uppercase the first letter of each word, lowercase the
/// rest of it. A non-letter resets the word — EXCEPT a *case-ignorable* one,
/// which is transparent, so the letter after it continues the word it was in.
///
/// That exception is the whole difference between `"Who's Who"` and `"Who'S
/// Who"`, and this function used to produce the second: an apostrophe reset the
/// word, so the `s` began a new one. Its own doc-comment asserted `"Who'S Who"`
/// was `(PHP 8)`'s answer. It never was — `php 8.5.9` answers `"Who's Who"`, and
/// so does every PHP that has had `mb_convert_case`.
fn title_case(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut in_word = false;
    for c in s.chars() {
        if is_case_ignorable(c) {
            // Transparent: written through without disturbing the word state,
            // so `x.y` titles to `X.y` while `x,y` titles to `X,Y`.
            out.push(c);
        } else if c.is_alphabetic() {
            if in_word {
                out.extend(c.to_lowercase());
            } else {
                out.extend(c.to_uppercase());
            }
            in_word = true;
        } else {
            out.push(c);
            in_word = false;
        }
    }
    out
}

/// Whether `c` is Unicode `Case_Ignorable`, the property that decides which
/// characters a title-casing pass looks straight through.
///
/// APPROXIMATION: the full property is `Word_Break ∈ {MidLetter, MidNumLet,
/// Single_Quote}` plus general categories `Mn`, `Me`, `Cf`, `Lm` and `Sk`. The
/// first three sets are finite and listed in full below; the categories need a
/// Unicode table this crate does not carry, so only their ASCII and Latin-1
/// members are recognised. A combining mark or a format character therefore
/// still resets the word here where the reference would see through it.
fn is_case_ignorable(c: char) -> bool {
    matches!(
        c,
        // Word_Break = Single_Quote / MidNumLet / MidLetter.
        '\u{0027}' | '\u{002E}' | '\u{003A}' | '\u{00B7}' | '\u{0387}'
        | '\u{055F}' | '\u{05F4}' | '\u{2018}' | '\u{2019}' | '\u{2024}'
        | '\u{2027}' | '\u{FE13}' | '\u{FE52}' | '\u{FE55}' | '\u{FF07}'
        | '\u{FF0E}' | '\u{FF1A}'
        // General category Sk, ASCII and Latin-1 members.
        | '\u{005E}' | '\u{0060}' | '\u{00A8}' | '\u{00AF}' | '\u{00B4}'
        | '\u{00B8}'
    )
}

// ── searching / positions ────────────────────────────────────────────────────

/// `mblen_table_utf8` (libmbfl/filters/mbfilter_utf8.c): the byte length
/// mbstring steps over for each lead byte, whether or not what follows is
/// valid.
fn utf8_step(lead: u8) -> usize {
    match lead {
        0xC2..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF4 => 4,
        _ => 1,
    }
}

/// `mb_fast_strlen_utf8`: the bytes that are not continuation bytes.
fn utf8_fast_len(b: &[u8]) -> usize {
    b.iter().filter(|&&c| !(0x80..0xC0).contains(&c)).count()
}

/// Port of `offset_to_pointer_utf8` (ext/mbstring/mbstring.c): the byte
/// position `offset` characters into `b[start..]` (from the end when
/// negative), or `None` past either end.
fn utf8_offset(b: &[u8], start: usize, offset: i64) -> Option<usize> {
    if offset < 0 {
        let mut pos = b.len();
        let mut offset = offset;
        while offset < 0 {
            if pos <= start {
                return None;
            }
            pos -= 1;
            if !(0x80..0xC0).contains(&b[pos]) {
                offset += 1;
            }
        }
        Some(pos)
    } else {
        let mut pos = start;
        for _ in 0..offset {
            if pos >= b.len() {
                return None;
            }
            pos += utf8_step(b[pos]);
        }
        Some(pos.min(b.len()))
    }
}

/// Port of `mb_find_strpos` for UTF-8: a BYTE search (so a needle holding a
/// stray byte matches inside a character), answered as the number of
/// characters before the match as `mb_fast_strlen_utf8` counts them. `Err`
/// is the offset error.
fn mb_find_strpos(
    hay: &[u8],
    needle: &[u8],
    offset: i64,
    reverse: bool,
) -> Result<Option<usize>, ()> {
    let from = utf8_offset(hay, 0, offset).ok_or(())?;
    if hay.len() < needle.len() {
        return Ok(None);
    }
    let found = if !reverse {
        crate::bytes::find(&hay[from..], needle).map(|i| i + from)
    } else if offset >= 0 {
        crate::bytes::rfind(&hay[from..], needle).map(|i| i + from)
    } else {
        // A negative offset is where the LAST match may start: step forward
        // by the needle's length in characters to find where it may end.
        let needle_len = utf8_fast_len(needle) as i64;
        let end = utf8_offset(hay, from, needle_len).unwrap_or(hay.len());
        crate::bytes::rfind(&hay[..end], needle)
    };
    Ok(found.map(|at| utf8_fast_len(&hay[..at])))
}

/// `mb_strpos` / `mb_strrpos` through [`mb_find_strpos`].
fn find_strpos_call(args: &[Value], fname: &str, reverse: bool) -> Result<Value, String> {
    let hay = crate::bytes::to_bytes(&str_arg(args, 0)).into_owned();
    let needle = crate::bytes::to_bytes(&str_arg(args, 1)).into_owned();
    match mb_find_strpos(&hay, &needle, int_arg(args, 2), reverse) {
        Ok(Some(n)) => Ok(Value::int(n as i64)),
        Ok(None) => Ok(Value::bool(false)),
        Err(()) => Err(throws(
            "ValueError",
            format!(
                "{fname}(): Argument #3 ($offset) must be contained in argument #1 ($haystack)"
            ),
        )),
    }
}

/// `mb_strpos`/`mb_stripos($haystack, $needle, $offset = 0, $encoding = null)`:
/// codepoint position of the first match of `$needle`, or `false`. `ci` selects
/// the case-insensitive `mb_stripos`. PHP 8 raises a `ValueError` when `$offset`
/// is outside `[-len, len]` (a negative offset counts from the end).
fn mb_strpos(args: &[Value], ci: bool) -> Result<Value, String> {
    if !ci {
        return find_strpos_call(args, "mb_strpos", false);
    }
    let (hay, needle) = ci_pair(args, ci);
    let len = hay.len() as i64;
    let off_raw = int_arg(args, 2);
    if off_raw > len || off_raw < -len {
        return Err(throws(
            "ValueError",
            format!(
                "{}(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
                if ci { "mb_stripos" } else { "mb_strpos" }
            ),
        ));
    }
    let off = if off_raw < 0 {
        (len + off_raw) as usize
    } else {
        off_raw as usize
    };
    // Empty needle matches at the offset (PHP 8 semantics).
    for i in off..=hay.len().saturating_sub(needle.len()) {
        if hay[i..].starts_with(&needle[..]) {
            return Ok(Value::int(i as i64));
        }
    }
    Ok(Value::bool(false))
}

/// `mb_strrpos`/`mb_strripos($haystack, $needle, $offset = 0, $encoding = null)`:
/// codepoint position of the LAST match, or `false`. A positive `$offset` limits
/// the search to matches starting at or after it; a negative `$offset` stops the
/// search that many characters from the end. `ci` selects `mb_strripos`. PHP 8
/// raises a `ValueError` when `$offset` is outside `[-len, len]`.
fn mb_strrpos(args: &[Value], ci: bool) -> Result<Value, String> {
    if !ci {
        return find_strpos_call(args, "mb_strrpos", true);
    }
    let (hay, needle) = ci_pair(args, ci);
    let len = hay.len();
    let ilen = len as i64;
    let off = int_arg(args, 2);
    if off > ilen || off < -ilen {
        return Err(throws(
            "ValueError",
            format!(
                "{}(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
                if ci { "mb_strripos" } else { "mb_strrpos" }
            ),
        ));
    }
    if needle.is_empty() {
        return Ok(Value::int(len as i64));
    }
    let (lo, hi) = if off >= 0 {
        (off as usize, len.saturating_sub(needle.len()))
    } else {
        let hi = (ilen + off).max(0) as usize;
        (0, hi.min(len.saturating_sub(needle.len())))
    };
    match (lo..=hi)
        .rev()
        .find(|&i| i + needle.len() <= len && hay[i..].starts_with(&needle[..]))
    {
        Some(i) => Ok(Value::int(i as i64)),
        None => Ok(Value::bool(false)),
    }
}

/// `mb_substr_count($haystack, $needle, $encoding = null)`: number of non-
/// overlapping codepoint matches. PHP 8 raises a `ValueError` on an empty needle.
fn mb_substr_count(args: &[Value]) -> Result<Value, String> {
    let hay: Vec<char> = str_arg(args, 0).chars().collect();
    let needle: Vec<char> = str_arg(args, 1).chars().collect();
    if needle.is_empty() {
        return Err(throws(
            "ValueError",
            "mb_substr_count(): Argument #2 ($needle) must not be empty",
        ));
    }
    let mut count = 0i64;
    let mut i = 0;
    while i + needle.len() <= hay.len() {
        if hay[i..i + needle.len()] == needle[..] {
            count += 1;
            i += needle.len();
        } else {
            i += 1;
        }
    }
    Ok(Value::int(count))
}

/// Return `(haystack, needle)` as codepoint vectors, case-folded when `ci`.
fn ci_pair(args: &[Value], ci: bool) -> (Vec<char>, Vec<char>) {
    let (h, n) = (str_arg(args, 0), str_arg(args, 1));
    if ci {
        (fold_chars(&h), fold_chars(&n))
    } else {
        (h.chars().collect(), n.chars().collect())
    }
}

/// Lowercase each character to a single representative codepoint, keeping a 1:1
/// char mapping so a case-insensitive match index stays aligned with the original
/// string. Full `str::to_lowercase` can expand one char into several (e.g. `İ`
/// U+0130 → `i` + combining dot), which would shift every subsequent position and
/// make `mb_stripos`/`mb_strripos` return a wrong index.
fn fold_chars(s: &str) -> Vec<char> {
    s.chars()
        .map(|c| c.to_lowercase().next().unwrap_or(c))
        .collect()
}

// ── padding ──────────────────────────────────────────────────────────────────

/// `mb_str_pad($string, $length, $pad_string = " ", $pad_type = STR_PAD_RIGHT,
/// $encoding = null)` (PHP 8.3). `$length` and padding are counted in codepoints.
/// `STR_PAD_RIGHT` (1), `STR_PAD_LEFT` (0) and `STR_PAD_BOTH` (2) are accepted as
/// integers or as their constant-name strings.
fn mb_str_pad(args: &[Value]) -> Result<Value, String> {
    // Counted in mbstring characters; an invalid sequence is one, copied
    // through as its bytes.
    let subject = crate::bytes::to_bytes(&str_arg(args, 0)).into_owned();
    let s = stored_units(&subject);
    let target = int_arg(args, 1);
    let pad_str = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => str_arg(args, 2),
        _ => " ".to_string(),
    };
    let pad_bytes = crate::bytes::to_bytes(&pad_str).into_owned();
    let pad = stored_units(&pad_bytes);
    let pad_type = resolve_pad_type(&arg(args, 3));

    if target <= s.len() as i64 {
        return Ok(Value::str(s.concat()));
    }
    if pad.is_empty() {
        return Err(throws(
            "ValueError",
            "mb_str_pad(): Argument #3 ($pad_string) must not be empty",
        ));
    }
    let total = target as usize - s.len();
    let make = |n: usize| -> Vec<String> { pad.iter().cloned().cycle().take(n).collect() };

    // NOT `with_capacity(target)`: `$length` is unbounded and reserving
    // `target * size_of::<char>()` bytes up front panicked with "capacity
    // overflow" before any padding was built.
    let mut out: Vec<String> = Vec::new();
    match pad_type {
        0 => {
            // STR_PAD_LEFT
            out.extend(make(total));
            out.extend(s);
        }
        2 => {
            // STR_PAD_BOTH: left gets the smaller half (PHP floors the left side).
            let left = total / 2;
            let right = total - left;
            out.extend(make(left));
            out.extend(s);
            out.extend(make(right));
        }
        _ => {
            // STR_PAD_RIGHT (default)
            out.extend(s);
            out.extend(make(total));
        }
    }
    Ok(Value::str(crate::bytes::canonical(out.concat())))
}

/// The mbstring characters of `b`, each in stored form.
fn stored_units(b: &[u8]) -> Vec<String> {
    crate::bytes::mb_units(b)
        .into_iter()
        .map(crate::bytes::MbUnit::stored)
        .collect()
}

/// Resolve a `$pad_type` argument (STR_PAD_* integer or constant-name string).
fn resolve_pad_type(v: &Value) -> i64 {
    if let Value::Str(name) = v {
        match name.as_str() {
            "STR_PAD_LEFT" => return 0,
            "STR_PAD_RIGHT" => return 1,
            "STR_PAD_BOTH" => return 2,
            _ => {}
        }
    }
    match v {
        Value::Undef => 1,
        _ => v.to_int(),
    }
}

// ── codepoint <-> character ──────────────────────────────────────────────────

/// `mb_ord($string, $encoding = null)`: the codepoint of the first character.
///
/// An empty string is a `ValueError`, not `false` — PHP 8 rejects it rather than
/// answering a failure sentinel the way PHP 7 did.
fn mb_ord(args: &[Value]) -> Result<Value, String> {
    let bytes = crate::bytes::to_bytes(&str_arg(args, 0)).into_owned();
    match crate::bytes::mb_units(&bytes).first() {
        Some(crate::bytes::MbUnit::Char(c)) => Ok(Value::int(*c as i64)),
        // An invalid first sequence has no code point.
        Some(crate::bytes::MbUnit::Invalid(_)) => Ok(Value::bool(false)),
        None => Err(throws(
            "ValueError",
            "mb_ord(): Argument #1 ($string) must not be empty",
        )),
    }
}

/// `mb_chr($codepoint, $encoding = null)`: the character for a Unicode codepoint,
/// or `false` when the value is not a valid scalar value (surrogate or > 0x10FFFF).
fn mb_chr(args: &[Value]) -> Value {
    let cp = int_arg(args, 0);
    match u32::try_from(cp).ok().and_then(char::from_u32) {
        Some(c) => text_value(c.encode_utf8(&mut [0u8; 4])),
        None => Value::bool(false),
    }
}

// ── first-character case / cutting / splitting ───────────────────────────────

/// `mb_lcfirst($string, $encoding = null)`: lowercase only the first character,
/// leaving the rest untouched. Empty string returns empty.
fn mb_lcfirst(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        // A stored escape (an invalid sequence, or a character in the escape
        // range, which has no case) is left as it is.
        Some(first) if crate::bytes::has_raw(first.encode_utf8(&mut [0u8; 4])) => s.to_string(),
        Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// `mb_ucfirst($string, $encoding = null)` (PHP 8.4): uppercase only the first
/// character, leaving the rest untouched. Empty string returns empty.
fn mb_ucfirst(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(first) if crate::bytes::has_raw(first.encode_utf8(&mut [0u8; 4])) => s.to_string(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// `mb_strcut($string, $start, $length = null, $encoding = null)`: byte-offset
/// substring that never splits a multibyte character. `$start`/`$length` count
/// bytes; a negative `$start` counts from the end, a negative `$length` omits
/// that many trailing bytes. Offsets landing mid-character are floored down to the
/// nearest character boundary (matching PHP's UTF-8 behavior), so the result is
/// always valid UTF-8.
fn mb_strcut(args: &[Value]) -> String {
    let s = str_arg(args, 0);
    let blen = s.len() as i64;
    let mut start = int_arg(args, 1);
    if start < 0 {
        start = (blen + start).max(0);
    }
    let start = start.clamp(0, blen) as usize;
    let end = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => {
            let l = with_host(|h| h.to_number(v).to_int());
            if l < 0 {
                (blen + l).max(0) as usize
            } else {
                // `$length` is unbounded, so the addition must saturate: a
                // `PHP_INT_MAX` length overflowed before the `.min` could clamp
                // it. The reference simply cuts at the end of the string.
                (start as i64).saturating_add(l).min(blen) as usize
            }
        }
        _ => blen as usize,
    };
    let start = floor_char_boundary(&s, start);
    let end = floor_char_boundary(&s, end.max(start));
    s[start..end].to_string()
}

/// Round a byte index down to the nearest UTF-8 character boundary (or `s.len()`
/// when at/after the end). Guarantees `s[..i]` and `s[i..]` are both valid slices.
fn floor_char_boundary(s: &str, mut i: usize) -> usize {
    if i >= s.len() {
        return s.len();
    }
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

/// `mb_split($pattern, $string, $limit = -1)`: split `$string` by the regular
/// expression `$pattern`, returning an array of pieces (or `false` on a pattern
/// that fails to compile). A positive `$limit` caps the number of pieces, the last
/// holding the remainder; `0` or negative means no limit. An empty pattern returns
/// the whole string as a single element (PHP behavior).
fn mb_split(args: &[Value]) -> Value {
    let pattern = str_arg(args, 0);
    let subject = str_arg(args, 1);
    let limit = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => int_arg(args, 2),
        _ => -1,
    };
    if pattern.is_empty() {
        return make_list(vec![Value::str(subject)]);
    }
    let re = match regex::Regex::new(&pattern) {
        Ok(r) => r,
        Err(_) => return Value::bool(false),
    };
    let parts: Vec<Value> = if limit > 0 {
        re.splitn(&subject, limit as usize)
            .map(|p| Value::str(p.to_string()))
            .collect()
    } else {
        re.split(&subject)
            .map(|p| Value::str(p.to_string()))
            .collect()
    };
    make_list(parts)
}

/// `mb_convert_kana($string, $mode = "KV", $encoding = null)`. Implements the
/// ASCII fullwidth<->halfwidth modes, which are fully defined by codepoint math:
/// `r`/`R` letters, `n`/`N` digits, `a`/`A` all alphanumerics + symbols
/// (U+FF01..U+FF5E <-> U+0021..U+007E), `s`/`S` the ideographic space
/// (U+3000 <-> U+0020). Lowercase = fullwidth→halfwidth, uppercase = the reverse.
/// The kana-specific modes (k/K/h/H/c/C/v/V) require Japanese kana tables that are
/// out of scope here; characters they would touch are left unchanged.
fn mb_convert_kana(args: &[Value]) -> String {
    let s = str_arg(args, 0);
    let mode = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => str_arg(args, 1),
        _ => "KV".to_string(),
    };
    let (fw_all, fw_letter, fw_digit) =
        (mode.contains('a'), mode.contains('r'), mode.contains('n'));
    let (hw_all, hw_letter, hw_digit) =
        (mode.contains('A'), mode.contains('R'), mode.contains('N'));
    let (fw_space, hw_space) = (mode.contains('s'), mode.contains('S'));

    s.chars()
        .map(|c| {
            let cp = c as u32;
            if cp == 0x3000 && fw_space {
                return ' ';
            }
            if cp == 0x20 && hw_space {
                return '\u{3000}';
            }
            // Fullwidth ASCII variants → halfwidth.
            if (0xFF01..=0xFF5E).contains(&cp) {
                let is_letter = (0xFF21..=0xFF3A).contains(&cp) || (0xFF41..=0xFF5A).contains(&cp);
                let is_digit = (0xFF10..=0xFF19).contains(&cp);
                if fw_all || (fw_letter && is_letter) || (fw_digit && is_digit) {
                    return char::from_u32(cp - 0xFEE0).unwrap_or(c);
                }
            }
            // Halfwidth ASCII printables → fullwidth.
            if (0x21..=0x7E).contains(&cp) {
                let is_letter = c.is_ascii_alphabetic();
                let is_digit = c.is_ascii_digit();
                if hw_all || (hw_letter && is_letter) || (hw_digit && is_digit) {
                    return char::from_u32(cp + 0xFEE0).unwrap_or(c);
                }
            }
            c
        })
        .collect()
}

// ── display width ────────────────────────────────────────────────────────────

/// East-Asian-width ranges that count as 2 columns, ported from PHP's
/// `mbfl_charwidth` table (mbstring/libmbfl). Every codepoint outside these
/// ranges has width 1.
const WIDE_RANGES: &[(u32, u32)] = &[
    (0x1100, 0x115F),
    (0x11A3, 0x11A7),
    (0x11FA, 0x11FF),
    (0x2329, 0x232A),
    (0x2E80, 0x2E99),
    (0x2E9B, 0x2EF3),
    (0x2F00, 0x2FD5),
    (0x2FF0, 0x2FFB),
    (0x3000, 0x303E),
    (0x3041, 0x33FF),
    (0x3400, 0x4DBF),
    (0x4E00, 0x9FFF),
    (0xA000, 0xA4CF),
    (0xA960, 0xA97C),
    (0xAC00, 0xD7A3),
    (0xF900, 0xFAFF),
    (0xFE10, 0xFE19),
    (0xFE30, 0xFE6B),
    (0xFF00, 0xFF60),
    (0xFFE0, 0xFFE6),
    (0x1B000, 0x1B001),
    (0x1F200, 0x1F251),
    (0x20000, 0x3FFFD),
];

/// `mb_strwidth($string, $encoding = null)`: sum of per-character display widths
/// (2 for the East-Asian wide/full-width ranges above, 1 for everything else).
fn mb_strwidth(s: &str) -> usize {
    s.chars()
        .map(|c| {
            let cp = c as u32;
            if WIDE_RANGES.iter().any(|&(lo, hi)| cp >= lo && cp <= hi) {
                2
            } else {
                1
            }
        })
        .sum()
}

// ── encoding conversion / detection ──────────────────────────────────────────

/// `mb_convert_encoding($string, $to_encoding, $from_encoding = null)`. Supports
/// the UTF-8 <-> ASCII / ISO-8859-1 / Latin-1 basics at the character level (see
/// the module note on the single-byte-output limitation). Characters that cannot
/// be represented in the target encoding become `?`.
fn mb_convert_encoding(args: &[Value]) -> Result<Value, String> {
    let s = str_arg(args, 0);
    let raw_to = str_arg(args, 1);
    let to = normalize_encoding(&raw_to);
    // An unrecognised target used to be silently treated as UTF-8, so a typo
    // returned the input unchanged instead of being reported.
    if !SUPPORTED_ENCODINGS.contains(&to.as_str()) {
        return Err(throws(
            "ValueError",
            format!(
                "mb_convert_encoding(): Argument #2 ($to_encoding) must be a valid \
                 encoding, \"{raw_to}\" given"
            ),
        ));
    }
    // The source charset: the one named, or the first of a candidate list
    // (an array, or a comma-separated string) the bytes are valid in. One this
    // module does not implement is read as UTF-8.
    let candidates: Vec<String> = match args.get(2) {
        Some(v) if with_host(|h| h.is_array(v)) => with_host(|h| {
            h.array_pairs(v)
                .unwrap_or_default()
                .into_iter()
                .map(|(_, val)| normalize_encoding(&h.to_str(&val)))
                .collect()
        }),
        Some(v) if !matches!(v, Value::Undef) => str_arg(args, 2)
            .split(',')
            .map(|e| normalize_encoding(e.trim()))
            .collect(),
        _ => Vec::new(),
    };
    let valid_in = |cs: &str| match cs {
        "ASCII" => crate::bytes::to_bytes(&s).is_ascii(),
        "UTF-8" => crate::bytes::is_utf8(&s),
        _ => true,
    };
    let from = match candidates.as_slice() {
        [one] => one.clone(),
        many => many
            .iter()
            .find(|c| valid_in(c))
            .cloned()
            .unwrap_or_else(|| "UTF-8".to_string()),
    };
    let text: String = match from.as_str() {
        "ASCII" => crate::bytes::to_bytes(&s)
            .iter()
            .map(|&b| if b < 0x80 { char::from(b) } else { '?' })
            .collect(),
        "ISO-8859-1" => crate::bytes::to_bytes(&s)
            .iter()
            .map(|&b| char::from(b))
            .collect(),
        // Each maximal invalid subpart is one `?`.
        _ => crate::bytes::mb_text(&s).into_owned(),
    };
    Ok(match to.as_str() {
        "ASCII" => Value::str(
            text.chars()
                .map(|c| if c.is_ascii() { c } else { '?' })
                .collect::<String>(),
        ),
        "ISO-8859-1" => {
            let bytes: Vec<u8> = text
                .chars()
                .map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?'))
                .collect();
            Value::str(crate::bytes::from_bytes(&bytes))
        }
        _ => Value::str(text),
    })
}

/// The encodings `mb_convert_encoding` accepts as a target. phplang stores every
/// string as UTF-8, so the list is the set it can meaningfully produce plus the
/// spellings `normalize_encoding` folds into them.
const SUPPORTED_ENCODINGS: &[&str] = &["UTF-8", "ASCII", "ISO-8859-1"];

/// `mb_detect_encoding($string, $encodings = null, $strict = false)`. phplang
/// strings are always valid UTF-8, so detection reduces to: pure-ASCII input is
/// "ASCII", otherwise "UTF-8". A candidate list is honored in order (the first
/// candidate the string satisfies wins); the default order is `["ASCII","UTF-8"]`,
/// matching PHP's default `detect_order`.
fn mb_detect_encoding(args: &[Value]) -> Value {
    let s = str_arg(args, 0);
    let is_ascii = s.is_ascii();
    let candidates: Vec<String> = match args.get(1) {
        Some(v) if with_host(|h| h.is_array(v)) => with_host(|h| {
            h.array_pairs(v)
                .unwrap_or_default()
                .into_iter()
                .map(|(_, val)| normalize_encoding(&h.to_str(&val)))
                .collect()
        }),
        Some(v) if !matches!(v, Value::Undef) => str_arg(args, 1)
            .split(',')
            .map(|e| normalize_encoding(e.trim()))
            .collect(),
        _ => vec!["ASCII".to_string(), "UTF-8".to_string()],
    };
    for cand in &candidates {
        let ok = match cand.as_str() {
            "ASCII" => is_ascii,
            "UTF-8" => true, // always valid here
            _ => false,
        };
        if ok {
            return Value::str(cand.clone());
        }
    }
    Value::bool(false)
}

/// `mb_check_encoding($value = null, $encoding = null)`: whether `$value` is valid
/// in `$encoding`. UTF-8 is always valid (phplang strings are UTF-8); ASCII is
/// valid iff every byte is < 0x80. Defaults to the internal encoding.
fn mb_check_encoding(args: &[Value]) -> bool {
    let s = str_arg(args, 0);
    let enc = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => normalize_encoding(&str_arg(args, 1)),
        _ => normalize_encoding(&current_internal_encoding()),
    };
    match enc.as_str() {
        "ASCII" => s.is_ascii(),
        // A raw byte (see `crate::bytes`) is exactly a byte that is not UTF-8.
        "UTF-8" => crate::bytes::is_utf8(&s),
        _ => true,
    }
}

/// `mb_internal_encoding($encoding = null)`: getter (no arg) returns the stored
/// encoding; setter stores it and returns `true`. See the module note on the
/// thread-local reset-isolation caveat.
fn mb_internal_encoding(args: &[Value]) -> Value {
    match args.first() {
        Some(v) if !matches!(v, Value::Undef) => {
            let enc = str_arg(args, 0);
            INTERNAL_ENCODING.with(|e| *e.borrow_mut() = enc);
            Value::bool(true)
        }
        _ => Value::str(current_internal_encoding()),
    }
}

fn current_internal_encoding() -> String {
    INTERNAL_ENCODING.with(|e| e.borrow().clone())
}

/// Canonicalize an encoding label to one of "UTF-8" / "ASCII" / "ISO-8859-1".
fn normalize_encoding(name: &str) -> String {
    let up = name.trim().to_ascii_uppercase().replace('_', "-");
    match up.as_str() {
        "UTF-8" | "UTF8" => "UTF-8".to_string(),
        "US-ASCII" | "ASCII" => "ASCII".to_string(),
        "ISO-8859-1" | "LATIN1" | "LATIN-1" | "ISO8859-1" => "ISO-8859-1".to_string(),
        other => other.to_string(),
    }
}

// ── trimming / sub-string extraction / width trimming ────────────────────────

/// Every encoding name `mb_list_encodings()` reports for the reference build.
/// Only used to refuse an unknown `$encoding` argument; the data itself is
/// always treated as UTF-8 (see the module note).
const KNOWN_ENCODINGS: &[&str] = &[
    "BASE64",
    "UUENCODE",
    "HTML-ENTITIES",
    "QUOTED-PRINTABLE",
    "7BIT",
    "8BIT",
    "UCS-4",
    "UCS-4BE",
    "UCS-4LE",
    "UCS-2",
    "UCS-2BE",
    "UCS-2LE",
    "UTF-32",
    "UTF-32BE",
    "UTF-32LE",
    "UTF-16",
    "UTF-16BE",
    "UTF-16LE",
    "UTF-8",
    "UTF-7",
    "UTF7-IMAP",
    "ASCII",
    "EUC-JP",
    "SJIS",
    "EUCJP-WIN",
    "EUC-JP-2004",
    "SJIS-MOBILE#DOCOMO",
    "SJIS-MOBILE#KDDI",
    "SJIS-MOBILE#SOFTBANK",
    "SJIS-MAC",
    "SJIS-2004",
    "UTF-8-MOBILE#DOCOMO",
    "UTF-8-MOBILE#KDDI-A",
    "UTF-8-MOBILE#KDDI-B",
    "UTF-8-MOBILE#SOFTBANK",
    "CP932",
    "SJIS-WIN",
    "CP51932",
    "JIS",
    "ISO-2022-JP",
    "ISO-2022-JP-MS",
    "GB18030",
    "GB18030-2022",
    "WINDOWS-1252",
    "WINDOWS-1254",
    "ISO-8859-1",
    "ISO-8859-2",
    "ISO-8859-3",
    "ISO-8859-4",
    "ISO-8859-5",
    "ISO-8859-6",
    "ISO-8859-7",
    "ISO-8859-8",
    "ISO-8859-9",
    "ISO-8859-10",
    "ISO-8859-13",
    "ISO-8859-14",
    "ISO-8859-15",
    "ISO-8859-16",
    "EUC-CN",
    "CP936",
    "HZ",
    "EUC-TW",
    "BIG-5",
    "CP950",
    "EUC-KR",
    "UHC",
    "ISO-2022-KR",
    "WINDOWS-1251",
    "CP866",
    "KOI8-R",
    "KOI8-U",
    "ARMSCII-8",
    "CP850",
    "ISO-2022-JP-2004",
    "ISO-2022-JP-MOBILE#KDDI",
    "CP50220",
    "CP50221",
    "CP50222",
];

/// Refuse an `$encoding` argument (0-based index `at`) that names no encoding the
/// reference knows, with its `ValueError`.
fn check_encoding(fname: &str, args: &[Value], at: usize) -> Result<(), String> {
    match args.get(at) {
        None | Some(Value::Undef) => Ok(()),
        Some(_) => {
            let name = str_arg(args, at);
            if KNOWN_ENCODINGS.contains(&name.to_ascii_uppercase().as_str()) {
                Ok(())
            } else {
                Err(throws(
                    "ValueError",
                    format!(
                        "{fname}(): Argument #{} ($encoding) must be a valid encoding, \"{name}\" given",
                        at + 1
                    ),
                ))
            }
        }
    }
}

/// The code points `mb_trim` strips when no character list is given: NUL and the
/// Unicode `White_Space` set plus U+180E, as measured on the reference.
fn is_default_trim_char(c: char) -> bool {
    matches!(
        c as u32,
        0x0000 | 0x0009..=0x000D | 0x0020 | 0x0085 | 0x00A0 | 0x1680 | 0x180E
            | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000
    )
}

/// `mb_trim` / `mb_ltrim` / `mb_rtrim($string, $characters = null,
/// $encoding = null)` (PHP 8.4). `$characters` is a SET of code points — there is
/// no `..` range syntax as in `trim()`.
fn mb_trim(args: &[Value], fname: &str, left: bool, right: bool) -> Result<Value, String> {
    check_encoding(fname, args, 2)?;
    let s = str_arg(args, 0);
    let set: Option<Vec<char>> = match args.get(1) {
        None | Some(Value::Undef) => None,
        Some(_) => Some(str_arg(args, 1).chars().collect()),
    };
    let strip = |c: char| match &set {
        None => is_default_trim_char(c),
        Some(list) => list.contains(&c),
    };
    let mut out: &str = &s;
    if left {
        out = out.trim_start_matches(strip);
    }
    if right {
        out = out.trim_end_matches(strip);
    }
    Ok(Value::str(out.to_string()))
}

/// `mb_strstr` / `mb_stristr` / `mb_strrchr` / `mb_strrichr($haystack, $needle,
/// $before_needle = false, $encoding = null)`: the part of the haystack from (or
/// before) the first / last occurrence of the whole needle, or `false`.
fn mb_strstr(args: &[Value], fname: &str, ci: bool, last: bool) -> Result<Value, String> {
    check_encoding(fname, args, 3)?;
    let before = with_host(|h| h.is_truthy(&arg(args, 2)));
    let hay: Vec<char> = str_arg(args, 0).chars().collect();
    let (h_cmp, n_cmp) = ci_pair(args, ci);
    let nlen = n_cmp.len();
    if nlen > h_cmp.len() {
        return Ok(Value::bool(false));
    }
    let matches_at = |i: usize| h_cmp[i..].starts_with(&n_cmp[..]);
    let last_start = h_cmp.len() - nlen;
    let found = if last {
        (0..=last_start).rev().find(|&i| matches_at(i))
    } else {
        (0..=last_start).find(|&i| matches_at(i))
    };
    Ok(match found {
        None => Value::bool(false),
        Some(i) => {
            let part: String = if before { &hay[..i] } else { &hay[i..] }.iter().collect();
            Value::str(part)
        }
    })
}

/// `mb_strimwidth($string, $start, $width, $trim_marker = "", $encoding = null)`:
/// the string from character `$start`, cut so that it (and the marker that
/// replaces the cut part) fits in `$width` display columns.
fn mb_strimwidth(args: &[Value]) -> Result<Value, String> {
    check_encoding("mb_strimwidth", args, 4)?;
    let chars: Vec<char> = str_arg(args, 0).chars().collect();
    let mut start = int_arg(args, 1);
    let mut width = int_arg(args, 2);
    let marker = match args.get(3) {
        None | Some(Value::Undef) => String::new(),
        Some(_) => str_arg(args, 3),
    };
    let char_width = |c: char| mb_strwidth(&c.to_string()) as i64;
    let total: i64 = chars.iter().map(|&c| char_width(c)).sum();
    if start < 0 {
        start += chars.len() as i64;
    }
    if start < 0 || start > chars.len() as i64 {
        return Err(throws(
            "ValueError",
            "mb_strimwidth(): Argument #2 ($start) is out of range",
        ));
    }
    if width < 0 {
        with_host(|h| {
            h.deprecated(
                "mb_strimwidth(): passing a negative integer to argument #3 ($width) is deprecated",
            )
        });
        let skipped: i64 = chars[..start as usize].iter().map(|&c| char_width(c)).sum();
        width = total + width - skipped;
    }
    if width < 0 {
        return Err(throws(
            "ValueError",
            "mb_strimwidth(): Argument #3 ($width) is out of range",
        ));
    }
    let rest = &chars[start as usize..];
    let rest_width: i64 = rest.iter().map(|&c| char_width(c)).sum();
    if rest_width <= width {
        return Ok(Value::str(rest.iter().collect::<String>()));
    }
    let marker_width = mb_strwidth(&marker) as i64;
    let budget = (width - marker_width).max(0);
    let mut out = String::new();
    let mut used = 0;
    for &c in rest {
        let w = char_width(c);
        if used + w > budget {
            break;
        }
        used += w;
        out.push(c);
    }
    out.push_str(&marker);
    Ok(Value::str(out))
}

// ── numeric entities ─────────────────────────────────────────────────────────

/// The `[start, end, offset, mask]` quadruples of a conversion map, or the
/// reference's `ValueError` when the map's length is not a multiple of four.
fn convmap(fname: &str, args: &[Value]) -> Result<Vec<[i64; 4]>, String> {
    let pairs = with_host(|h| h.array_pairs(&arg(args, 1))).unwrap_or_default();
    if pairs.len() % 4 != 0 {
        return Err(throws(
            "ValueError",
            format!("{fname}(): Argument #2 ($map) must have a multiple of 4 elements"),
        ));
    }
    let nums: Vec<i64> =
        with_host(|h| pairs.iter().map(|(_, v)| h.to_number(v).to_int()).collect());
    Ok(nums.chunks(4).map(|c| [c[0], c[1], c[2], c[3]]).collect())
}

/// `mb_encode_numericentity($string, $map, $encoding = null, $hex = false)`:
/// every code point inside a map range becomes `&#N;` (or `&#xH;`) where `N` is
/// `(code point + offset) & mask`.
fn mb_encode_numericentity(args: &[Value]) -> Result<Value, String> {
    let map = convmap("mb_encode_numericentity", args)?;
    check_encoding("mb_encode_numericentity", args, 2)?;
    let hex = with_host(|h| h.is_truthy(&arg(args, 3)));
    let mut out = String::new();
    for c in str_arg(args, 0).chars() {
        let cp = c as i64;
        match map.iter().find(|m| cp >= m[0] && cp <= m[1]) {
            Some(m) => {
                let n = ((cp + m[2]) & m[3]) as u64;
                if hex {
                    out.push_str(&format!("&#x{n:X};"));
                } else {
                    out.push_str(&format!("&#{n};"));
                }
            }
            None => out.push(c),
        }
    }
    Ok(Value::str(out))
}

/// `mb_decode_numericentity($string, $map, $encoding = null)`: the inverse. An
/// entity is `&#` plus decimal digits, or `&#x` plus hex digits; its value minus
/// the map offset must fall inside the range for it to become a character, and a
/// terminating `;` is consumed only when the entity is decoded.
fn mb_decode_numericentity(args: &[Value]) -> Result<Value, String> {
    let map = convmap("mb_decode_numericentity", args)?;
    check_encoding("mb_decode_numericentity", args, 2)?;
    let s: Vec<char> = str_arg(args, 0).chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < s.len() {
        if s[i] == '&' && s.get(i + 1) == Some(&'#') {
            let hex = s.get(i + 2) == Some(&'x');
            let radix = if hex { 16 } else { 10 };
            let digits_at = i + 2 + usize::from(hex);
            let digits: String = s[digits_at..]
                .iter()
                .take_while(|c| c.is_digit(radix))
                .collect();
            let max_digits = if hex { 8 } else { 10 };
            if !digits.is_empty() && digits.len() <= max_digits {
                if let Ok(n) = i64::from_str_radix(&digits, radix) {
                    let end = digits_at + digits.len();
                    let decoded = map
                        .iter()
                        .map(|m| (n - m[2], m))
                        .find(|(v, m)| *v >= m[0] && *v <= m[1])
                        .and_then(|(v, _)| u32::try_from(v).ok().and_then(char::from_u32));
                    if let Some(c) = decoded {
                        out.push(c);
                        i = if s.get(end) == Some(&';') {
                            end + 1
                        } else {
                            end
                        };
                        continue;
                    }
                }
            }
        }
        out.push(s[i]);
        i += 1;
    }
    Ok(Value::str(out))
}