aboutsummaryrefslogtreecommitdiff
path: root/src/lua/lua_text.c
blob: d60ecd476e89f4c0ca293631902f85576ba15e5a (plain) (blame)
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
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
/*
 * Copyright 2025 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "lua_common.h"
#include "libcryptobox/cryptobox.h"
#include "rspamd_simdutf.h"
#include "unix-std.h"
#include <zlib.h> /* for crc32() */

/***
 * @module rspamd_text
 * This module provides access to opaque text structures used widely to prevent
 * copying between Lua and C for various concerns: performance, security etc...
 *
 * You can convert rspamd_text into string but it will copy data.
 */

/***
 * @function rspamd_text.fromstring(str)
 * Creates rspamd_text from Lua string (copied to the text)
 * @param {string} str string to use
 * @return {rspamd_text} resulting text
 */
LUA_FUNCTION_DEF(text, fromstring);

/***
 * @function rspamd_text.null()
 * Creates rspamd_text with NULL pointer for testing purposes
 * @param {string} str string to use
 * @return {rspamd_text} resulting text
 */
LUA_FUNCTION_DEF(text, null);
/***
 * @function rspamd_text.randombytes(nbytes)
 * Creates rspamd_text with random bytes inside (raw bytes)
 * @param {number} nbytes number of random bytes generated
 * @return {rspamd_text} random bytes text
 */
LUA_FUNCTION_DEF(text, randombytes);

/***
 * @function rspamd_text.fromtable(tbl[, delim])
 * Same as `table.concat` but generates rspamd_text instead of the Lua string
 * @param {table} tbl table to use
 * @param {string} delim optional delimiter
 * @return {rspamd_text} resulting text
 */
LUA_FUNCTION_DEF(text, fromtable);
/***
 * @method rspamd_text:byte(pos[, pos2])
 * Returns a byte at the position `pos` or bytes from `pos` to `pos2` if specified
 * @param {integer} pos index
 * @param {integer} pos2 index
 * @return {integer} byte at the position `pos` or varargs of bytes
 */
LUA_FUNCTION_DEF(text, byte);
/***
 * @method rspamd_text:len()
 * Returns length of a string
 * @return {number} length of string in **bytes**
 */
LUA_FUNCTION_DEF(text, len);
/***
 * @method rspamd_text:len_utf8()
 * Returns length of a string
 * @return {number} length of string in **bytes**
 */
LUA_FUNCTION_DEF(text, len_utf8);
/***
 * @method rspamd_text:str()
 * Converts text to string by copying its content
 * @return {string} copy of text as Lua string
 */
LUA_FUNCTION_DEF(text, str);
/***
 * @method rspamd_text:ptr()
 * Converts text to lightuserdata
 * @return {lightuserdata} pointer value of rspamd_text
 */
LUA_FUNCTION_DEF(text, ptr);
/***
 * @method rspamd_text:save_in_file(fname[, mode])
 * Saves text in file
 * @return {boolean} true if save has been completed
 */
LUA_FUNCTION_DEF(text, save_in_file);
/***
 * @method rspamd_text:span(start[, len])
 * Returns a span for lua_text starting at pos [start] (1 indexed) and with
 * length `len` (or to the end of the text)
 * @param {integer} start start index
 * @param {integer} len length of span
 * @return {rspamd_text} new rspamd_text with span (must be careful when using with owned texts...)
 */
LUA_FUNCTION_DEF(text, span);
/***
 * @method rspamd_text:sub(start[, len])
 * Returns a substring for lua_text similar to string.sub from Lua
 * @return {rspamd_text} new rspamd_text with span (must be careful when using with owned texts...)
 */
LUA_FUNCTION_DEF(text, sub);
/***
 * @method rspamd_text:sub_utf8(start[, len])
 * Returns a substring for lua_text similar to string.sub from Lua using UTF8 points
 * @return {rspamd_text} new rspamd_text with span (must be careful when using with owned texts...)
 */
LUA_FUNCTION_DEF(text, sub_utf8);
/***
 * @method rspamd_text:lines([stringify])
 * Returns an iter over all lines as rspamd_text objects or as strings if `stringify` is true
 * @param {boolean} stringify stringify lines
 * @return {iterator} iterator triplet
 */
LUA_FUNCTION_DEF(text, lines);
/***
 * @method rspamd_text:split(regexp, [stringify])
 * Returns an iter over all encounters of the specific regexp as rspamd_text objects or as strings if `stringify` is true
 * @param {rspamd_regexp} regexp regexp (pcre syntax) used for splitting
 * @param {boolean} stringify stringify lines
 * @return {iterator} iterator triplet
 */
LUA_FUNCTION_DEF(text, split);
/***
 * @method rspamd_text:at(pos)
 * Returns a byte at the position `pos`
 * @param {integer} pos index
 * @return {integer} byte at the position `pos` or nil if pos out of bound
 */
LUA_FUNCTION_DEF(text, at);
/***
 * @method rspamd_text:memchr(chr, [reverse])
 * Returns the first or the last position of the character `chr` in the text or
 * -1 in case if a character has not been found. Indexes start from `1`
 * @param {string/number} chr character or a character code to find
 * @param {boolean} reverse last character if `true`
 * @return {integer} position of the character or `-1`
 */
LUA_FUNCTION_DEF(text, memchr);
/***
 * @method rspamd_text:bytes()
 * Converts text to an array of bytes
 * @return {table|integer} bytes in the array (as unsigned char)
 */
LUA_FUNCTION_DEF(text, bytes);
/***
 * @method rspamd_text:lower([is_utf, [inplace]])
 * Return a new text with lowercased characters, if is_utf is true then Rspamd applies utf8 lowercase
 * @param {boolean} is_utf apply utf8 lowercase
 * @param {boolean} inplace lowercase the original text
 * @return {rspamd_text} new rspamd_text (or the original text if inplace) with lowercased letters
 */
LUA_FUNCTION_DEF(text, lower);
LUA_FUNCTION_DEF(text, take_ownership);
/***
 * @method rspamd_text:exclude_chars(set_to_exclude, [always_copy])
 * Returns a text (if owned, then the original text is modified, if not, then it is copied and owned)
 * where all chars from `set_to_exclude` are removed
 * Patterns supported:
 *
 * - %s - all space characters
 * - %n - all newline characters
 * - %c - all control characters (it includes 8bit characters and spaces)
 * - %8 - all 8 bit characters
 * - %% - just a percent character
 *
 * @param {string} set_to_exclude characters to exclude
 * @param {boolean} always_copy always copy the source text
 * @return {rspamd_text} modified or copied text
 */
LUA_FUNCTION_DEF(text, exclude_chars);
/***
 * @method rspamd_text:memcspn(reject_chars)
 * Returns the length of the initial segment of text that consists entirely
 * of characters NOT in reject_chars (like C's strcspn, but for binary data)
 * @param {string} reject_chars set of characters to reject
 * @return {integer} length of the initial segment
 */
LUA_FUNCTION_DEF(text, memcspn);
/***
 * @method rspamd_text:oneline([always_copy])
 * Returns a text (if owned, then the original text is modified, if not, then it is copied and owned)
 * where the following transformations are made:
 * - All spaces sequences are replaced with a single space
 * - All newlines sequences are replaced with a single space
 * - Trailing and leading spaces are removed
 * - Control characters are excluded
 * - UTF8 sequences are normalised
 *
 * @param {boolean} always_copy always copy the source text
 * @return {rspamd_text} modified or copied text
 */
LUA_FUNCTION_DEF(text, oneline);
/***
 * @method rspamd_text:normalize_newlines([mode, [pool]])
 * Normalizes line endings in text to the specified format.
 * - If mode is "lf" or "unix": converts CRLF to LF
 * - If mode is "crlf" or "windows" (default): converts bare LF to CRLF
 * - If mode is "smtp": converts every bare CR and bare LF to CRLF, as SMTP
 *   allows CR and LF only as a CRLF pair (RFC 5321 2.3.8)
 *
 * If the text is owned, it may be modified in-place.
 * If a mempool is provided, new memory is allocated from it.
 * Otherwise, g_malloc is used and OWN flag is set.
 *
 * @param {string} mode target newline mode: "lf", "crlf" or "smtp" (default: "crlf")
 * @param {mempool} pool optional mempool for allocation
 * @return {rspamd_text} normalized text (may be same as input if no changes)
 */
LUA_FUNCTION_DEF(text, normalize_newlines);
/***
 * @method rspamd_text:base32([b32type])
 * Returns a text encoded in base32 (new rspamd_text is allocated)
 *
 * @param {string} b32type base32 type (default, bleach, rfc)
 * @return {rspamd_text} new text encoded in base32
 */
LUA_FUNCTION_DEF(text, base32);
/***
 * @method rspamd_text:base64([line_length, [nline, [fold]]])
 * Returns a text encoded in base64 (new rspamd_text is allocated)
 *
 * @param {number} line_length return text split with newlines up to this attribute
 * @param {string} nline newline type: `cr`, `lf`, `crlf`
 * @param {boolean} fold use folding when splitting into lines (false by default)
 * @return {rspamd_text} new text encoded in base64
 */
LUA_FUNCTION_DEF(text, base64);
/***
 * @method rspamd_text:hex()
 * Returns a text encoded in hex (new rspamd_text is allocated)
 *
 * @return {rspamd_text} new text encoded in hex
 */
LUA_FUNCTION_DEF(text, hex);
/***
 * @method rspamd_text:crc32([start[, len]])
 * Returns the CRC-32 checksum of the byte range starting at `start`
 * (1-indexed, default 1) and spanning `len` bytes (default: to the end of the
 * text). The range is read in place (no copy). This is the standard CRC-32
 * (zlib crc32 / YARA hash.crc32, polynomial 0xEDB88320) and the result is a Lua
 * integer suitable for numeric comparison (e.g. `t:crc32() == 0xCBF43926`).
 * @param {integer} start 1-based start index
 * @param {integer} len number of bytes
 * @return {integer} crc32 value as an unsigned 32-bit integer
 */
LUA_FUNCTION_DEF(text, crc32);
/***
 * @method rspamd_text:find(pattern [, init])
 * Looks for the first match of pattern in the string s.
 * If it finds a match, then find returns the indices of s where this occurrence
 * starts and ends; otherwise, it returns nil. A third,
 * optional numerical argument init specifies where to start the search;
 * its default value is 1 and can be negative.
 * This method currently supports merely a plain search, no patterns.
 *
 * @param {string} pattern pattern to find
 * @param {number} init specifies where to start the search (1 default)
 * @return {number,number/nil} If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil
 */
LUA_FUNCTION_DEF(text, find);
LUA_FUNCTION_DEF(text, gc);
LUA_FUNCTION_DEF(text, eq);
LUA_FUNCTION_DEF(text, lt);
LUA_FUNCTION_DEF(text, concat);
LUA_FUNCTION_DEF(text, strtoul);

static const struct luaL_reg textlib_f[] = {
	LUA_INTERFACE_DEF(text, fromstring),
	{"from_string", lua_text_fromstring},
	LUA_INTERFACE_DEF(text, fromtable),
	{"from_table", lua_text_fromtable},
	LUA_INTERFACE_DEF(text, null),
	LUA_INTERFACE_DEF(text, randombytes),
	{NULL, NULL}};

static const struct luaL_reg textlib_m[] = {
	LUA_INTERFACE_DEF(text, len),
	LUA_INTERFACE_DEF(text, len_utf8),
	LUA_INTERFACE_DEF(text, str),
	LUA_INTERFACE_DEF(text, ptr),
	LUA_INTERFACE_DEF(text, take_ownership),
	LUA_INTERFACE_DEF(text, save_in_file),
	LUA_INTERFACE_DEF(text, span),
	LUA_INTERFACE_DEF(text, sub),
	LUA_INTERFACE_DEF(text, sub_utf8),
	LUA_INTERFACE_DEF(text, lines),
	LUA_INTERFACE_DEF(text, split),
	LUA_INTERFACE_DEF(text, at),
	LUA_INTERFACE_DEF(text, memchr),
	LUA_INTERFACE_DEF(text, byte),
	LUA_INTERFACE_DEF(text, bytes),
	LUA_INTERFACE_DEF(text, lower),
	LUA_INTERFACE_DEF(text, exclude_chars),
	LUA_INTERFACE_DEF(text, memcspn),
	LUA_INTERFACE_DEF(text, oneline),
	LUA_INTERFACE_DEF(text, normalize_newlines),
	LUA_INTERFACE_DEF(text, base32),
	LUA_INTERFACE_DEF(text, base64),
	LUA_INTERFACE_DEF(text, hex),
	LUA_INTERFACE_DEF(text, crc32),
	LUA_INTERFACE_DEF(text, find),
	LUA_INTERFACE_DEF(text, strtoul),
	{"write", lua_text_save_in_file},
	{"__len", lua_text_len},
	{"__tostring", lua_text_str},
	{"__gc", lua_text_gc},
	{"__eq", lua_text_eq},
	{"__lt", lua_text_lt},
	{"__concat", lua_text_concat},
	{NULL, NULL}};

struct rspamd_lua_text *
lua_check_text(lua_State *L, int pos)
{
	void *ud = rspamd_lua_check_udata(L, pos, rspamd_text_classname);
	luaL_argcheck(L, ud != NULL, pos, "'text' expected");
	return ud ? (struct rspamd_lua_text *) ud : NULL;
}

struct rspamd_lua_text *
lua_check_text_or_string(lua_State *L, int pos)
{
	int pos_type = lua_type(L, pos);

	if (pos_type == LUA_TUSERDATA) {
		void *ud = rspamd_lua_check_udata(L, pos, rspamd_text_classname);
		luaL_argcheck(L, ud != NULL, pos, "'text' expected");
		return ud ? (struct rspamd_lua_text *) ud : NULL;
	}
	else if (pos_type == LUA_TSTRING) {
		/*
		 * Fake static lua_text, we allow to use this function multiple times
		 * by having a small array of static structures.
		 */
		static unsigned cur_txt_idx = 0;
		static struct rspamd_lua_text fake_text[4];
		gsize len;
		int sel_idx;

		sel_idx = cur_txt_idx++ % G_N_ELEMENTS(fake_text);
		fake_text[sel_idx].start = lua_tolstring(L, pos, &len);

		if (len >= G_MAXUINT) {
			return NULL;
		}

		fake_text[sel_idx].len = len;
		fake_text[sel_idx].flags = RSPAMD_TEXT_FLAG_FAKE;

		return &fake_text[sel_idx];
	}

	return NULL;
}

struct rspamd_lua_text *
lua_new_text(lua_State *L, const char *start, gsize len, gboolean allocate_memory)
{
	struct rspamd_lua_text *t;

	t = lua_newuserdata(L, sizeof(*t));
	t->flags = 0;

	if (allocate_memory) {
		char *storage;

		if (len > 0) {
			storage = g_malloc(len);

			if (start != NULL) {
				memcpy(storage, start, len);
			}

			t->start = storage;
			t->flags = RSPAMD_TEXT_FLAG_OWN;
		}
		else {
			t->start = "";
		}
	}
	else {
		t->start = start;
	}

	t->len = len;
	rspamd_lua_setclass(L, rspamd_text_classname, -1);

	return t;
}

struct rspamd_lua_text *
lua_new_text_task(lua_State *L, struct rspamd_task *task,
				  const char *start, gsize len, gboolean own)
{
	struct rspamd_lua_text *t;

	t = lua_newuserdata(L, sizeof(*t));
	t->flags = 0;

	if (own) {
		char *storage;

		if (len > 0) {
			storage = rspamd_mempool_alloc(task->task_pool, len);

			if (start != NULL) {
				memcpy(storage, start, len);
			}

			t->start = storage;
		}
		else {
			t->start = "";
		}
	}
	else {
		t->start = start;
	}

	t->len = len;
	rspamd_lua_setclass(L, rspamd_text_classname, -1);

	return t;
}

bool lua_is_text_binary(struct rspamd_lua_text *t)
{
	if (t == NULL || t->len == 0) {
		return false;
	}

	if (rspamd_str_has_8bit(t->start, t->len)) {
		if (rspamd_fast_utf8_validate(t->start, t->len) == 0) {
			return false;
		}
		return true;
	}

	return false;
}

struct rspamd_lua_text *
rspamd_lua_text_normalize_newlines(struct rspamd_lua_text *t,
								   rspamd_mempool_t *pool,
								   enum rspamd_text_newline_mode mode)
{
	if (t == NULL || t->len == 0) {
		return t;
	}

	const char *p, *end;
	size_t count = 0;

	p = t->start;
	end = t->start + t->len;

	if (mode == RSPAMD_TEXT_NEWLINES_CRLF) {
		/* LF -> CRLF: count bare LFs (not preceded by CR) */
		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\n", 1);
			p += span;

			if (p < end) {
				/* Found LF, check if bare */
				if (p == t->start || *(p - 1) != '\r') {
					count++;
				}
				p++;
			}
		}

		if (count == 0) {
			return t; /* Already normalized */
		}

		/* Need to insert 'count' CR characters */
		size_t new_len = t->len + count;
		char *new_start;

		if (pool) {
			new_start = rspamd_mempool_alloc(pool, new_len);
		}
		else {
			new_start = g_malloc(new_len);
		}

		/* Copy with CR insertion */
		char *out = new_start;
		p = t->start;

		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\n", 1);
			memcpy(out, p, span);
			out += span;
			p += span;

			if (p < end) {
				if (p == t->start || *(p - 1) != '\r') {
					*out++ = '\r'; /* Insert CR */
				}
				*out++ = *p++; /* Copy LF */
			}
		}

		/* Free old memory if owned */
		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			g_free((void *) t->start);
		}

		t->start = new_start;
		t->len = new_len;
		t->flags = pool ? 0 : RSPAMD_TEXT_FLAG_OWN;
	}
	else if (mode == RSPAMD_TEXT_NEWLINES_SMTP) {
		/*
		 * SMTP allows CR and LF only as CRLF: a bare CR is as much a line end as a
		 * bare LF, and leaving it would let "<CR>.<CR><LF>" pass dot-stuffing
		 */
		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\r\n", 2);
			p += span;

			if (p < end) {
				if (*p == '\r' && p + 1 < end && *(p + 1) == '\n') {
					p += 2;
				}
				else {
					count++;
					p++;
				}
			}
		}

		if (count == 0) {
			return t; /* Already normalized */
		}

		/* Every bare CR or LF grows into a CRLF pair */
		size_t new_len = t->len + count;
		char *new_start;

		if (pool) {
			new_start = rspamd_mempool_alloc(pool, new_len);
		}
		else {
			new_start = g_malloc(new_len);
		}

		char *out = new_start;
		p = t->start;

		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\r\n", 2);
			memcpy(out, p, span);
			out += span;
			p += span;

			if (p < end) {
				if (*p == '\r' && p + 1 < end && *(p + 1) == '\n') {
					*out++ = *p++;
					*out++ = *p++;
				}
				else {
					*out++ = '\r';
					*out++ = '\n';
					p++;
				}
			}
		}

		/* Free old memory if owned */
		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			g_free((void *) t->start);
		}

		t->start = new_start;
		t->len = new_len;
		t->flags = pool ? 0 : RSPAMD_TEXT_FLAG_OWN;
	}
	else {
		/* CRLF -> LF: count CR followed by LF */
		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\r", 1);
			p += span;

			if (p < end) {
				/* Found CR, check if followed by LF */
				if (p + 1 < end && *(p + 1) == '\n') {
					count++;
				}
				p++;
			}
		}

		if (count == 0) {
			return t; /* Already normalized */
		}

		/* Need to remove 'count' CR characters */
		size_t new_len = t->len - count;
		char *new_start;

		if (pool) {
			new_start = rspamd_mempool_alloc(pool, new_len);
		}
		else {
			new_start = g_malloc(new_len);
		}

		/* Copy, skipping CR before LF */
		char *out = new_start;
		p = t->start;

		while (p < end) {
			size_t span = rspamd_memcspn(p, end - p, "\r", 1);
			memcpy(out, p, span);
			out += span;
			p += span;

			if (p < end) {
				/* Check if CR is followed by LF */
				if (p + 1 < end && *(p + 1) == '\n') {
					/* Skip the CR, will copy LF on next iteration */
					p++;
				}
				else {
					*out++ = *p++; /* Copy CR (not followed by LF) */
				}
			}
		}

		/* Free old memory if owned */
		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			g_free((void *) t->start);
		}

		t->start = new_start;
		t->len = new_len;
		t->flags = pool ? 0 : RSPAMD_TEXT_FLAG_OWN;
	}

	return t;
}


static int
lua_text_fromstring(lua_State *L)
{
	LUA_TRACE_POINT;
	const char *str;
	gsize l = 0;
	gboolean transparent = FALSE;

	str = luaL_checklstring(L, 1, &l);

	if (str) {
		if (lua_isboolean(L, 2)) {
			transparent = lua_toboolean(L, 2);
		}

		lua_new_text(L, str, l, !transparent);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}


	return 1;
}

static int
lua_text_null(lua_State *L)
{
	LUA_TRACE_POINT;

	lua_new_text(L, NULL, 0, false);

	return 1;
}

static int
lua_text_randombytes(lua_State *L)
{
	LUA_TRACE_POINT;
	unsigned int nbytes = luaL_checkinteger(L, 1);
	struct rspamd_lua_text *out;

	out = lua_new_text(L, NULL, nbytes, TRUE);
	randombytes_buf((char *) out->start, nbytes);
	out->len = nbytes;

	return 1;
}

#define MAX_REC 10

static void
lua_text_tbl_length(lua_State *L, gsize dlen, gsize *dest, unsigned int rec)
{
	gsize tblen, stlen;
	struct rspamd_lua_text *elt;

	if (rec > MAX_REC) {
		luaL_error(L, "lua_text_tbl_length: recursion limit exceeded");

		return;
	}

	tblen = rspamd_lua_table_size(L, -1);

	for (gsize i = 0; i < tblen; i++) {
		lua_rawgeti(L, -1, i + 1);

		if (lua_type(L, -1) == LUA_TSTRING) {
#if LUA_VERSION_NUM >= 502
			stlen = lua_rawlen(L, -1);
#else
			stlen = lua_objlen(L, -1);
#endif
			(*dest) += stlen;
		}
		else if (lua_type(L, -1) == LUA_TUSERDATA) {
			elt = (struct rspamd_lua_text *) lua_touserdata(L, -1);

			if (elt) {
				(*dest) += elt->len;
			}
		}
		else if (lua_type(L, -1) == LUA_TTABLE) {
			lua_text_tbl_length(L, dlen, dest, rec + 1);
		}

		if (i != tblen - 1) {
			(*dest) += dlen;
		}

		lua_pop(L, 1);
	}
}

static void
lua_text_tbl_append(lua_State *L,
					const char *delim,
					gsize dlen,
					char **dest,
					unsigned int rec)
{
	const char *st;
	gsize tblen, stlen;
	struct rspamd_lua_text *elt;

	if (rec > MAX_REC) {
		luaL_error(L, "lua_text_tbl_length: recursion limit exceeded");

		return;
	}

	tblen = rspamd_lua_table_size(L, -1);

	for (unsigned int i = 0; i < tblen; i++) {
		lua_rawgeti(L, -1, i + 1);

		if (lua_type(L, -1) == LUA_TSTRING) {
			st = lua_tolstring(L, -1, &stlen);
			memcpy((*dest), st, stlen);
			(*dest) += stlen;
		}
		else if (lua_type(L, -1) == LUA_TUSERDATA) {
			elt = (struct rspamd_lua_text *) lua_touserdata(L, -1);

			if (elt) {
				memcpy((*dest), elt->start, elt->len);
				(*dest) += elt->len;
			}
		}
		else if (lua_type(L, -1) == LUA_TTABLE) {
			lua_text_tbl_append(L, delim, dlen, dest, rec + 1);
		}

		if (dlen && i != tblen - 1) {
			memcpy((*dest), delim, dlen);
			(*dest) += dlen;
		}

		lua_pop(L, 1);
	}
}

static int
lua_text_fromtable(lua_State *L)
{
	LUA_TRACE_POINT;
	const char *delim = "";
	struct rspamd_lua_text *t;
	gsize textlen = 0, dlen, oldtop = lua_gettop(L);
	char *dest;

	if (!lua_istable(L, 1)) {
		return luaL_error(L, "invalid arguments");
	}

	if (lua_type(L, 2) == LUA_TSTRING) {
		delim = lua_tolstring(L, 2, &dlen);
	}
	else {
		dlen = 0;
	}

	/* Calculate length needed */
	lua_pushvalue(L, 1);
	lua_text_tbl_length(L, dlen, &textlen, 0);
	lua_pop(L, 1);

	/* Allocate new text */
	t = lua_newuserdata(L, sizeof(*t));
	dest = g_malloc(textlen);
	t->start = dest;
	t->len = textlen;
	t->flags = RSPAMD_TEXT_FLAG_OWN;
	rspamd_lua_setclass(L, rspamd_text_classname, -1);

	lua_pushvalue(L, 1);
	lua_text_tbl_append(L, delim, dlen, &dest, 0);
	lua_pop(L, 1); /* Table arg */

	int newtop = lua_gettop(L);
	g_assert(newtop == oldtop + 1);

	return 1;
}

static int
lua_text_len(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	gsize l = 0;

	if (t != NULL) {
		l = t->len;
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	lua_pushinteger(L, l);

	return 1;
}

static int
lua_text_str(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t != NULL) {
		lua_pushlstring(L, t->start, t->len);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_ptr(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t != NULL) {
		lua_pushlightuserdata(L, (gpointer) t->start);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_take_ownership(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	char *dest;

	if (t != NULL) {
		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			/* We already own it */
			lua_pushboolean(L, true);
		}
		else {
			dest = g_malloc(t->len);
			memcpy(dest, t->start, t->len);
			t->start = dest;
			t->flags |= RSPAMD_TEXT_FLAG_OWN;
			lua_pushboolean(L, true);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_span(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	int64_t start = lua_tointeger(L, 2), len = -1;

	if (t && start >= 1 && start <= t->len) {
		if (lua_isnumber(L, 3)) {
			len = lua_tonumber(L, 3);
		}

		if (len == -1) {
			len = t->len - (start - 1);
		}

		if (len < 0 || (len > (t->len - (start - 1)))) {
			return luaL_error(L, "invalid length");
		}

		lua_new_text(L, t->start + (start - 1), len, FALSE);
	}
	else {
		if (!t) {
			return luaL_error(L, "invalid arguments, text required");
		}
		else {
			return luaL_error(L, "invalid arguments: start offset %d "
								 "is larger than text len %d",
							  (int) start, (int) t->len);
		}
	}

	return 1;
}

/* Helpers to behave exactly as Lua does */
static inline gsize
relative_pos_start(int pos, gsize len)
{
	if (pos > 0) {
		return pos;
	}
	else if (pos == 0) {
		return 1;
	}
	else if (pos < -((int) len)) {
		return 1;
	}

	/* Negative pos inside str */
	return len + ((gsize) pos) + 1;
}

static inline gsize
relative_pos_end(int pos, gsize len)
{
	if (pos > (int) len) {
		return len;
	}
	else if (pos >= 0) {
		return (size_t) pos;
	}
	else if (pos < -((int) len)) {
		return 0;
	}

	return len + ((gsize) pos) + 1;
}

static int
lua_text_sub(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t) {
		size_t start = relative_pos_start(luaL_checkinteger(L, 2),
										  t->len);
		size_t end = relative_pos_end(luaL_optinteger(L, 3, -1),
									  t->len);


		if (start <= end) {
			lua_new_text(L, t->start + (start - 1),
						 (end - start) + 1, FALSE);
		}
		else {
			lua_new_text(L, "", 0, TRUE);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int64_t
rspamd_lua_text_push_line(lua_State *L,
						  struct rspamd_lua_text *t,
						  int64_t start_offset,
						  const char *sep_pos,
						  gboolean stringify)
{
	const char *start;
	gsize len;
	int64_t ret;

	start = t->start + start_offset;
	len = sep_pos ? (sep_pos - start) : (t->len - start_offset);
	ret = start_offset + len;

	/* Trim line */
	while (len > 0) {
		if (start[len - 1] == '\r' || start[len - 1] == '\n') {
			len--;
		}
		else {
			break;
		}
	}

	if (stringify) {
		lua_pushlstring(L, start, len);
	}
	else {
		struct rspamd_lua_text *ntext;

		ntext = lua_newuserdata(L, sizeof(*ntext));
		rspamd_lua_setclass(L, rspamd_text_classname, -1);
		ntext->start = start;
		ntext->len = len;
		ntext->flags = 0; /* Not own as it must be owned by a top object */
	}

	return ret;
}

static int
rspamd_lua_text_readline(lua_State *L)
{
	struct rspamd_lua_text *t = lua_touserdata(L, lua_upvalueindex(1));
	gboolean stringify = lua_toboolean(L, lua_upvalueindex(2));
	int64_t pos = lua_tointeger(L, lua_upvalueindex(3));

	if (pos < 0) {
		return luaL_error(L, "invalid pos: %d", (int) pos);
	}

	if (pos >= t->len) {
		/* We are done */
		return 0;
	}

	const char *sep_pos;

	/* We look just for `\n` ignoring `\r` as it is very rare nowadays */
	sep_pos = memchr(t->start + pos, '\n', t->len - pos);

	if (sep_pos == NULL) {
		/* Either last `\n` or `\r` separated text */
		sep_pos = memchr(t->start + pos, '\r', t->len - pos);
	}

	pos = rspamd_lua_text_push_line(L, t, pos, sep_pos, stringify);

	/* Skip separators */
	while (pos < t->len) {
		if (t->start[pos] == '\n' || t->start[pos] == '\r') {
			pos++;
		}
		else {
			break;
		}
	}

	/* Update pos */
	lua_pushinteger(L, pos);
	lua_replace(L, lua_upvalueindex(3));

	return 1;
}

static int
lua_text_lines(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	gboolean stringify = FALSE;

	if (t) {
		if (lua_isboolean(L, 2)) {
			stringify = lua_toboolean(L, 2);
		}

		lua_pushvalue(L, 1);
		lua_pushboolean(L, stringify);
		lua_pushinteger(L, 0); /* Current pos */
		lua_pushcclosure(L, rspamd_lua_text_readline, 3);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
rspamd_lua_text_regexp_split(lua_State *L)
{
	struct rspamd_lua_text *t = lua_touserdata(L, lua_upvalueindex(1)),
						   *new_t;
	struct rspamd_lua_regexp *re = *(struct rspamd_lua_regexp **)
									   lua_touserdata(L, lua_upvalueindex(2));
	gboolean stringify = lua_toboolean(L, lua_upvalueindex(3));
	int64_t pos = lua_tointeger(L, lua_upvalueindex(4));
	gboolean matched;

	if (pos < 0) {
		return luaL_error(L, "invalid pos: %d", (int) pos);
	}

	if (pos >= t->len) {
		/* We are done */
		return 0;
	}

	const char *start, *end, *old_start;

	end = t->start + pos;

	for (;;) {
		old_start = end;

		matched = rspamd_regexp_search(re->re, t->start, t->len, &start, &end, FALSE,
									   NULL);

		if (matched) {
			if (start - old_start > 0) {
				if (stringify) {
					lua_pushlstring(L, old_start, start - old_start);
				}
				else {
					new_t = lua_newuserdata(L, sizeof(*t));
					rspamd_lua_setclass(L, rspamd_text_classname, -1);
					new_t->start = old_start;
					new_t->len = start - old_start;
					new_t->flags = 0;
				}

				break;
			}
			else {
				if (start == end) {
					matched = FALSE;
					break;
				}
				/*
				 * All match separators (e.g. starting separator,
				 * we need to skip it). Continue iterations.
				 */
			}
		}
		else {
			/* No match, stop */
			break;
		}
	}

	if (!matched && (t->len > 0 && (end == NULL || end < t->start + t->len))) {
		/* No more matches, but we might need to push the last element */
		if (end == NULL) {
			end = t->start;
		}
		/* No separators, need to push the whole remaining part */
		if (stringify) {
			lua_pushlstring(L, end, (t->start + t->len) - end);
		}
		else {
			new_t = lua_newuserdata(L, sizeof(*t));
			rspamd_lua_setclass(L, rspamd_text_classname, -1);
			new_t->start = end;
			new_t->len = (t->start + t->len) - end;
			new_t->flags = 0;
		}

		pos = t->len;
	}
	else {

		pos = end - t->start;
	}

	/* Update pos */
	lua_pushinteger(L, pos);
	lua_replace(L, lua_upvalueindex(4));

	return 1;
}

static int
lua_text_split(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	struct rspamd_lua_regexp *re;
	gboolean stringify = FALSE, own_re = FALSE;

	if (t == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	if (lua_type(L, 2) == LUA_TUSERDATA) {
		re = lua_check_regexp(L, 2);
	}
	else {
		rspamd_regexp_t *c_re;
		GError *err = NULL;

		c_re = rspamd_regexp_new(lua_tostring(L, 2), NULL, &err);
		if (c_re == NULL) {

			int ret = luaL_error(L, "cannot parse regexp: %s, error: %s",
								 lua_tostring(L, 2),
								 err == NULL ? "undefined" : err->message);
			if (err) {
				g_error_free(err);
			}

			return ret;
		}

		re = g_malloc0(sizeof(struct rspamd_lua_regexp));
		re->re = c_re;
		re->re_pattern = g_strdup(lua_tostring(L, 2));
		re->module = rspamd_lua_get_module_name(L);
		own_re = TRUE;
	}

	if (re) {
		if (lua_isboolean(L, 3)) {
			stringify = lua_toboolean(L, 3);
		}

		/* Upvalues */
		lua_pushvalue(L, 1); /* text */

		if (own_re) {
			struct rspamd_lua_regexp **pre;
			pre = lua_newuserdata(L, sizeof(struct rspamd_lua_regexp *));
			rspamd_lua_setclass(L, rspamd_regexp_classname, -1);
			*pre = re;
		}
		else {
			lua_pushvalue(L, 2); /* regexp */
		}

		lua_pushboolean(L, stringify);
		lua_pushinteger(L, 0); /* Current pos */
		lua_pushcclosure(L, rspamd_lua_text_regexp_split, 4);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}


static int
lua_text_at(lua_State *L)
{
	return lua_text_byte(L);
}

static int
lua_text_byte(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	if (!t) {
		return luaL_error(L, "invalid arguments");
	}

	gsize start = relative_pos_start(luaL_optinteger(L, 2, 1), t->len);
	gsize end = relative_pos_end(luaL_optinteger(L, 3, start), t->len);
	start--;

	if (start >= end) {
		return 0;
	}

	for (gsize i = start; i < end; i++) {
		lua_pushinteger(L, t->start[i]);
	}
	return end - start;
}

static int
lua_text_memchr(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	int c;
	bool reverse = false;

	if (lua_isnumber(L, 2)) {
		c = lua_tonumber(L, 2);
	}
	else {
		gsize l;
		const char *str = lua_tolstring(L, 2, &l);

		if (str) {
			c = str[0];

			if (l != 1) {
				return luaL_error(L, "need exactly one character to search");
			}
		}
		else {
			return luaL_error(L, "invalid arguments");
		}
	}

	if (t) {
		void *f;

		if (lua_isboolean(L, 3)) {
			reverse = lua_toboolean(L, 3);
		}

		if (reverse) {
			f = rspamd_memrchr(t->start, c, t->len);
		}
		else {
			f = memchr(t->start, c, t->len);
		}

		if (f) {
			lua_pushinteger(L, ((const char *) f) - t->start + 1);
		}
		else {
			lua_pushinteger(L, -1);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_bytes(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t) {
		lua_createtable(L, t->len, 0);

		for (gsize i = 0; i < t->len; i++) {
			lua_pushinteger(L, (unsigned char) t->start[i]);
			lua_rawseti(L, -2, i + 1);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_save_in_file(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	const char *fname = NULL;
	unsigned int mode = 00644;
	int fd = -1;
	gboolean need_close = FALSE;

	if (t != NULL) {
		if (lua_type(L, 2) == LUA_TSTRING) {
			fname = luaL_checkstring(L, 2);

			if (lua_type(L, 3) == LUA_TNUMBER) {
				mode = lua_tointeger(L, 3);
			}
		}
		else if (lua_type(L, 2) == LUA_TNUMBER) {
			/* Created fd */
			fd = lua_tointeger(L, 2);
		}

		if (fd == -1) {
			if (fname) {
				fd = rspamd_file_xopen(fname, O_CREAT | O_WRONLY | O_EXCL, mode, 0);

				if (fd == -1) {
					lua_pushboolean(L, false);
					lua_pushstring(L, strerror(errno));

					return 2;
				}
				need_close = TRUE;
			}
			else {
				fd = STDOUT_FILENO;
			}
		}

		if (!rspamd_write_all(fd, t->start, t->len)) {
			int saved_errno = errno;

			/* A caller-supplied fd is owned (and closed) by the caller */
			if (need_close) {
				close(fd);
				/* Do not leave a truncated file behind */
				unlink(fname);
			}

			lua_pushboolean(L, false);
			lua_pushstring(L, strerror(saved_errno));

			return 2;
		}

		if (need_close) {
			close(fd);
		}

		lua_pushboolean(L, true);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_gc(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t != NULL) {
		g_assert(!(t->flags & RSPAMD_TEXT_FLAG_FAKE));

		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			if (t->flags & RSPAMD_TEXT_FLAG_WIPE) {
				rspamd_explicit_memzero((unsigned char *) t->start, t->len);
			}

			if (t->flags & RSPAMD_TEXT_FLAG_MMAPED) {
				munmap((gpointer) t->start, t->len);
			}
			else {
				if (t->flags & RSPAMD_TEXT_FLAG_SYSMALLOC) {
					free((gpointer) t->start);
				}
				else {
					g_free((gpointer) t->start);
				}
			}
		}
	}

	return 0;
}

static int
lua_text_eq(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t1 = lua_check_text_or_string(L, 1),
						   *t2 = lua_check_text_or_string(L, 2);

	if (t1->len == t2->len) {
		lua_pushboolean(L, memcmp(t1->start, t2->start, t1->len) == 0);
	}
	else {
		lua_pushboolean(L, false);
	}

	return 1;
}

static int
lua_text_lt(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t1 = lua_check_text_or_string(L, 1),
						   *t2 = lua_check_text_or_string(L, 2);

	if (t1 && t2) {
		if (t1->len == t2->len) {
			lua_pushboolean(L, memcmp(t1->start, t2->start, t1->len) < 0);
		}
		else {
			lua_pushboolean(L, t1->len < t2->len);
		}
	}

	return 1;
}

static int
lua_text_concat(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t1 = lua_check_text_or_string(L, 1),
						   *t2 = lua_check_text_or_string(L, 2);

	if (t1 && t2) {
		struct rspamd_lua_text *final;

		final = lua_new_text(L, NULL, t1->len + t2->len, TRUE);
		memcpy((void *) final->start, t1->start, t1->len);
		memcpy((void *) (final->start + t1->len), t2->start, t2->len);
	}

	return 1;
}

static int
lua_text_wipe(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t != NULL) {
		if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			rspamd_explicit_memzero((unsigned char *) t->start, t->len);
		}
		else {
			return luaL_error(L, "cannot wipe not owned text");
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 0;
}

static int
lua_text_base32(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1), *out;
	enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;

	if (t != NULL) {
		if (lua_type(L, 2) == LUA_TSTRING) {
			btype = rspamd_base32_decode_type_from_str(lua_tostring(L, 2));

			if (btype == RSPAMD_BASE32_INVALID) {
				return luaL_error(L, "invalid b32 type: %s", lua_tostring(L, 2));
			}
		}

		out = lua_new_text(L, NULL, t->len * 8 / 5 + 2, TRUE);
		out->len = rspamd_encode_base32_buf(t->start, t->len, (char *) out->start,
											out->len, btype);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_base64(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1), *out;
	gsize line_len = 0;
	gboolean fold = FALSE;

	if (t != NULL) {
		if (lua_type(L, 2) == LUA_TNUMBER) {
			line_len = lua_tointeger(L, 2);

			if (line_len <= 8) {
				return luaL_error(L, "too small line length (at least 8 is required)");
			}
		}

		enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;

		if (lua_type(L, 3) == LUA_TSTRING) {
			const char *how_str = lua_tostring(L, 3);

			if (g_ascii_strcasecmp(how_str, "cr") == 0) {
				how = RSPAMD_TASK_NEWLINES_CR;
			}
			else if (g_ascii_strcasecmp(how_str, "lf") == 0) {
				how = RSPAMD_TASK_NEWLINES_LF;
			}
			else if (g_ascii_strcasecmp(how_str, "crlf") != 0) {
				return luaL_error(L, "invalid newline style: %s", how_str);
			}
		}

		if (lua_type(L, 4) == LUA_TBOOLEAN) {
			fold = lua_toboolean(L, 4);
		}

		gsize sz_len;

		out = lua_newuserdata(L, sizeof(*t));
		out->flags = RSPAMD_TEXT_FLAG_OWN;
		out->start = rspamd_encode_base64_common(t->start, t->len,
												 line_len, &sz_len, fold, how);
		out->len = sz_len;
		rspamd_lua_setclass(L, rspamd_text_classname, -1);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_hex(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1), *out;

	if (t != NULL) {

		out = lua_new_text(L, NULL, t->len * 2, TRUE);
		out->len = rspamd_encode_hex_buf(t->start, t->len, (char *) out->start,
										 out->len);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_crc32(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	int64_t start = 1, len = -1;

	if (t == NULL) {
		return luaL_error(L, "invalid arguments, text required");
	}

	if (lua_isnumber(L, 2)) {
		start = lua_tointeger(L, 2);
	}
	if (lua_isnumber(L, 3)) {
		len = lua_tointeger(L, 3);
	}

	if (start < 1 || (start - 1) > t->len) {
		return luaL_error(L, "invalid start offset %d (text len %d)",
						  (int) start, (int) t->len);
	}

	if (len == -1) {
		len = t->len - (start - 1);
	}

	if (len < 0 || len > (t->len - (start - 1))) {
		return luaL_error(L, "invalid length");
	}

	/* Standard CRC-32 (poly 0xEDB88320), bit-exact with zlib/YARA hash.crc32 */
	const unsigned char *p = (const unsigned char *) t->start + (start - 1);
	gsize remain = (gsize) len;
	uLong crc = crc32(0L, Z_NULL, 0);

	/* zlib crc32() takes a uInt length, so feed the slice in chunks */
	while (remain > 0) {
		uInt chunk = remain > G_MAXUINT ? G_MAXUINT : (uInt) remain;
		crc = crc32(crc, p, chunk);
		p += chunk;
		remain -= chunk;
	}

	lua_pushinteger(L, (lua_Integer) (uint32_t) crc);

	return 1;
}

static int
lua_text_find(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	gsize patlen, init = 1;
	const char *pat = luaL_checklstring(L, 2, &patlen);

	if (t != NULL && pat != NULL) {

		if (lua_isnumber(L, 3)) {
			init = relative_pos_start(lua_tointeger(L, 3), t->len);
		}

		init--;

		if (init > t->len) {
			return luaL_error(L, "invalid arguments to find: init too large");
		}

		goffset pos = rspamd_substring_search(t->start + init,
											  t->len - init,
											  pat, patlen);

		if (pos == -1) {
			lua_pushnil(L);

			return 1;
		}

		lua_pushinteger(L, pos + 1);
		lua_pushinteger(L, pos + patlen);
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 2;
}

#define BITOP(a, b, op) \
	((a)[(uint64_t) (b) / (8u * sizeof *(a))] op(uint64_t) 1 << ((uint64_t) (b) % (8u * sizeof *(a))))

static int
lua_text_exclude_chars(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	gssize patlen;
	const char *pat = lua_tolstring(L, 2, &patlen), *p, *end;
	char *dest, *d;
	uint64_t byteset[32 / sizeof(uint64_t)]; /* Bitset for ascii */
	gboolean copy = TRUE;
	unsigned int *plen;

	if (t != NULL && pat && patlen > 0) {
		if (lua_isboolean(L, 3)) {
			copy = lua_toboolean(L, 3);
		}
		else if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			copy = FALSE;
		}

		if (!copy) {
			dest = (char *) t->start;
			plen = &t->len;
			lua_pushvalue(L, 1); /* Push text as a result */
		}
		else {
			/* We need to copy read only text */
			struct rspamd_lua_text *nt;

			dest = g_malloc(t->len);
			nt = lua_newuserdata(L, sizeof(*nt));
			rspamd_lua_setclass(L, rspamd_text_classname, -1);
			nt->len = t->len;
			nt->flags = RSPAMD_TEXT_FLAG_OWN;
			memcpy(dest, t->start, t->len);
			nt->start = dest;
			plen = &nt->len;
		}

		/* Fill pattern bitset */
		memset(byteset, 0, sizeof byteset);

		while (patlen > 0) {
			if (*pat == '%') {
				pat++;
				patlen--;

				if (patlen > 0) {
					/*
					 * This stuff assumes little endian, but GUINT64_FROM_LE should
					 * deal with proper conversion
					 */
					switch (*pat) {
					case '%':
						BITOP(byteset, *(unsigned char *) pat, |=);
						break;
					case 's':
						/* "\r\n\t\f " */
						byteset[0] |= GUINT64_FROM_LE(0x100003600LLU);
						break;
					case 'n':
						/* newlines: "\r\n" */
						byteset[0] |= GUINT64_FROM_LE(0x2400LLU);
						break;
					case '8':
						/* 8 bit characters */
						byteset[2] |= GUINT64_FROM_LE(0xffffffffffffffffLLU);
						byteset[3] |= GUINT64_FROM_LE(0xffffffffffffffffLLU);
						break;
					case 'c':
						/* Non printable (control) characters */
						byteset[0] |= GUINT64_FROM_LE(0xffffffffLLU);
						/* Del character */
						byteset[1] |= GUINT64_FROM_LE(0x8000000000000000LLU);
						break;
					}
				}
				else {
					/* Last '%' */
					BITOP(byteset, (unsigned char) '%', |=);
				}
			}
			else {
				BITOP(byteset, *(unsigned char *) pat, |=);
			}

			pat++;
			patlen--;
		}
		for (; patlen > 0 && BITOP(byteset, *(unsigned char *) pat, |=); pat++, patlen--);

		p = t->start;
		end = t->start + t->len;
		d = dest;

		while (p < end) {
			if (!BITOP(byteset, *(unsigned char *) p, &)) {
				*d++ = *p;
			}

			p++;
		}

		*(plen) = d - dest;
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_memcspn(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	const char *reject_chars;
	gsize reject_len, span_len;

	if (t == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	reject_chars = luaL_checklstring(L, 2, &reject_len);
	if (reject_chars == NULL || reject_len == 0) {
		/* No reject chars - return full length */
		lua_pushinteger(L, t->len);
		return 1;
	}

	/* Use rspamd_memcspn from str_util */
	span_len = rspamd_memcspn(t->start, t->len, reject_chars, reject_len);
	lua_pushinteger(L, span_len);

	return 1;
}

static int
lua_text_oneline(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	const char *p, *end;
	char *dest, *d;
	uint64_t byteset[32 / sizeof(uint64_t)]; /* Bitset for ascii */
	gboolean copy = TRUE, seen_8bit = FALSE;
	unsigned int *plen;

	if (t != NULL) {
		if (lua_isboolean(L, 2)) {
			copy = lua_toboolean(L, 2);
		}
		else if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
			copy = FALSE;
		}

		if (!copy) {
			dest = (char *) t->start;
			plen = &t->len;
			lua_pushvalue(L, 1); /* Push text as a result */
		}
		else {
			/* We need to copy read only text */
			struct rspamd_lua_text *nt;

			dest = g_malloc(t->len);
			nt = lua_newuserdata(L, sizeof(*nt));
			rspamd_lua_setclass(L, rspamd_text_classname, -1);
			nt->len = t->len;
			nt->flags = RSPAMD_TEXT_FLAG_OWN;
			memcpy(dest, t->start, t->len);
			nt->start = dest;
			plen = &nt->len;
		}

		/* Fill pattern bitset */
		memset(byteset, 0, sizeof byteset);
		/* All spaces */
		byteset[0] |= GUINT64_FROM_LE(0x100003600LLU);
		/* Control characters */
		byteset[0] |= GUINT64_FROM_LE(0xffffffffLLU);
		/* Del character */
		byteset[1] |= GUINT64_FROM_LE(0x8000000000000000LLU);
		/* 8 bit characters */
		byteset[2] |= GUINT64_FROM_LE(0xffffffffffffffffLLU);
		byteset[3] |= GUINT64_FROM_LE(0xffffffffffffffffLLU);

		p = t->start;
		end = t->start + t->len;
		d = dest;

		while (p < end) {
			if (!BITOP(byteset, *(unsigned char *) p, &)) {
				*d++ = *p;
			}
			else {
				if ((*(unsigned char *) p) & 0x80) {
					seen_8bit = TRUE;
					*d++ = *p;
				}
				else {
					if (*p == ' ') {
						if (d != dest) {
							*d++ = *p++;
						}

						while (p < end && g_ascii_isspace(*p)) {
							p++;
						}

						continue; /* To avoid p++ */
					}
					else if (*p == '\r' || *p == '\n') {
						if (d != dest) {
							*d++ = ' ';
							p++;
						}

						while (p < end && g_ascii_isspace(*p)) {
							p++;
						}

						continue; /* To avoid p++ */
					}
				}
			}

			p++;
		}

		while (d > dest && g_ascii_isspace(*(d - 1))) {
			d--;
		}

		if (seen_8bit) {
			if (rspamd_fast_utf8_validate(dest, d - dest) != 0) {
				/* Need to make it valid :( */
				UChar32 uc;
				goffset err_offset;
				gsize remain = d - dest;
				char *nd = dest;

				while (remain > 0 && (err_offset = rspamd_fast_utf8_validate(nd, remain)) > 0) {
					int i = 0;

					err_offset--; /* As it returns it 1 indexed */
					nd += err_offset;
					remain -= err_offset;

					/* Each invalid character of input requires 3 bytes of output (+2 bytes) */
					while (i < remain) {
						int old_pos = i;
						U8_NEXT(nd, i, remain, uc);

						if (uc < 0) {
							nd[old_pos] = '?';
						}
						else {
							break;
						}
					}

					nd += i;
					remain -= i;
				}
			}
		}

		*(plen) = d - dest;
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_normalize_newlines(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	rspamd_mempool_t *pool = NULL;
	enum rspamd_text_newline_mode mode = RSPAMD_TEXT_NEWLINES_CRLF;

	if (t == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	/* Check for mode argument */
	if (lua_type(L, 2) == LUA_TSTRING) {
		const char *mode_str = lua_tostring(L, 2);

		if (g_ascii_strcasecmp(mode_str, "lf") == 0 ||
			g_ascii_strcasecmp(mode_str, "unix") == 0) {
			mode = RSPAMD_TEXT_NEWLINES_LF;
		}
		else if (g_ascii_strcasecmp(mode_str, "crlf") == 0 ||
				 g_ascii_strcasecmp(mode_str, "windows") == 0) {
			mode = RSPAMD_TEXT_NEWLINES_CRLF;
		}
		else if (g_ascii_strcasecmp(mode_str, "smtp") == 0) {
			mode = RSPAMD_TEXT_NEWLINES_SMTP;
		}
		else {
			return luaL_error(L, "invalid mode: %s (expected 'lf', 'crlf' or 'smtp')", mode_str);
		}
	}

	/* Check for pool argument */
	if (lua_type(L, 3) == LUA_TUSERDATA) {
		pool = rspamd_lua_check_mempool(L, 3);
	}

	/* Normalize the text (may return same pointer if no changes) */
	rspamd_lua_text_normalize_newlines(t, pool, mode);

	/* Return the (possibly modified) text */
	lua_pushvalue(L, 1);

	return 1;
}

static int
lua_text_lower(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1), *nt;
	gboolean is_utf8 = FALSE, is_inplace = FALSE;

	if (t != NULL) {
		if (lua_isboolean(L, 2)) {
			is_utf8 = lua_toboolean(L, 2);
		}
		if (lua_isboolean(L, 3)) {
			is_inplace = lua_toboolean(L, 3);
		}

		if (is_inplace) {
			nt = t;
			lua_pushvalue(L, 1);
		}
		else {
			nt = lua_new_text(L, t->start, t->len, TRUE);
		}

		if (!is_utf8) {
			rspamd_str_lc((char *) nt->start, nt->len);
		}
		else {
			rspamd_str_lc_utf8((char *) nt->start, nt->len);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_strtoul(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);

	if (t) {
		unsigned long ll;

		if (rspamd_strtoul(t->start, t->len, &ll)) {
			lua_pushinteger(L, ll);
		}
		else {
			lua_pushnil(L);
		}
	}
	else {
		return luaL_error(L, "invalid arguments");
	}

	return 1;
}

static int
lua_text_len_utf8(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	if (t != NULL) {
		const char *s = t->start;
		int32_t count = 0, i = 0;
		UChar32 c;
		while (i < t->len) {
			U8_NEXT(s, i, t->len, c);
			if (c < 0) {
				lua_pushnil(L);
				return 1;
			}
			count++;
		}

		lua_pushinteger(L, count);
		return 1;
	}
	else {
		return luaL_error(L, "invalid arguments");
	}
}

static int
lua_text_sub_utf8(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_text *t = lua_check_text(L, 1);
	if (t == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	UChar32 c;

	int32_t start = luaL_checkinteger(L, 2);
	int32_t finish = luaL_optinteger(L, 3, -1);

	int32_t len_utf8 = 0;
	int32_t i = 0;
	while (i < t->len) {
		U8_NEXT(t->start, i, t->len, c);
		if (c < 0) {
			lua_pushnil(L);
			return 1;
		}

		len_utf8++;
	}

	start = relative_pos_start(start, len_utf8);
	finish = relative_pos_end(finish, len_utf8);

	if (start > finish) {
		lua_new_text(L, "", 0, TRUE);
		return 1;
	}

	const char *sub_start = t->start;
	const char *sub_end = t->start;
	int32_t char_pos = 0, remain, utf8_idx = 0;

	while (char_pos < t->len && utf8_idx < start - 1) {
		U8_NEXT(t->start, char_pos, t->len, c);
		sub_start = &t->start[char_pos];
		utf8_idx++;
	}

	remain = (t->start + t->len) - sub_start;
	char_pos = 0;

	while (char_pos < remain && utf8_idx < finish) {
		U8_NEXT(sub_start, char_pos, remain, c);
		sub_end = &sub_start[char_pos];
		utf8_idx++;
	}

	/* Copy as we have no other options to make it safe */
	lua_new_text(L, sub_start, sub_end - sub_start, TRUE);

	return 1;
}

/* Used to distinguish lua text metatable */
static const unsigned int rspamd_lua_text_cookie = 0x2b21ef6fU;

static int
lua_load_text(lua_State *L)
{
	lua_newtable(L);
	lua_pushstring(L, "cookie");
	lua_pushnumber(L, rspamd_lua_text_cookie);
	lua_settable(L, -3);
	luaL_register(L, NULL, textlib_f);

	return 1;
}

void luaopen_text(lua_State *L)
{
	rspamd_lua_new_class(L, rspamd_text_classname, textlib_m);
	lua_pushstring(L, "cookie");
	lua_pushnumber(L, rspamd_lua_text_cookie);
	lua_settable(L, -3);
	lua_pop(L, 1);

	rspamd_lua_add_preload(L, "rspamd_text", lua_load_text);
}