tsuki 0.4.8

Lua 5.4 ported to Rust
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
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
//! Implementation of [string library](https://www.lua.org/manual/5.4/manual.html#6.4).
use crate::context::{Arg, Args, Context, Ret};
use crate::{Buffer, Float, Fp, LuaFn, Nil, Number, Str, Table, Type, Value};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cmp::min;
use core::ffi::{c_double, c_float, c_int, c_long, c_short};
use core::fmt::Write;
use core::iter::Peekable;
use core::num::NonZero;
use memchr::memchr;

mod pack;

/// Implementation of `__add` metamethod for string.
pub fn add<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__add", |cx, lhs, rhs| {
        cx.push_add(lhs, rhs).map(|_| ())
    })
}

/// Implementation of [string.byte](https://www.lua.org/manual/5.4/manual.html#pdf-string.byte).
pub fn byte<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let s = cx.arg(1).to_str()?.as_bytes();
    let pi = cx.arg(2).to_nilable_int(false)?.unwrap_or(1);
    let pose = cx.arg(3).to_nilable_int(false)?.unwrap_or(pi);
    let l = s.len() as i64;
    let posi = posrelatI(pi, l);
    let pose = getendpos(pose, l);

    if posi.get() > pose {
        return Ok(cx.into());
    }

    // Reserve stack.
    let posi = posi.get() as usize; // posi guarantee to not exceed the length of string.
    let pose = pose as usize; // Same here.
    let n = pose - posi + 1;

    if cx.reserve(n).is_err() {
        return Err("string slice too long".into());
    }

    for i in 0..n {
        cx.push(s[posi - 1 + i])?;
    }

    Ok(cx.into())
}

/// Implementation of [string.char](https://www.lua.org/manual/5.4/manual.html#pdf-string.char).
pub fn char<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let n = cx.args();
    let mut b = Vec::with_capacity(n);

    for i in 1..=n {
        let arg = cx.arg(i);
        let val = arg.to_int()? as u64;
        let val = val
            .try_into()
            .map_err(|_| arg.error("value out of range"))?;

        b.push(val);
    }

    cx.push_bytes(b)?;

    Ok(cx.into())
}

/// Implementation of `__div` metamethod for string.
pub fn div<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__div", |cx, lhs, rhs| {
        let r = cx.thread().div(lhs, rhs)?;

        cx.push(r)?;

        Ok(())
    })
}

/// Implementation of [string.find](https://www.lua.org/manual/5.4/manual.html#pdf-string.find).
///
/// Note that class `z` is not supported.
pub fn find<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    str_find_aux(cx, true)
}

/// Implementation of [string.format](https://www.lua.org/manual/5.4/manual.html#pdf-string.format).
///
/// The main differences from Lua is:
///
/// - First argument accept only a UTF-8 string.
/// - `a`, `A`, `e`, `E`, `g` and `G` format is not supported.
/// - `q` format requires string value to be UTF-8 and will use decimal notation instead of
///   hexadecimal exponent notation for float.
/// - Format have unlimited length.
pub fn format<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    // Get format.
    let mut next = 1;
    let arg = cx.arg(next);
    let fmt = arg.to_str()?;
    let fmt = fmt
        .as_utf8()
        .ok_or_else(|| arg.error("expect UTF-8 string"))?;

    // Parse format.
    let mut res = Vec::with_capacity(fmt.len() * 2);
    let mut buf = Buffer::default();
    let mut iter = fmt.chars();

    while let Some(ch) = iter.next() {
        // Check if '%'.
        if ch != '%' {
            res.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
            continue;
        }

        // Check if '%%.
        let start = iter.as_str();
        let mut len = 1;
        let mut ch = match iter.next() {
            Some('%') => {
                res.push(b'%');
                continue;
            }
            Some(v) => v,
            None => return Err("invalid conversion '%' to 'format'".into()),
        };

        // Parse flags.
        let mut left = false;
        let mut sign = Sign::Negative;
        let mut alt = false;
        let mut lz = false;

        loop {
            match ch {
                '-' => left = true,
                '+' => sign = Sign::Always,
                ' ' => match sign {
                    Sign::Always => (),
                    Sign::SpaceIfPositive => (),
                    Sign::Negative => sign = Sign::SpaceIfPositive,
                },
                '#' => alt = true,
                '0' => lz = true,
                _ => break,
            };

            ch = match iter.next() {
                Some(v) => v,
                None => return Err(format!("invalid conversion '%{start}' to 'format'").into()),
            };

            len += 1;
        }

        // Parse width. Lua does not support '*'.
        let width = if ch.is_ascii_digit() {
            // The value is never be '0' when we are here.
            let mut v = (ch as u8) - b'0';

            ch = match iter.next() {
                Some(v) => v,
                None => return Err(format!("invalid conversion '%{start}' to 'format'").into()),
            };

            len += 1;

            // Lua limit 2 digits for width.
            if ch.is_ascii_digit() {
                v *= 10;
                v += (ch as u8) - b'0';

                ch = match iter.next() {
                    Some(v) => v,
                    None => return Err(format!("invalid conversion '%{start}' to 'format'").into()),
                };

                len += 1;
            }

            Some(NonZero::new(v).unwrap())
        } else {
            None
        };

        // Parse precision.
        let precision = if ch == '.' {
            ch = match iter.next() {
                Some(v) => v,
                None => return Err(format!("invalid conversion '%{start}' to 'format'").into()),
            };

            len += 1;

            // Lua does not support '*'.
            if ch.is_ascii_digit() {
                let mut p = (ch as u8) - b'0';

                ch = match iter.next() {
                    Some(v) => v,
                    None => return Err(format!("invalid conversion '%{start}' to 'format'").into()),
                };

                len += 1;

                // Lua limit 2 digits for width.
                if ch.is_ascii_digit() {
                    p *= 10;
                    p += (ch as u8) - b'0';

                    ch = match iter.next() {
                        Some(v) => v,
                        None => {
                            return Err(format!("invalid conversion '%{start}' to 'format'").into());
                        }
                    };

                    len += 1;
                }

                Some(p.into())
            } else {
                Some(0)
            }
        } else {
            None
        };

        // Check if argument exists.
        next += 1;

        if next > cx.args() {
            return Err(cx.arg(next).error("no value"));
        }

        // Parse format.
        let arg = cx.arg(next);
        let fmt = &start[..len];

        buf.clear();

        match ch {
            'c' if sign == Sign::Negative && !alt && !lz && precision.is_none() => {
                buf.push(arg.to_int()? as u8);
            }
            'd' | 'i' if !alt => {
                let n = arg.to_int()?;
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                match precision {
                    Some(p) if p == 0 && n == 0 => {
                        // Produce empty data.
                    }
                    Some(p) => match sign {
                        Sign::Always => {
                            buf.push(if n >= 0 { b'+' } else { b'-' });

                            write!(buf, "{:01$}", n.unsigned_abs(), p).unwrap();
                        }
                        Sign::SpaceIfPositive => {
                            buf.push(if n >= 0 { b' ' } else { b'-' });

                            write!(buf, "{:01$}", n.unsigned_abs(), p).unwrap();
                        }
                        Sign::Negative => {
                            if n < 0 {
                                buf.push(b'-');
                            }

                            write!(buf, "{:01$}", n.unsigned_abs(), p).unwrap();
                        }
                    },
                    None => match (sign, lz) {
                        (Sign::Always, true) => write!(buf, "{:+01$}", n, w).unwrap(),
                        (Sign::Always, false) => write!(buf, "{:+}", n).unwrap(),
                        (Sign::SpaceIfPositive, true) => match n >= 0 {
                            true => write!(buf, " {:01$}", n, w).unwrap(),
                            false => write!(buf, "{:01$}", n, w).unwrap(),
                        },
                        (Sign::SpaceIfPositive, false) => match n >= 0 {
                            true => write!(buf, " {}", n).unwrap(),
                            false => write!(buf, "{}", n).unwrap(),
                        },
                        (Sign::Negative, true) => write!(buf, "{:01$}", n, w).unwrap(),
                        (Sign::Negative, false) => write!(buf, "{}", n).unwrap(),
                    },
                }
            }
            'u' if sign == Sign::Negative && !alt => {
                let n = arg.to_int()? as u64;
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                match precision {
                    Some(p) if p == 0 && n == 0 => {
                        // Produce empty data.
                    }
                    Some(p) => write!(buf, "{:01$}", n, p).unwrap(),
                    None => match lz {
                        true => write!(buf, "{:01$}", n, w).unwrap(),
                        false => write!(buf, "{}", n).unwrap(),
                    },
                }
            }
            'o' if sign == Sign::Negative => {
                let n = arg.to_int()? as u64;
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                match precision {
                    Some(p) if p == 0 && n == 0 => {
                        if alt {
                            buf.push(b'0');
                        }
                    }
                    Some(p) => write!(buf, "{:01$o}", n, p).unwrap(),
                    None => match lz {
                        true => write!(buf, "{:01$o}", n, w).unwrap(),
                        false => write!(buf, "{:o}", n).unwrap(),
                    },
                }

                if alt && buf[0] != b'0' {
                    buf.insert(0, b'0');
                }
            }
            'x' if sign == Sign::Negative => {
                let n = arg.to_int()? as u64;
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                if n != 0 && alt {
                    buf.extend_from_slice(b"0x");
                }

                match precision {
                    Some(p) if p == 0 && n == 0 => {
                        // Produce empty data.
                    }
                    Some(p) => write!(buf, "{:01$x}", n, p).unwrap(),
                    None => match lz {
                        true => write!(buf, "{:01$x}", n, w).unwrap(),
                        false => write!(buf, "{:x}", n).unwrap(),
                    },
                }
            }
            'X' if sign == Sign::Negative => {
                let n = arg.to_int()? as u64;
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                if n != 0 && alt {
                    buf.extend_from_slice(b"0X");
                }

                match precision {
                    Some(p) if p == 0 && n == 0 => {
                        // Produce empty data.
                    }
                    Some(p) => write!(buf, "{:01$X}", n, p).unwrap(),
                    None => match lz {
                        true => write!(buf, "{:01$X}", n, w).unwrap(),
                        false => write!(buf, "{:X}", n).unwrap(),
                    },
                }
            }
            'f' => {
                let Float(n) = arg.to_float()?;
                let p = precision.unwrap_or(6);
                let w = width.map(|v| v.get()).unwrap_or(0).into();
                let lz = if left || w == 0 { false } else { lz };

                match (sign, lz) {
                    (Sign::Always, true) => write!(buf, "{:+02$.1$}", n, p, w).unwrap(),
                    (Sign::Always, false) => write!(buf, "{:+.1$}", n, p).unwrap(),
                    (Sign::SpaceIfPositive, true) => {
                        if n >= 0.0 {
                            buf.push(b' ');
                        }

                        write!(buf, "{:02$.1$}", n, p, w).unwrap()
                    }
                    (Sign::SpaceIfPositive, false) => {
                        if n >= 0.0 {
                            buf.push(b' ');
                        }

                        write!(buf, "{:.1$}", n, p).unwrap()
                    }
                    (Sign::Negative, true) => write!(buf, "{:02$.1$}", n, p, w).unwrap(),
                    (Sign::Negative, false) => write!(buf, "{:.1$}", n, p).unwrap(),
                }

                if alt {}
            }
            'p' if sign == Sign::Negative && !alt && !lz && precision.is_none() => {
                let p = arg.as_ptr();

                match p.is_null() {
                    true => buf.extend_from_slice(b"(null)"),
                    false => write!(buf, "{:p}", p).unwrap(),
                }
            }
            'q' => {
                if len != 1 {
                    return Err("specifier '%q' cannot have modifiers".into());
                }

                match arg.ty() {
                    Some(Type::String) => {
                        let s = arg
                            .get_str()?
                            .as_utf8()
                            .ok_or_else(|| arg.error("specifier '%q' requires UTF-8 string"))?;
                        let mut iter = s.chars().peekable();

                        buf.push(b'"');

                        while let Some(ch) = iter.next() {
                            if ch == '"' || ch == '\\' || ch == '\n' {
                                buf.push(b'\\');
                                buf.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
                            } else if ch.is_ascii_control() {
                                if iter.peek().is_none_or(|&b| !b.is_ascii_digit()) {
                                    write!(buf, "\\{}", ch as i32).unwrap();
                                } else {
                                    write!(buf, "\\{:03}", ch as i32).unwrap();
                                }
                            } else {
                                buf.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
                            }
                        }

                        buf.push(b'"');
                    }
                    Some(Type::Number) => match arg.as_int(false) {
                        Some(n) if n == i64::MIN => write!(buf, "{:#x}", n).unwrap(),
                        Some(n) => write!(buf, "{}", n).unwrap(),
                        None => {
                            let Float(n) = arg.to_float()?;

                            if n == f64::INFINITY {
                                buf.extend_from_slice(b"1e9999");
                            } else if n == -f64::INFINITY {
                                buf.extend_from_slice(b"-1e9999");
                            } else if n != n {
                                buf.extend_from_slice(b"(0/0)");
                            } else {
                                write!(buf, "{}", n).unwrap();
                            }
                        }
                    },
                    Some(Type::Nil) | Some(Type::Boolean) => {
                        // Use display() to honor metatable (if any).
                        let s = arg.display()?;

                        buf.extend_from_slice(s.as_bytes());
                    }
                    _ => return Err(arg.error("value has no literal form")),
                }
            }
            's' if sign == Sign::Negative && !alt && !lz => {
                let s = arg.display()?;
                let v = s.as_bytes();

                if len == 1 {
                    buf.extend_from_slice(v);
                } else if v.contains(&0) {
                    return Err(arg.error("string contains zeros"));
                } else if let Some(p) = precision {
                    let l = min(p, v.len());

                    buf.extend_from_slice(&v[..l]);
                } else {
                    buf.extend_from_slice(v);
                }
            }
            _ => return Err(format!("invalid conversion '%{fmt}' to 'format'").into()),
        }

        // Apply width.
        match width {
            Some(w) if buf.len() < w.get().into() => match left {
                true => {
                    res.extend_from_slice(&buf);

                    for _ in 0..(usize::from(w.get()) - buf.len()) {
                        res.push(b' ');
                    }
                }
                false => {
                    for _ in 0..(usize::from(w.get()) - buf.len()) {
                        res.push(b' ');
                    }

                    res.extend_from_slice(&buf);
                }
            },
            _ => res.extend_from_slice(&buf),
        }
    }

    cx.push_bytes(res)?;

    Ok(cx.into())
}

/// Implementation of [string.gsub](https://www.lua.org/manual/5.4/manual.html#pdf-string.gsub).
///
/// Note that class `z` is not supported.
pub fn gsub<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let arg1 = cx.arg(1);
    let src = arg1.to_str()?.as_bytes();
    let mut p = cx.arg(2).to_str()?.as_bytes();
    let tr = cx.arg(3);
    let max_s = cx
        .arg(4)
        .to_nilable_int(false)?
        .unwrap_or((src.len() + 1) as i64);
    let anchor = p.first().copied() == Some(b'^');
    let mut n = 0;
    let mut changed = false;
    let mut b = Vec::new();
    let mut ms = MatchState::prepstate(src);
    let mut off = 0;
    let mut lastmatch = usize::MAX;
    let tr = if let Some(v) = tr.as_str(true) {
        Replacement::Str(v)
    } else if let Some(v) = tr.as_table() {
        Replacement::Table(v)
    } else if let Some(v) = tr.as_fp() {
        Replacement::Fp(v)
    } else if let Some(v) = tr.as_lua_fn() {
        Replacement::LuaFn(v)
    } else {
        return Err(tr.invalid_type("string/function/table"));
    };

    if anchor {
        p = &p[1..];
    }

    while n < max_s {
        ms.reprepstate();

        if let Some(e) = ms.match_0(off, p)?
            && e != lastmatch
        {
            n += 1;
            changed |= ms.add_value(&cx, &mut b, off, e, &tr)?;
            lastmatch = e;
            off = lastmatch;
        } else {
            if !(off < src.len()) {
                break;
            }

            b.push(src[off]);
            off += 1;
        }

        if anchor {
            break;
        }
    }

    if !changed {
        cx.push(arg1)?;
    } else {
        b.extend_from_slice(&src[off..]);
        cx.push_bytes(b)?;
    }

    cx.push(n)?;

    Ok(cx.into())
}

/// Implementation of [string.len](https://www.lua.org/manual/5.4/manual.html#pdf-string.len).
pub fn len<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let l = cx.arg(1).to_str()?.len();

    cx.push(l as i64)?;

    Ok(cx.into())
}

/// Implementation of [string.lower](https://www.lua.org/manual/5.4/manual.html#pdf-string.lower).
pub fn lower<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let mut s = cx.arg(1).to_str()?.as_bytes().to_vec();

    for b in &mut s {
        b.make_ascii_lowercase();
    }

    cx.push_bytes(s)?;

    Ok(cx.into())
}

/// Implementation of [string.match](https://www.lua.org/manual/5.4/manual.html#pdf-string.match).
pub fn r#match<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    str_find_aux(cx, false)
}

/// Implementation of `__mul` metamethod for string.
pub fn mul<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__mul", |cx, lhs, rhs| {
        let r = cx.thread().mul(lhs, rhs)?;

        cx.push(r)?;

        Ok(())
    })
}

/// Implementation of `__unm` metamethod for string.
pub fn negate<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__unm", |cx, v, _| cx.push_neg(v).map(|_| ()))
}

/// Implementation of [string.pack](https://www.lua.org/manual/5.4/manual.html#pdf-string.pack).
pub fn pack<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    // Check if UTF-8.
    let arg = cx.arg(1);
    let fmt = arg
        .to_str()?
        .as_utf8()
        .ok_or_else(|| arg.error("expect UTF-8 string"))?;

    // Parse.
    let mut fmt = fmt.chars().take_while(|&c| c != '\0').peekable();
    let mut h = Header::new();
    let mut next = 1;
    let mut totalsize = 0;
    let mut b = Vec::new();

    while let Some(first) = fmt.next() {
        // Parse format.
        let mut ntoalign = 0;
        let opt = h
            .getdetails(totalsize, first, &mut fmt, &mut ntoalign)
            .map_err(|e| arg.error(e))?;

        for _ in 0..ntoalign {
            b.push(0);
        }

        next += 1;

        // Process.
        let arg = cx.arg(next);

        totalsize += ntoalign;
        totalsize += match opt {
            Pack::Signed(size) => {
                let n = arg.to_int()?;

                if size < size_of::<i64>() {
                    let lim = 1i64 << size * 8 - 1;

                    if !(-lim <= n && n < lim) {
                        return Err(arg.error("integer overflow"));
                    }
                }

                self::pack::packint(&mut b, n as u64, h.islittle, size, n < 0);

                size
            }
            Pack::Unsigned(size) => {
                let n = arg.to_int()?;

                if size < size_of::<i64>() {
                    if !((n as u64) < 1u64 << size * 8) {
                        return Err(arg.error("unsigned overflow"));
                    }
                }

                self::pack::packint(&mut b, n as u64, h.islittle, size, false);

                size
            }
            Pack::Float => {
                let f = arg.to_float()?.0 as c_float;

                self::pack::extend_with_endian(&mut b, f.to_ne_bytes(), h.islittle);

                size_of::<c_float>()
            }
            Pack::Double => {
                let f = arg.to_float()?.0 as c_double;

                self::pack::extend_with_endian(&mut b, f.to_ne_bytes(), h.islittle);

                size_of::<c_double>()
            }
            Pack::Number => {
                let Float(f) = arg.to_float()?;

                self::pack::extend_with_endian(&mut b, f.to_ne_bytes(), h.islittle);

                size_of::<f64>()
            }
            Pack::Char(size) => {
                let s = arg.to_str()?;
                let len = s.len();

                if len > size {
                    return Err(arg.error("string longer than given size"));
                }

                b.extend_from_slice(s.as_bytes());

                for _ in len..size {
                    b.push(0);
                }

                size
            }
            Pack::Str(Some(size)) => {
                let s = arg.to_str()?;
                let len = s.len();

                if !(size >= size_of::<usize>() || len < (1usize) << size * 8) {
                    return Err(arg.error("string length does not fit in given size"));
                }

                self::pack::packint(&mut b, len as u64, h.islittle, size, false);

                b.extend_from_slice(s.as_bytes());

                size + len
            }
            Pack::Str(None) => {
                let s = arg.to_str()?;
                let len = s.len();
                let s = s.as_bytes();

                if memchr(0, s).is_some() {
                    return Err(arg.error("string contains zeros"));
                }

                b.extend_from_slice(s);
                b.push(0);

                len + 1
            }
            Pack::Padding(size) => {
                for _ in 0..size {
                    b.push(0);
                }

                next -= 1;

                size
            }
            Pack::PadAlign | Pack::Nop => {
                next -= 1;
                0
            }
        };
    }

    cx.push_bytes(b)?;

    Ok(cx.into())
}

/// Implementation of [string.packsize](https://www.lua.org/manual/5.4/manual.html#pdf-string.packsize).
///
/// Note that first argumebnt must be UTF-8 and format error always report as argument error.
pub fn packsize<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    // Check if UTF-8.
    let arg = cx.arg(1);
    let fmt = arg
        .to_str()?
        .as_utf8()
        .ok_or_else(|| arg.error("expect UTF-8 string"))?;

    // Parse.
    let mut fmt = fmt.chars().take_while(|&c| c != '\0').peekable();
    let mut h = Header::new();
    let mut totalsize = 0;

    while let Some(first) = fmt.next() {
        let mut ntoalign = 0;
        let mut size = match h
            .getdetails(totalsize, first, &mut fmt, &mut ntoalign)
            .map_err(|e| arg.error(e))?
        {
            Pack::Signed(v) => v,
            Pack::Unsigned(v) => v,
            Pack::Float => size_of::<c_float>(),
            Pack::Double => size_of::<c_double>(),
            Pack::Number => size_of::<f64>(),
            Pack::Char(v) => v,
            Pack::Str(_) => return Err(arg.error("variable-length format")),
            Pack::Padding(v) => v,
            Pack::PadAlign => 0,
            Pack::Nop => 0,
        };

        size += ntoalign;

        if totalsize > 2147483647usize.wrapping_sub(size) {
            return Err(arg.error("format result too large"));
        }

        totalsize = totalsize.wrapping_add(size);
    }

    cx.push(totalsize as i64)?;

    Ok(cx.into())
}

/// Implementation of `__pow` metamethod for string.
pub fn pow<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__pow", |cx, lhs, rhs| {
        cx.push_pow(lhs, rhs).map(|_| ())
    })
}

/// Implementation of `__mod` metamethod for string.
pub fn rem<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__mod", |cx, lhs, rhs| {
        cx.push_rem(lhs, rhs).map(|_| ())
    })
}

/// Implementation of [string.rep](https://www.lua.org/manual/5.4/manual.html#pdf-string.rep).
pub fn rep<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    // Check n.
    let n = cx.arg(2).to_int()?;

    if n <= 0 {
        cx.push_str("")?;

        return Ok(cx.into());
    }

    // Check length.
    let s = cx.arg(1).to_str()?;
    let sep = cx.arg(3).to_nilable_str(false)?;
    let lsep = sep.map(|v| v.len()).unwrap_or(0);

    if !s
        .len()
        .checked_add(lsep)
        .is_some_and(move |v| v <= (0x7FFFFFFF / n) as usize)
    {
        return Err("resulting string too large".into());
    }

    // Build string.
    let len = n as usize * s.len() + (n - 1) as usize * lsep;

    match (s.as_utf8(), sep.map(|v| v.as_utf8()).unwrap_or(Some(""))) {
        (Some(s), Some(sep)) => {
            let mut b = String::with_capacity(len);

            for _ in 0..(n - 1) {
                b.push_str(s);
                b.push_str(sep);
            }

            b.push_str(s);

            cx.push_str(b)?;
        }
        _ => {
            let s = s.as_bytes();
            let sep = sep.map(|v| v.as_bytes()).unwrap_or(b"");
            let mut b = Vec::with_capacity(len);

            for _ in 0..(n - 1) {
                b.extend_from_slice(s);
                b.extend_from_slice(sep);
            }

            b.extend_from_slice(s);

            cx.push_bytes(b)?;
        }
    }

    Ok(cx.into())
}

/// Implementation of
/// [string.reverse](https://www.lua.org/manual/5.4/manual.html#pdf-string.reverse).
pub fn reverse<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let mut s = cx.arg(1).to_str()?.as_bytes().to_vec();

    s.reverse();

    cx.push_bytes(s)?;

    Ok(cx.into())
}

/// Implementation of [string.sub](https://www.lua.org/manual/5.4/manual.html#pdf-string.sub).
pub fn sub<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let s = cx.arg(1).to_str()?;
    let s = s.as_bytes();
    let start = cx.arg(2).to_int()?;
    let start = posrelatI(start, s.len().try_into().unwrap()).get();
    let end = cx.arg(3).to_nilable_int(false)?.unwrap_or(-1);
    let end = getendpos(end, s.len().try_into().unwrap());
    let s = if start <= end {
        let start = usize::try_from(start).unwrap();
        let end = usize::try_from(end).unwrap();
        let len = end - start + 1;

        &s[(start - 1)..][..len]
    } else {
        b""
    };

    cx.push_bytes(s)?;

    Ok(cx.into())
}

/// Implementation of `__sub` metamethod for string.
pub fn subtract<D>(cx: Context<D, Args>) -> Result<Context<D, Ret>, Box<dyn core::error::Error>> {
    arith(cx, "__sub", |cx, lhs, rhs| {
        cx.push_sub(lhs, rhs).map(|_| ())
    })
}

/// Implementation of [string.unpack](https://www.lua.org/manual/5.4/manual.html#pdf-string.unpack).
pub fn unpack<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let fmt = cx.arg(1).to_utf8()?;
    let arg = cx.arg(2);
    let data = arg.to_str()?.as_bytes();
    let pos = cx.arg(3);
    let ld = data.len();
    let mut pos = match posrelatI(pos.to_nilable_int(false)?.unwrap_or(1), ld as i64).get() - 1 {
        v if v > (ld as u64) => return Err(pos.error("initial position out of string")),
        v => v as usize,
    };

    // Parse.
    let mut fmt = fmt.chars().take_while(|&c| c != '\0').peekable();
    let mut h = Header::new();

    while let Some(first) = fmt.next() {
        let mut ntoalign = 0;
        let opt = h.getdetails(pos, first, &mut fmt, &mut ntoalign)?;

        pos += ntoalign;
        pos += match opt {
            Pack::Signed(size) => {
                let res = data
                    .get(pos..(pos + size))
                    .ok_or_else(|| "data string too short".into())
                    .and_then(|v| self::pack::unpackint(v, h.islittle, true))
                    .map_err(|e| arg.error(e))?;

                cx.push(res)?;

                size
            }
            Pack::Unsigned(size) => {
                let res = data
                    .get(pos..(pos + size))
                    .ok_or_else(|| "data string too short".into())
                    .and_then(|v| self::pack::unpackint(v, h.islittle, false))
                    .map_err(|e| arg.error(e))?;

                cx.push(res)?;

                size
            }
            Pack::Float => {
                let mut data: [u8; size_of::<c_float>()] = data
                    .get(pos..(pos + size_of::<c_float>()))
                    .ok_or_else(|| arg.error("data string too short"))?
                    .try_into()
                    .unwrap();

                if h.islittle != cfg!(target_endian = "little") {
                    data.reverse();
                }

                cx.push(c_float::from_ne_bytes(data))?;

                size_of::<c_float>()
            }
            Pack::Number => {
                let mut data: [u8; size_of::<f64>()] = data
                    .get(pos..(pos + size_of::<f64>()))
                    .ok_or_else(|| arg.error("data string too short"))?
                    .try_into()
                    .unwrap();

                if h.islittle != cfg!(target_endian = "little") {
                    data.reverse();
                }

                cx.push(f64::from_ne_bytes(data))?;

                size_of::<f64>()
            }
            Pack::Double => {
                let mut data: [u8; size_of::<c_double>()] = data
                    .get(pos..(pos + size_of::<c_double>()))
                    .ok_or_else(|| arg.error("data string too short"))?
                    .try_into()
                    .unwrap();

                if h.islittle != cfg!(target_endian = "little") {
                    data.reverse();
                }

                cx.push(c_double::from_ne_bytes(data))?;

                size_of::<c_double>()
            }
            Pack::Char(size) => {
                let data = data
                    .get(pos..(pos + size))
                    .ok_or_else(|| arg.error("data string too short"))?;

                cx.push_bytes(data)?;

                size
            }
            Pack::Str(Some(size)) => {
                let len = data
                    .get(pos..(pos + size))
                    .ok_or_else(|| "data string too short".into())
                    .and_then(|v| self::pack::unpackint(v, h.islittle, false))
                    .map_err(|e| arg.error(e))? as usize;
                let data = data
                    .get((pos + size)..)
                    .and_then(move |v| v.get(..len))
                    .ok_or_else(|| arg.error("data string too short"))?;

                cx.push_bytes(data)?;

                size + len
            }
            Pack::Str(None) => {
                let data = data
                    .get(pos..)
                    .ok_or_else(|| "data string too short".into())
                    .and_then(|v| match memchr(0, v) {
                        Some(i) => Ok(unsafe { v.get_unchecked(..i) }),
                        None => Err("unfinished string for format 'z'".into()),
                    })
                    .map_err(|e: Box<dyn core::error::Error>| arg.error(e))?;

                cx.push_bytes(data)?;

                data.len() + 1
            }
            Pack::Padding(size) => size,
            Pack::PadAlign | Pack::Nop => 0,
        };
    }

    cx.push((pos + 1) as i64)?;

    Ok(cx.into())
}

/// Implementation of [string.upper](https://www.lua.org/manual/5.4/manual.html#pdf-string.upper).
pub fn upper<A>(cx: Context<A, Args>) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let s = cx.arg(1).to_str()?;
    let mut s = s.as_bytes().to_vec();

    for b in &mut s {
        b.make_ascii_uppercase();
    }

    cx.push_bytes(s)?;

    Ok(cx.into())
}

fn arith<'a, A>(
    cx: Context<'a, A, Args>,
    mt: &str,
    f: impl FnOnce(&Context<'a, A, Args>, Number, Number) -> Result<(), Box<dyn core::error::Error>>,
) -> Result<Context<'a, A, Ret>, Box<dyn core::error::Error>> {
    // Get first operand.
    let lhs = cx.arg(1);
    let lhs = match tonum(&lhs) {
        Some(v) => v,
        None => return trymt(cx, mt),
    };

    // Get second operand.
    let rhs = cx.arg(2);
    let rhs = match tonum(&rhs) {
        Some(v) => v,
        None => return trymt(cx, mt),
    };

    f(&cx, lhs, rhs)?;

    Ok(cx.into())
}

fn tonum<A>(arg: &Arg<A>) -> Option<Number> {
    if let Some(v) = arg.as_num() {
        Some(v)
    } else if let Some(v) = arg.as_str(false) {
        v.to_num()
    } else {
        None
    }
}

fn trymt<'a, A>(
    cx: Context<'a, A, Args>,
    name: &str,
) -> Result<Context<'a, A, Ret>, Box<dyn core::error::Error>> {
    // Get metamethod.
    let lhs = cx.arg(1);
    let rhs = cx.arg(2);
    let mt = (rhs.ty() != Some(Type::String)).then(|| rhs.metatable().unwrap());
    let mt = match mt
        .as_ref()
        .and_then(|t| t.as_ref())
        .and_then(|t| match t.get_str_key(name) {
            Value::Nil => None,
            v => Some(v),
        }) {
        Some(v) => v,
        None => {
            let e = format!(
                "attempt to {} a '{}' with a '{}'",
                &name[2..],
                lhs.ty().unwrap(),
                rhs.ty().unwrap()
            );

            return Err(e.into());
        }
    };

    // Prepare to call metamethod.
    cx.push(mt)?;
    cx.push(lhs)?;
    cx.push(rhs)?;

    // Call metamethod.
    let mut cx = match cx.forward(-3) {
        (_, Some(e)) => return Err(e),
        (cx, _) => cx,
    };

    cx.truncate(1);

    Ok(cx)
}

fn str_find_aux<A>(
    cx: Context<A, Args>,
    find: bool,
) -> Result<Context<A, Ret>, Box<dyn core::error::Error>> {
    let s = cx.arg(1).to_str()?;
    let s = s.as_bytes();
    let p = cx.arg(2).to_str()?;
    let mut p = p.as_bytes();
    let init = cx.arg(3).to_nilable_int(false)?.unwrap_or(1);
    let ls = s.len().try_into().unwrap();
    let lp = p.len();
    let init = posrelatI(init, ls).get() - 1;

    if init > ls as u64 {
        cx.push(Nil)?;

        return Ok(cx.into());
    }

    // When we are here init guarantee to fit in usize.
    let mut init = init as usize;

    if find && (cx.arg(4).to_bool() == Some(true) || nospecials(p)) {
        if let Some(i) = memchr::memmem::find(&s[init..], p) {
            let i = init + i;

            cx.push((i + 1) as i64)?;
            cx.push((i + lp) as i64)?;

            return Ok(cx.into());
        }
    } else {
        let mut ms = MatchState::prepstate(s);
        let anchor = p.first().copied() == Some(b'^');

        if anchor {
            p = &p[1..];
        }

        loop {
            ms.reprepstate();

            if let Some(res) = ms.match_0(init, p)? {
                if find {
                    cx.push((init + 1) as i64)?;
                    cx.push(res as i64)?;

                    ms.push_captures(&cx, None, None)?;
                } else {
                    ms.push_captures(&cx, Some(init), Some(res))?;
                }

                return Ok(cx.into());
            }

            let fresh4 = init;

            init += 1;

            if !(fresh4 < s.len() && !anchor) {
                break;
            }
        }
    }

    cx.push(Nil)?;

    Ok(cx.into())
}

fn nospecials(p: &[u8]) -> bool {
    let m = |b| {
        b == b'^'
            || b == b'$'
            || b == b'*'
            || b == b'+'
            || b == b'?'
            || b == b'.'
            || b == b'('
            || b == b'['
            || b == b'%'
            || b == b'-'
    };

    if p.iter().copied().any(m) {
        return false;
    }

    true
}

// TODO: Find a better name.
#[allow(non_snake_case)]
fn posrelatI(pos: i64, len: i64) -> NonZero<u64> {
    let r = if pos > 0 {
        pos as u64
    } else if pos == 0 {
        1
    } else if pos < -len {
        1
    } else {
        (len + pos + 1).try_into().unwrap()
    };

    NonZero::new(r).unwrap()
}

fn getendpos(pos: i64, len: i64) -> u64 {
    if pos > len {
        len.try_into().unwrap()
    } else if pos >= 0 {
        pos as u64
    } else if pos < -len {
        0
    } else {
        (len + pos + 1).try_into().unwrap()
    }
}

struct MatchState<'a> {
    src: &'a [u8],
    matchdepth: i32,
    capture: Vec<MatchCapture>,
}

impl<'a> MatchState<'a> {
    fn prepstate(s: &'a [u8]) -> Self {
        Self {
            src: s,
            matchdepth: 200,
            capture: Vec::with_capacity(32),
        }
    }

    fn reprepstate(&mut self) {
        self.capture.clear();
    }

    fn match_0(
        &mut self,
        mut off: usize,
        mut p: &[u8],
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        // Check depth.
        if self.matchdepth == 0 {
            return Err("pattern too complex".into());
        }

        self.matchdepth -= 1;

        // Match.
        let current_block: u64;
        let mut ep_0 = 0;
        let mut res = loop {
            // Check first character.
            let first = match p.first().copied() {
                Some(v) => v,
                None => {
                    current_block = 6476622998065200121;
                    break Some(off);
                }
            };

            match first {
                b'(' => {
                    let r = if p.get(1).copied() == Some(b')') {
                        self.start_capture(off, &p[2..], -2)?
                    } else {
                        self.start_capture(off, &p[1..], -1)?
                    };

                    current_block = 6476622998065200121;
                    break r;
                }
                b')' => {
                    let r = self.end_capture(off, &p[1..])?;
                    current_block = 6476622998065200121;
                    break r;
                }
                b'$' => {
                    if !p.get(1).is_some() {
                        let r = if off == self.src.len() {
                            Some(off)
                        } else {
                            None
                        };
                        current_block = 6476622998065200121;
                        break r;
                    }
                }
                b'%' => match p.get(1) {
                    Some(b'b') => match self.matchbalance(off, &p[2..])? {
                        Some(v) => {
                            off = v;
                            p = &p[4..];
                            continue;
                        }
                        None => {
                            current_block = 6476622998065200121;
                            break None;
                        }
                    },
                    Some(b'f') => {
                        p = &p[2..];

                        if p.first().copied().is_none_or(|b| b != b'[') {
                            return Err("missing '[' after '%f' in pattern".into());
                        }

                        let ep = Self::classend(p)?;
                        let previous = if off == 0 { 0 } else { self.src[off - 1] };

                        if !Self::matchbracketclass(previous, p, ep - 1)
                            && Self::matchbracketclass(self.src[off], p, ep - 1)
                        {
                            p = &p[ep..];
                            continue;
                        } else {
                            current_block = 6476622998065200121;
                            break None;
                        }
                    }
                    Some(b'0') | Some(b'1') | Some(b'2') | Some(b'3') | Some(b'4') | Some(b'5')
                    | Some(b'6') | Some(b'7') | Some(b'8') | Some(b'9') => {
                        off = match self.match_capture(off, p[1])? {
                            Some(v) => v,
                            None => {
                                current_block = 6476622998065200121;
                                break None;
                            }
                        };

                        p = &p[2..];
                        continue;
                    }
                    _ => {}
                },
                _ => {}
            }

            ep_0 = Self::classend(p)?;

            if !self.singlematch(off, p, ep_0) {
                if p.get(ep_0).is_some_and(|b| matches!(b, b'*' | b'?' | b'-')) {
                    p = &p[(ep_0 + 1)..];
                } else {
                    current_block = 6476622998065200121;
                    break None;
                }
            } else {
                match p.get(ep_0) {
                    Some(b'?') => match self.match_0(off + 1, &p[(ep_0 + 1)..])? {
                        Some(v) => {
                            current_block = 6476622998065200121;
                            break Some(v);
                        }
                        None => p = &p[(ep_0 + 1)..],
                    },
                    Some(b'+') => {
                        current_block = 5161946086944071447;
                        break Some(off + 1);
                    }
                    Some(b'*') => {
                        current_block = 5161946086944071447;
                        break Some(off);
                    }
                    Some(b'-') => {
                        current_block = 6476622998065200121;
                        break self.min_expand(off, p, ep_0)?;
                    }
                    _ => {
                        off += 1;
                        p = &p[ep_0..];
                    }
                }
            }
        };

        match current_block {
            5161946086944071447 => {
                res = self.max_expand(off, p, ep_0)?;
            }
            _ => {}
        }

        self.matchdepth += 1;

        Ok(res)
    }

    fn start_capture(
        &mut self,
        off: usize,
        p: &[u8],
        what: isize,
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        if self.capture.len() >= 32 {
            return Err("too many captures".into());
        }

        self.capture.push(MatchCapture { off, len: what });

        let res = self.match_0(off, p)?;

        if res.is_none() {
            self.capture.pop();
        }

        Ok(res)
    }

    fn end_capture(
        &mut self,
        off: usize,
        p: &[u8],
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        let l = self.capture_to_close()?;

        self.capture[l].len = (off - self.capture[l].off) as isize;

        let res = self.match_0(off, p)?;

        if res.is_none() {
            self.capture[l].len = -1;
        }

        Ok(res)
    }

    fn capture_to_close(&self) -> Result<usize, Box<dyn core::error::Error>> {
        for (l, c) in self.capture.iter().enumerate().rev() {
            if c.len == -1 {
                return Ok(l);
            }
        }

        Err("invalid pattern capture".into())
    }

    fn matchbalance(
        &self,
        mut off: usize,
        p: &[u8],
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        let mut iter = p.iter().copied();
        let first = match iter.next() {
            Some(v) => v,
            None => return Err("malformed pattern (missing arguments to '%b')".into()),
        };

        if self.src[off] != first {
            return Ok(None);
        } else {
            let e = iter.next();
            let mut cont = 1;

            loop {
                off += 1;

                if !(off < self.src.len()) {
                    break;
                }

                if Some(self.src[off]) == e {
                    cont -= 1;

                    if cont == 0 {
                        return Ok(Some(off + 1));
                    }
                } else if self.src[off] == first {
                    cont += 1;
                }
            }
        }

        Ok(None)
    }

    fn classend(p: &[u8]) -> Result<usize, Box<dyn core::error::Error>> {
        let mut p = p.iter();

        match p.next().copied() {
            Some(b'%') => {
                if p.next().is_none() {
                    return Err("malformed pattern (ends with '%')".into());
                }

                Ok(2)
            }
            Some(b'[') => {
                let mut o = 1;

                if p.as_slice().first().copied() == Some(b'^') {
                    p.next();
                    o += 1;
                }

                loop {
                    let fresh2 = match p.next().copied() {
                        Some(v) => v,
                        None => return Err("malformed pattern (missing ']')".into()),
                    };

                    o += 1;

                    if fresh2 == b'%' && !p.as_slice().is_empty() {
                        p.next();
                        o += 1;
                    }

                    if !(p.as_slice().first().copied() != Some(b']')) {
                        break;
                    }
                }

                p.next();
                o += 1;

                Ok(o)
            }
            _ => Ok(1),
        }
    }

    fn singlematch(&self, off: usize, p: &[u8], ep: usize) -> bool {
        let c = match self.src.get(off).copied() {
            Some(v) => v,
            None => return false,
        };

        match p.first().copied() {
            Some(b'.') => true,
            Some(b'%') => Self::match_class(c, p[1]),
            Some(b'[') => Self::matchbracketclass(c, p, ep - 1),
            _ => p[0] == c,
        }
    }

    fn matchbracketclass(c: u8, p: &[u8], ec: usize) -> bool {
        let mut sig = true;
        let mut i = 0;

        if p[1] == b'^' {
            sig = false;
            i = 1;
        }

        loop {
            i += 1;

            if i >= ec {
                break;
            }

            if p[i] == b'%' {
                i += 1;

                if Self::match_class(c, p[i]) {
                    return sig;
                }
            } else if p[i + 1] == b'-' && (i + 2) < ec {
                i += 2;

                if p[i - 2] <= c && c <= p[i] {
                    return sig;
                }
            } else if p[i] == c {
                return sig;
            }
        }

        sig == false
    }

    fn match_class(c: u8, cl: u8) -> bool {
        let res = match cl.to_ascii_lowercase() {
            b'a' => c.is_ascii_alphabetic(),
            b'c' => c.is_ascii_control(),
            b'd' => c.is_ascii_digit(),
            b'g' => c.is_ascii_graphic(),
            b'l' => c.is_ascii_lowercase(),
            b'p' => c.is_ascii_punctuation(),
            b's' => c == 0x20 || c == 0x0c || c == 0x0a || c == 0x0d || c == 0x09 || c == 0x0b,
            b'u' => c.is_ascii_uppercase(),
            b'w' => c.is_ascii_alphanumeric(),
            b'x' => c.is_ascii_hexdigit(),
            _ => return cl == c,
        };

        if cl.is_ascii_lowercase() {
            res
        } else {
            res == false
        }
    }

    fn match_capture(
        &self,
        off: usize,
        l: u8,
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        let l = self.check_capture(l)?;
        let len = usize::try_from(self.capture[l].len).unwrap();
        let c = self.capture[l].off;
        let c = &self.src[c..];
        let c = &c[..len];
        let s = &self.src[off..];
        let s = match s.get(..len) {
            Some(v) => v,
            None => return Ok(None),
        };

        if s == c {
            Ok(Some(off + len))
        } else {
            Ok(None)
        }
    }

    fn check_capture(&self, l: u8) -> Result<usize, Box<dyn core::error::Error>> {
        let mut l = isize::from(l);

        l -= isize::from(b'1');

        if l < 0 || self.capture.get(l as usize).is_none_or(|c| c.len == -1) {
            return Err(format!("invalid capture index %{}", l + 1).into());
        }

        Ok(l as usize)
    }

    fn min_expand(
        &mut self,
        mut off: usize,
        p: &[u8],
        ep: usize,
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        loop {
            if let Some(v) = self.match_0(off, &p[(ep + 1)..])? {
                return Ok(Some(v));
            }

            if self.singlematch(off, p, ep) {
                off += 1;
            } else {
                return Ok(None);
            }
        }
    }

    fn max_expand(
        &mut self,
        off: usize,
        p: &[u8],
        ep: usize,
    ) -> Result<Option<usize>, Box<dyn core::error::Error>> {
        let mut i = 0;

        while self.singlematch(off + i, p, ep) {
            i += 1;
        }

        for i in (0..=i).rev() {
            if let Some(v) = self.match_0(off + i, &p[(ep + 1)..])? {
                return Ok(Some(v));
            }
        }

        Ok(None)
    }

    fn captures_to_values<'b, A>(
        &self,
        cx: &Context<'b, A, Args>,
        off: Option<usize>,
        e: Option<usize>,
    ) -> Result<Vec<Value<'b, A>>, Box<dyn core::error::Error>> {
        let nlevels = if self.capture.is_empty() && off.is_some() {
            1
        } else {
            self.capture.len()
        };

        // Create values.
        let mut values = Vec::with_capacity(nlevels);

        for i in 0..nlevels {
            let v = match self.get_onecapture(i, off, e)? {
                CaptureValue::Num(v) => Value::Int(v),
                CaptureValue::Str(v) => Value::Str(cx.create_bytes(v)),
            };

            values.push(v);
        }

        Ok(values)
    }

    fn push_captures<A>(
        self,
        cx: &Context<A, Args>,
        off: Option<usize>,
        e: Option<usize>,
    ) -> Result<(), Box<dyn core::error::Error>> {
        let nlevels = if self.capture.is_empty() && off.is_some() {
            1
        } else {
            self.capture.len()
        };

        if cx.reserve(nlevels).is_err() {
            return Err("too many captures".into());
        }

        for i in 0..nlevels {
            self.push_onecapture(&cx, i, off, e)?;
        }

        Ok(())
    }

    fn push_onecapture<A>(
        &self,
        cx: &Context<A, Args>,
        i: usize,
        off: Option<usize>,
        e: Option<usize>,
    ) -> Result<(), Box<dyn core::error::Error>> {
        match self.get_onecapture(i, off, e)? {
            CaptureValue::Num(v) => cx.push(v)?,
            CaptureValue::Str(v) => cx.push_bytes(v)?,
        }

        Ok(())
    }

    fn get_onecapture<'b>(
        &self,
        i: usize,
        off: Option<usize>,
        e: Option<usize>,
    ) -> Result<CaptureValue<'a>, Box<dyn core::error::Error>> {
        let cap = match self.capture.get(i) {
            Some(v) => v,
            None => {
                return match i {
                    0 => Ok(CaptureValue::Str(&self.src[off.unwrap()..e.unwrap()])),
                    _ => Err(format!("invalid capture index %{}", i.wrapping_add(1)).into()),
                };
            }
        };

        match cap.len {
            -1 => Err("unfinished capture".into()),
            -2 => Ok(CaptureValue::Num((cap.off + 1) as i64)),
            l => {
                let l = usize::try_from(l).unwrap();

                Ok(CaptureValue::Str(&self.src[cap.off..(cap.off + l)]))
            }
        }
    }

    fn add_value<A>(
        &self,
        cx: &Context<A, Args>,
        b: &mut Vec<u8>,
        off: usize,
        e: usize,
        tr: &Replacement<A>,
    ) -> Result<bool, Box<dyn core::error::Error>> {
        let r = match tr {
            Replacement::Fp(f) => self
                .captures_to_values(cx, Some(off), Some(e))
                .and_then(move |args| cx.call(*f, args))?,
            Replacement::Str(v) => {
                self.add_s(b, off, e, v.as_bytes())?;

                return Ok(true);
            }
            Replacement::Table(t) => match self.get_onecapture(0, Some(off), Some(e))? {
                CaptureValue::Num(v) => t.get(v),
                CaptureValue::Str(v) => t.get_bytes_key(v),
            },
            Replacement::LuaFn(f) => self
                .captures_to_values(cx, Some(off), Some(e))
                .and_then(move |args| cx.call(*f, args))?,
        };

        match r {
            Value::Nil | Value::False => {
                b.extend_from_slice(&self.src[off..e]);

                return Ok(false);
            }
            Value::Int(v) => b.extend_from_slice(v.to_string().as_bytes()),
            Value::Float(v) => b.extend_from_slice(v.to_string().as_bytes()),
            Value::Str(v) => b.extend_from_slice(v.as_bytes()),
            v => return Err(format!("invalid replacement value (a {})", cx.type_name(v)).into()),
        }

        Ok(true)
    }

    fn add_s(
        &self,
        b: &mut Vec<u8>,
        off: usize,
        e: usize,
        mut tr: &[u8],
    ) -> Result<(), Box<dyn core::error::Error>> {
        loop {
            let mut p = match memchr(b'%', tr) {
                Some(v) => v,
                None => break,
            };

            b.extend_from_slice(&tr[..p]);
            p += 1;

            match tr.get(p).copied() {
                Some(b'%') => b.push(b'%'),
                Some(v) if v.is_ascii_digit() => {
                    match self.get_onecapture(
                        v.checked_sub(b'1').map(usize::from).unwrap_or(usize::MAX),
                        Some(off),
                        Some(e),
                    )? {
                        CaptureValue::Num(v) => b.extend_from_slice(v.to_string().as_bytes()),
                        CaptureValue::Str(v) => b.extend_from_slice(v),
                    }
                }
                Some(_) => return Err("invalid use of '%' in replacement string".into()),
                None => b.extend_from_slice(&self.src[off..e]),
            }

            tr = &tr[(p + 1)..];
        }

        b.extend_from_slice(tr);

        Ok(())
    }
}

struct MatchCapture {
    off: usize,
    len: isize,
}

enum CaptureValue<'a> {
    Num(i64),
    Str(&'a [u8]),
}

enum Replacement<'a, A> {
    Fp(Fp<A>),
    Str(&'a Str<A>),
    Table(&'a Table<A>),
    LuaFn(&'a LuaFn<A>),
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Sign {
    Always,
    SpaceIfPositive,
    Negative,
}

struct Header {
    islittle: bool,
    maxalign: usize,
}

impl Header {
    fn new() -> Self {
        Self {
            islittle: cfg!(target_endian = "little"),
            maxalign: 1,
        }
    }

    fn getdetails<F: Iterator<Item = char>>(
        &mut self,
        totalsize: usize,
        first: char,
        fmt: &mut Peekable<F>,
        ntoalign: &mut usize,
    ) -> Result<Pack, Box<dyn core::error::Error>> {
        let opt = self.getoption(first, fmt)?;
        let mut align = match opt {
            Pack::Signed(v) => v,
            Pack::Unsigned(v) => v,
            Pack::Float => size_of::<c_float>(),
            Pack::Double => size_of::<c_double>(),
            Pack::Number => size_of::<f64>(),
            Pack::Char(v) => v,
            Pack::Str(v) => v.unwrap_or(0),
            Pack::Padding(v) => v,
            Pack::PadAlign => match fmt.next().map(|c| self.getoption(c, fmt)).transpose()? {
                Some(Pack::Signed(v))
                | Some(Pack::Unsigned(v))
                | Some(Pack::Str(Some(v)))
                | Some(Pack::Padding(v))
                    if v != 0 =>
                {
                    v
                }
                Some(Pack::Float) => size_of::<c_float>(),
                Some(Pack::Double) => size_of::<c_double>(),
                Some(Pack::Number) => size_of::<f64>(),
                _ => return Err("invalid next option for option 'X'".into()),
            },
            Pack::Nop => 0,
        };

        if align <= 1 || matches!(opt, Pack::Char(_)) {
            *ntoalign = 0;
        } else {
            if align > self.maxalign {
                align = self.maxalign;
            }

            if align & align - 1 != 0 {
                return Err("format asks for alignment not power of 2".into());
            }

            *ntoalign = align - (totalsize & (align - 1)) & align - 1;
        }

        Ok(opt)
    }

    fn getoption<F: Iterator<Item = char>>(
        &mut self,
        opt: char,
        fmt: &mut Peekable<F>,
    ) -> Result<Pack, Box<dyn core::error::Error>> {
        match opt {
            'b' => return Ok(Pack::Signed(1)),
            'B' => return Ok(Pack::Unsigned(1)),
            'h' => return Ok(Pack::Signed(size_of::<c_short>())),
            'H' => return Ok(Pack::Unsigned(size_of::<c_short>())),
            'l' => return Ok(Pack::Signed(size_of::<c_long>())),
            'L' => return Ok(Pack::Unsigned(size_of::<c_long>())),
            'j' => return Ok(Pack::Signed(8)),
            'J' => return Ok(Pack::Unsigned(8)),
            'T' => return Ok(Pack::Unsigned(size_of::<usize>())),
            'f' => return Ok(Pack::Float),
            'n' => return Ok(Pack::Number),
            'd' => return Ok(Pack::Double),
            'i' => return Self::getnumlimit(fmt, size_of::<c_int>()).map(Pack::Signed),
            'I' => return Self::getnumlimit(fmt, size_of::<c_int>()).map(Pack::Unsigned),
            's' => return Self::getnumlimit(fmt, size_of::<usize>()).map(|v| Pack::Str(Some(v))),
            'c' => match Self::getnum(fmt) {
                Some(v) => return Ok(Pack::Char(v)),
                None => return Err("missing size for format option 'c'".into()),
            },
            'z' => return Ok(Pack::Str(None)),
            'x' => return Ok(Pack::Padding(1)),
            'X' => return Ok(Pack::PadAlign),
            ' ' => (),
            '<' => self.islittle = true,
            '>' => self.islittle = false,
            '=' => self.islittle = cfg!(target_endian = "little"),
            '!' => self.maxalign = Self::getnumlimit(fmt, size_of::<usize>())?,
            _ => return Err(format!("invalid format option '{opt}'",).into()),
        }

        Ok(Pack::Nop)
    }

    fn getnumlimit<F: Iterator<Item = char>>(
        fmt: &mut Peekable<F>,
        df: usize,
    ) -> Result<usize, Box<dyn core::error::Error>> {
        let sz = Self::getnum(fmt).unwrap_or(df);

        if sz > 16 || sz <= 0 {
            return Err(format!("integral size ({sz}) out of limits [1,16]").into());
        }

        Ok(sz)
    }

    fn getnum<F: Iterator<Item = char>>(fmt: &mut Peekable<F>) -> Option<usize> {
        let mut b = fmt.next_if(|b| b.is_ascii_digit())? as u8;
        let mut a = 0;

        loop {
            a = a * 10 + usize::from(b - b'0');

            b = match fmt.next_if(move |b| b.is_ascii_digit() && a <= (2147483647 - 9) / 10) {
                Some(v) => v as u8,
                None => break,
            };
        }

        Some(a)
    }
}

#[derive(Clone, Copy)]
enum Pack {
    Signed(usize),
    Unsigned(usize),
    Float,
    Double,
    Number,
    Char(usize),
    Str(Option<usize>),
    Padding(usize),
    PadAlign,
    Nop,
}