url-cleaner-engine 0.11.0

The engine behind URL Cleaner.
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
//! Rules for modifying strings.

use std::borrow::Cow;
use std::str::FromStr;

use serde::{Serialize, Deserialize};
use thiserror::Error;
use ::percent_encoding::{percent_decode_str, utf8_percent_encode};
#[expect(unused_imports, reason = "Used in a doc comment.")]
#[cfg(feature = "regex")]
use ::regex::Regex;
#[cfg(feature = "base64")]
use ::base64::prelude::*;
use ::percent_encoding::percent_decode_str as pds;

use crate::types::*;
use crate::glue::*;
use crate::util::*;

/// Modify a string.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Suitability)]
#[serde(deny_unknown_fields)]
#[serde(remote = "Self")]
pub enum StringModification {
    /// Doesn't do any modification.
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::None.apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("abc".into()));
    /// ```
    None,



    /// Print debug info about the contained [`Self`] and its call to [`Self::apply`].
    ///
    /// The exact info printed is unspecified and subject to change at any time for any reason.
    /// # Suitability
    /// Always unsuitable to be in the default config.
    /// # Errors
    /// If the call to [`Self::apply`] returns an error, that error is returned after the debug info is printed.
    #[suitable(never)]
    Debug(Box<Self>),



    /// Always returns the error [`StringModificationError::ExplicitError`] with the included message.
    /// # Errors
    /// Always returns the error [`StringModificationError::ExplicitError`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::Error("...".into()).apply(&mut to, &task_state_view).unwrap_err();
    ///
    /// assert_eq!(to, Some("abc".into()));
    /// ```
    Error(String),
    /// If the contained [`Self`] returns an error, ignore it.
    ///
    /// Does not revert any successful calls to [`Self::apply`]. For that, also use [`Self::RevertOnError`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::IgnoreError(Box::new(StringModification::Error("...".into()))).apply(&mut to, &task_state_view).unwrap();
    /// ```
    IgnoreError(Box<Self>),
    /// If the contained [`Self`] returns an error, revert the string to its previous value then return the error.
    /// # Errors
    #[doc = edoc!(applyerr(Self))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::RevertOnError(Box::new(StringModification::All(vec![
    ///     StringModification::Set("def".into()),
    ///     StringModification::Error("...".into())
    /// ]))).apply(&mut to, &task_state_view).unwrap_err();
    ///
    /// assert_eq!(to, Some("abc".into()));
    /// ```
    RevertOnError(Box<Self>),
    /// If [`Self::TryElse::try`]'s call to [`Self::apply`] returns an error, apply [`Self::TryElse::else`].
    ///
    /// Does not revert on error. For that, see [`Self::RevertOnError`].
    /// # Errors
    #[doc = edoc!(applyerrte(Self, StringModification))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::TryElse {
    ///     r#try : Box::new(StringModification::Error("...".into())),
    ///     r#else: Box::new(StringModification::Set("def".into()))
    /// }.apply(&mut to, &task_state_view);
    /// ```
    TryElse {
        /// The [`Self`] to try first.
        r#try: Box<Self>,
        /// The [`Self`] to try if [`Self::TryElse::try`] returns an error.
        r#else: Box<Self>
    },
    /// Applies the contained [`Self`]s in order.
    ///
    /// Does not revert on error. For that, see [`Self::RevertOnError`].
    /// # Errors
    #[doc = edoc!(applyerr(Self, 3))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::All(vec![
    ///     StringModification::Append("def".into()),
    ///     StringModification::Error("...".into())
    /// ]).apply(&mut to, &task_state_view).unwrap_err();
    ///
    /// assert_eq!(to, Some("abcdef".into()));
    /// ```
    All(Vec<Self>),
    /// Calls [`Self::apply`] on each contained [`Self`] in order, stopping once one returns [`Ok`].
    ///
    /// Does not revert on error. For that, see [`Self::RevertOnError`].
    /// # Errors
    #[doc = edoc!(applyerrfne(Self, StringModification))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::FirstNotError(vec![
    ///     StringModification::Append("def".into()),
    ///     StringModification::Error("...".into())
    /// ]).apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("abcdef".into()));
    /// ```
    FirstNotError(Vec<Self>),



    /// Only apply the [`Self`] if the string is [`Some`].
    /// # Errors
    #[doc = edoc!(applyerr(Self))]
    IfSome(Box<Self>),
    /// If the string satisfies [`Self::IfMatches::matcher`], apply [`Self::IfMatches::then`].
    ///
    /// If the string does not satisfy [`Self::IfMatches::matcher`] and [`Self::IfMatches::else`] is [`Some`], apply [`Self::IfMatches::else`].
    /// # Errors
    #[doc = edoc!(checkerr(StringMatcher), applyerr(Self))]
    IfMatches {
        /// The [`StringMatcher`] to check if the string satisfies.
        matcher: Box<StringMatcher>,
        /// The [`Self`] to apply if [`Self::IfMatches::matcher`] is satisfied.
        then: Box<Self>,
        /// The [`Self`] to apply if [`Self::IfMatches::matcher`] isn't satisfied.
        ///
        /// Defaults to [`None`].
        #[serde(default, skip_serializing_if = "is_default")]
        r#else: Option<Box<Self>>
    },
    /// If the string contains [`Self::IfContains::value`] at [`Self::IfContains::at`], apply [`Self::IfContains::then`], otherwise apply [`Self::IfContains::else`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModificationError), checkerr(StringLocation), applyerr(Self))]
    IfContains {
        /// The [`StringSource`] to look for in the string.
        value: StringSource,
        /// The [`StringLocation`] to look for [`Self::IfContains::value`] at.
        at: StringLocation,
        /// The [`Self`] to apply if [`Self::IfContains::value`] is found at [`Self::IfContains::at`].
        then: Box<Self>,
        /// The [`Self`] to apply if [`Self::IfContains::value`] is not found at [`Self::IfContains::at`].
        r#else: Option<Box<Self>>
    },
    /// If the string contains any value in [`Self::IfContainsAny::values`] at [`Self::IfContains::at`], apply [`Self::IfContains::then`], otherwise apply [`Self::IfContains::else`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 3), getnone(StringSource, StringModificationError, 3), checkerr(StringLocation, 3), applyerr(Self, 3))]
    IfContainsAny {
        /// The [`StringSource`]s to look for in the string.
        values: Vec<StringSource>,
        /// The [`StringLocation`] to look for [`Self::IfContainsAny::values`] at.
        at: StringLocation,
        /// The [`Self`] to apply if any value in [`Self::IfContainsAny::values`] is found at [`Self::IfContains::at`].
        then: Box<Self>,
        /// The [`Self`] to apply if no values in [`Self::IfContainsAny::values`] are found at [`Self::IfContains::at`].
        r#else: Option<Box<Self>>
    },
    /// Indexes [`Self::Map::map`] with [`Self::Map::value`] and, if a [`Self`] is found, applies it.
    ///
    /// If the call to [`Map::get`] returns [`None`], does nothing.
    /// # Errors
    #[doc = edoc!(geterr(StringSource), applyerr(Self))]
    Map {
        /// The value to index [`Self::Map::map`] with.
        value: Box<StringSource>,
        /// The [`Map`] to index with [`Self::Map::value`].
        #[serde(flatten)]
        map: Map<Self>,
    },



    /// Sets the string to the specified value.
    /// # Errors
    #[doc = edoc!(geterr(StringSource))]
    Set(StringSource),
    /// Appends the specified value.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    Append(StringSource),
    /// Prepends the specified value.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    Prepend(StringSource),
    /// Insert [`Self::Insert::value`] at [`Self::Insert::index`].
    ///
    /// See [`String::insert_str`] for details.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If [`Self::Insert::index`] isn't a [`str::is_char_boundary`], returns the error [`StringModificationError::InvalidIndex`].
    Insert {
        /// The value to insert at [`Self::Insert::index`].
        value: StringSource,
        /// The index to insert [`Self::Insert::value`] at.
        index: isize
    },
    /// Sets the string to lowercase.
    ///
    /// See [`str::to_lowercase`] for details.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    Lowercase,
    /// Sets the string to uppercase.
    ///
    /// See [`str::to_uppercase`] for details.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    Uppercase,



    /// Removes the specified prefix.
    ///
    /// If you want to not return an error when the string doesn't start with the prefix, see [`Self::StripMaybePrefix`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the string doesn't start with the specified prefix, returns the error [`StringModificationError::PrefixNotFound`].
    StripPrefix(StringSource),
    /// If the string starts with the specified value, remove it.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    StripMaybePrefix(StringSource),
    /// Removes the specified suffix.
    ///
    /// If you want to not return an error when the string doesn't start with the suffix, see [`Self::StripMaybeSuffix`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the string doesn't start with the specified suffix, returns the error [`StringModificationError::SuffixNotFound`].
    StripSuffix(StringSource),
    /// If the string ends with the specified value, remove it.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    StripMaybeSuffix(StringSource),
    /// Removes the [`char`] at the specified index.
    ///
    /// See [`String::remove`] for details.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    ///
    /// If the specified index isn't a [`str::is_char_boundary`], returns the error [`StringModificationError::InvalidIndex`].
    RemoveChar(isize),



    /// Finds the first instance of the specified substring and keeps only everything before it.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the specified substring isn't found, returns the error [`StringModificationError::SubstringNotFound`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::KeepBefore("b".into()).apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("a".into()));
    /// ```
    KeepBefore(StringSource),
    /// Finds the first instance of the specified substring and removes everything before it.
    ///
    /// Useful in combination with [`Self::GetJsStringLiteralPrefix`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the specified substring isn't found, returns the error [`StringModificationError::SubstringNotFound`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::StripBefore("b".into()).apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("bc".into()));
    /// ```
    StripBefore(StringSource),
    /// Effectively [`Self::KeepAfter`] with [`Self::KeepBetween::start`] and [`Self::KeepBefore`] with [`Self::KeepBetween::end`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 2), getnone(StringSource, StringModification, 2))]
    ///
    /// If the value of [`Self::KeepBetween::start`] isn't found in the string, returns the error [`StringModificationError::KeepBetweenStartNotFound`].
    ///
    /// If the value of [`Self::KeepBetween::end`] isn't found in the string after [`Self::KeepBetween::start`], returns the error [`StringModificationError::KeepBetweenEndNotFound`].
    KeepBetween {
        /// The value to [`Self::KeepAfter`].
        start: StringSource,
        /// The value to [`Self::KeepBefore`].
        end: StringSource
    },
    /// Finds the first instance of the specified substring and removes everything after it.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the specified substring isn't found, returns the error [`StringModificationError::SubstringNotFound`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::StripAfter("b".into()).apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("ab".into()));
    /// ```
    StripAfter(StringSource),
    /// Finds the first instance of the specified substring and keeps only everything after it.
    ///
    /// Useful in combination with [`Self::GetHtmlAttribute`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the specified substring isn't found, returns the error [`StringModificationError::SubstringNotFound`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state_view);
    /// let mut to = Some("abc".into());
    ///
    /// StringModification::KeepAfter("b".into()).apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("c".into()));
    /// ```
    KeepAfter(StringSource),



    /// [`Self::KeepAfter`] but does nothing if the substring isn't found.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModificationError))]
    KeepMaybeBefore(StringSource),
    /// [`Self::StripBefore`] but does nothing if the substring isn't found.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModificationError))]
    StripMaybeBefore(StringSource),
    /// [`Self::KeepBetween`] but with [`Self::KeepAfter`] [`Self::KeepBefore`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 2), getnone(StringSource, StringModification, 2))]
    KeepMaybeBetween {
        /// The value to [`Self::KeepMaybeAfter`].
        start: StringSource,
        /// The value to [`Self::KeepMaybeBefore`].
        end: StringSource
    },
    /// [`Self::StripAfter`] but does nothing if the substring isn't found.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModificationError))]
    StripMaybeAfter(StringSource),
    /// [`Self::KeepAfter`] but does nothing if the substring isn't found.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModificationError))]
    KeepMaybeAfter(StringSource),



    /// Replace up to [`Self::Replacen::count`] instances of [`Self::Replacen::find`] with [`Self::Replacen::replace`].
    ///
    /// See [`str::replacen`] for details.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    Replacen {
        /// The value to replace with [`Self::Replacen::replace`].
        find: StringSource,
        /// The value to replace instances of [`Self::Replacen::find`] with.
        replace: StringSource,
        /// The maximum amount of instances to replace.
        count: usize
    },
    /// Replace all instances of [`Self::ReplaceAll::find`] with [`Self::ReplaceAll::replace`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 2), getnone(StringSource, StringModification, 2))]
    ReplaceAll {
        /// The value to replace with [`Self::ReplaceAll::replace`].
        find: StringSource,
        /// The value to replace instances of [`Self::ReplaceAll::find`] with.
        replace: StringSource
    },



    /// Replace the specified range with [`Self::ReplaceRange::replace`].
    /// # Errors
    /// If either [`Self::ReplaceRange::start`] and/or [`Self::ReplaceRange::end`] isn't a [`str::is_char_boundary`], returns the error [`StringModificationError::InvalidSlice`].
    ///
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ReplaceRange {
        /// The start of the range to replace.
        start: isize,
        /// The end of the range to replace.
        end: Option<isize>,
        /// The value to replace the range with.
        replace: StringSource
    },
    /// Removes everything outside the specified range.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    ///
    /// If either [`Self::KeepRange::start`] and/or [`Self::KeepRange::end`] isn't a [`str::is_char_boundary`], returns the error [`StringModificationError::InvalidSlice`].
    KeepRange {
        /// The start of the range to keep.
        start: isize,
        /// The end of the range to keep.
        end: Option<isize>
    },



    /// Split the string with [`Self::SetSegment::split`] and set the [`Self::SetSegment::index`] segment to [`Self::SetSegment::value`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 2))]
    ///
    /// If the segment isn't found, returns the error [`StringModificationError::SegmentNotFound`].
    SetSegment {
        /// The value to split the string with.
        split: StringSource,
        /// The index of the segment to set.
        index: isize,
        /// The value to set the segment to.
        value: StringSource,
        /// If [`Some`], the value to join with.
        ///
        /// If [`None`], joins with [`Self::KeepSegments::split`].
        join: Option<StringSource>
    },
    /// Split the string with [`Self::InsertSegment::split`] and inserts [`Self::InsertSegment::value`] before the [`Self::InsertSegment::index`] segment.
    ///
    /// If [`Self::InsertSegment::index`] is equal to the amount of segments, appends the new segment at the end.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource, 2))]
    ///
    /// If the segment boundary isn't found, returns the error [`StringModificationError::SegmentNotFound`].
    InsertSegment {
        /// The value to split the string with.
        split: StringSource,
        /// The location to insert the value at.
        index: isize,
        /// The value to insert.
        value: StringSource,
        /// If [`Some`], the value to join with.
        ///
        /// If [`None`], joins with [`Self::KeepSegments::split`].
        ///
        /// Defaults to [`None`].
        #[serde(default, skip_serializing_if = "is_default")]
        join: Option<StringSource>
    },
    /// Split the string with [`Self::KeepSegment::split`] and keep only the [`Self::KeepSegment::index`] segment.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the segment isn't found, returns the error [`StringModificationError::SegmentNotFound`].
    KeepSegment {
        /// The value to split the string on.
        split: StringSource,
        /// The index of the segment to keep.
        index: isize,
    },
    /// Split the string with [`Self::KeepSegmentRange`] and keep only the segments between [`Self::KeepSegmentRange::start`] (inclusive) and [`Self::KeepSegmentRange::end`] (exclusive).
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification))]
    ///
    /// If the range isn't found, returns the error [`StringModificationError::SegmentRangeNotFound`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    /// url_cleaner_engine::task_state_view!(task_state_view);
    ///
    /// let mut to = Some("a/b/c/d/e".into());
    ///
    /// StringModification::KeepSegmentRange {
    ///     split: "/".into(),
    ///     start: 1,
    ///     end: Some(4),
    ///     join: None
    /// }.apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("b/c/d".into()));
    ///
    /// StringModification::KeepSegmentRange {
    ///     split: "/".into(),
    ///     start: 0,
    ///     end: Some(-1),
    ///     join: None
    /// }.apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("b/c".into()));
    ///
    /// StringModification::KeepSegmentRange {
    ///     split: "/".into(),
    ///     start: 0,
    ///     end: None,
    ///     join: Some("-".into())
    /// }.apply(&mut to, &task_state_view).unwrap();
    ///
    /// assert_eq!(to, Some("b-c".into()));
    /// ```
    KeepSegmentRange {
        /// The value to split the string with.
        split: StringSource,
        /// The index of the first segment to keep.
        ///
        /// Defaults to `0`.
        #[serde(default, skip_serializing_if = "is_default")]
        start: isize,
        /// The index of the last segment to keep.
        ///
        /// Set to [`None`] to keep all segments after [`Self::KeepSegmentRange::start`].
        ///
        /// Defaults to [`None`].
        #[serde(default, skip_serializing_if = "is_default")]
        end: Option<isize>,
        /// If [`Some`], the value to join with.
        ///
        /// If [`None`], joins with [`Self::KeepSegments::split`].
        ///
        /// Defaults to [`None`].
        #[serde(default, skip_serializing_if = "is_default")]
        join: Option<StringSource>
    },
    /// If [`Self::KeepSegments::join`] is [`None`], joins on the same value as [`Self::KeepSegments::split`].
    KeepSegments {
        /// The value to split the string with.
        split: StringSource,
        /// The list of segments to keep.
        indices: Vec<isize>,
        /// If [`Some`], the value to join with.
        ///
        /// If [`None`], joins with [`Self::KeepSegments::split`].
        ///
        /// Defaults to [`None`].
        #[serde(default, skip_serializing_if = "is_default")]
        join: Option<StringSource>
    },
    /// If [`Self::KeepModifiedSegments::join`] is [`None`], joins on the same value as [`Self::KeepModifiedSegments::split`].
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// url_cleaner_engine::task_state_view!(task_state);
    ///
    /// let mut to = Some("a/b/c".into());
    ///
    /// StringModification::KeepModifiedSegments {
    ///   split: "/".into(),
    ///   indices: vec![-1, 0],
    ///   modification: Box::new(StringModification::Uppercase),
    ///   join: None
    /// }.apply(&mut to, &task_state).unwrap();
    ///
    /// assert_eq!(to, Some("A/C".into()));
    ///
    /// let mut to = Some("a/b/c".into());
    ///
    /// StringModification::KeepModifiedSegments {
    ///   split: "/".into(),
    ///   indices: vec![-1, 0],
    ///   modification: Box::new(StringModification::Lowercase),
    ///   join: Some("-".into())
    /// }.apply(&mut to, &task_state).unwrap();
    ///
    /// assert_eq!(to, Some("a-c".into()));
    /// ```
    KeepModifiedSegments {
        /// The value to split the string with.
        split: StringSource,
        /// The list of segments to keep.
        indices: Vec<isize>,
        /// The [`Self`] to apply.
        modification: Box<Self>,
        /// If [`Some`], the value to join with.
        ///
        /// If [`None`], joins with [`Self::KeepModifiedSegments::split`].
        #[serde(default, skip_serializing_if = "is_default")]
        join: Option<StringSource>
    },



    /// Parses the javascript string literal at the start of the string and returns its value.
    ///
    /// Useful in combination with [`Self::KeepAfter`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), callerr(parse::js::string_literal_prefix))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    /// url_cleaner_engine::task_state_view!(task_state);
    ///
    /// let mut to = Some(r#"let destination = "https:\/\/example.com";"#.into());
    ///
    /// StringModification::All(vec![
    ///     StringModification::KeepAfter("let destination = ".into()),
    ///     StringModification::GetJsStringLiteralPrefix
    /// ]).apply(&mut to, &task_state).unwrap();;
    ///
    /// assert_eq!(to, Some("https://example.com".into()));
    /// ```
    GetJsStringLiteralPrefix,
    /// Processes HTML character references/escape codes like `&map;` into `&` and `&41;` into `A`.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), callerr(parse::html::unescape_text))]
    UnescapeHtmlText,
    /// Parses the HTML element at the start of the string and returns the [`Self::UnescapeHtmlText`]ed value of the last attribute with the specified name.
    ///
    /// Useful in combination with [`Self::StripBefore`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), callerr(parse::html::get_attribute_value))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    /// url_cleaner_engine::task_state_view!(task_state);
    ///
    /// let mut to = Some(r#"Redirecting you to <a id="destination" href="https://example.com?a=2&amp;b=3">example.com</a>..."#.into());
    ///
    /// StringModification::All(vec![
    ///     StringModification::StripBefore(r#"<a id="destination""#.into()),
    ///     StringModification::GetHtmlAttribute("href".into())
    /// ]).apply(&mut to, &task_state).unwrap();
    ///
    /// assert_eq!(to, Some("https://example.com?a=2&b=3".into()));
    /// ```
    GetHtmlAttribute(StringSource),



    /// Calls [`Regex::find`] and returns its value.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(RegexWrapper), callnone(Regex::find, StringModificationError::RegexMatchNotFound))]
    #[cfg(feature = "regex")]
    RegexFind(RegexWrapper),
    /// Calls [`::regex::Regex::captures`] and returns the result of [`::regex::Captures::expand`]ing with [`Self::RegexSubstitute::replace`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification), callnone(Regex::captures, StringModificationError::RegexMatchNotFound))]
    #[cfg(feature = "regex")]
    RegexSubstitute {
        /// The [`RegexWrapper`] to capture with.
        regex: RegexWrapper,
        /// The format string to pass to [`::regex::Captures::expand`].
        replace: StringSource
    },
    /// [`::regex::Captures::expand`]s each [`::regex::Regex::captures_iter`] with [`Self::JoinAllRegexSubstitutions::replace`] and join them with [`Self::JoinAllRegexSubstitutions::join`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification), geterr(RegexWrapper))]
    #[cfg(feature = "regex")]
    JoinAllRegexSubstitutions {
        /// The [`RegexWrapper`] to capture with.
        regex: RegexWrapper,
        /// The format string to pass to [`::regex::Captures::expand`].
        replace: StringSource,
        /// The [`StringSource`] to join the expanded captures with.
        join: StringSource
    },
    /// [`Regex::replace`]s the first match of [`Self::RegexReplaceOne::regex`] with [`Self::RegexReplaceOne::replace`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification), geterr(RegexWrapper))]
    #[cfg(feature = "regex")]
    RegexReplaceOne {
        /// The [`RegexWrapper`] to search with.
        regex: RegexWrapper,
        /// The format string to expand the capture with.
        replace: StringSource
    },
    /// [`Regex::replace`]s the all matches of [`Self::RegexReplaceAll::regex`] with [`Self::RegexReplaceAll::replace`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification), geterr(RegexWrapper))]
    #[cfg(feature = "regex")]
    RegexReplaceAll {
        /// The [`RegexWrapper`] to search with.
        regex: RegexWrapper,
        /// The format string to expand the captures with.
        replace: StringSource
    },
    /// [`Regex::replacen`]s the first [`Self::RegexReplacen::n`] of [`Self::RegexReplacen::regex`] with [`Self::RegexReplacen::replace`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), geterr(StringSource), getnone(StringSource, StringModification), geterr(RegexWrapper))]
    #[cfg(feature = "regex")]
    RegexReplacen {
        /// The [`RegexWrapper`] to search with.
        regex: RegexWrapper,
        /// The number of captures to find and replace.
        n: usize,
        /// The format string to expand the captures with.
        replace: StringSource
    },



    /// Parses the string as JSON and uses [`serde_json::Value::pointer_mut`] with the specified pointer.
    ///
    /// When extracting values from javascript, it's often faster to find the start of the desired string and use [`Self::GetJsStringLiteralPrefix`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), callerr(serde_json::from_str), geterr(StringSource), getnone(StringSource, StringModification), callnone(serde_json::Value::pointer_mut, StringModificationError::JsonValueNotFound))]
    ///
    /// If the call to [`serde_json::Value::pointer_mut`] doesn't return a [`serde_json::Value::String`], returns the error [`StringModificationError::JsonPointeeIsNotAString`].
    JsonPointer(StringSource),



    /// Percent encodes the string.
    ///
    /// Please note that this can be deserialized from `"PercentDecode"`, in which case the contained [`PercentEncodeAlphabet`] is defaulted.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// assert_eq!(serde_json::from_str::<StringModification>(r#""PercentEncode""#).unwrap(), StringModification::PercentEncode(Default::default()));
    /// ```
    PercentEncode(#[serde(default, skip_serializing_if = "is_default")] PercentEncodeAlphabet),
    /// Percent decodes the string.
    ///
    /// Unfortunately doesn't allow specifying a [`PercentEncodeAlphabet`] to keep certain values encoded due to limitations with the [`::percent_encoding`] API.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), callerr(::percent_encoding::PercentDecode::decode_utf8))]
    PercentDecode,
    /// [`Self::PercentDecode`] but replaces non-UTF-8 percent encoded byte sequences with U+FFFD (�), the replacement character.
    ///
    /// Unfortunately doesn't allow specifying a [`PercentEncodeAlphabet`] to keep certain values encoded due to limitations with the [`::percent_encoding`] API.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    LossyPercentDecode,



    /// Base64 encodes the string.
    ///
    /// Please note that this can be deserialized from `"Base64Encode"`, in which case the contained [`Base64Config`] is defaulted.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// assert_eq!(serde_json::from_str::<StringModification>(r#""Base64Encode""#).unwrap(), StringModification::Base64Encode(Default::default()));
    /// ```
    #[cfg(feature = "base64")]
    Base64Encode(#[serde(default, skip_serializing_if = "is_default")] Base64Config),
    /// Base64 decodes the string.
    ///
    /// Please note that this can be deserialized from `"Base64Decode"`, in which case the contained [`Base64Config`] is defaulted.
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), callerr(::base64::engine::GeneralPurpose::decode), callerr(String::from_utf8))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    ///
    /// assert_eq!(serde_json::from_str::<StringModification>(r#""Base64Decode""#).unwrap(), StringModification::Base64Decode(Default::default()));
    /// ```
    #[cfg(feature = "base64")]
    Base64Decode(#[serde(default, skip_serializing_if = "is_default")] Base64Config),



    /// The same operation [`Action::RemoveQueryParamsMatching`] does to a [`UrlPart::Query`].
    /// # Errors
    /// If the string is [`None`], returns the error [`StringModificationError::StringIsNone`].
    ///
    #[doc = edoc!(stringisnone(StringModification), checkerr(StringMatcher, 3))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    /// url_cleaner_engine::task_state_view!(task_state);
    ///
    /// let mut to = Some("a=2&b=3&%61=4&c=5".into());
    ///
    /// StringModification::RemoveQueryParamsMatching(Box::new(StringMatcher::Is("a".into()))).apply(&mut to, &task_state).unwrap();
    /// assert_eq!(to, Some("b=3&c=5".into()));
    /// StringModification::RemoveQueryParamsMatching(Box::new(StringMatcher::Is("b".into()))).apply(&mut to, &task_state).unwrap();
    /// assert_eq!(to, Some("c=5".into()));
    /// StringModification::RemoveQueryParamsMatching(Box::new(StringMatcher::Is("c".into()))).apply(&mut to, &task_state).unwrap();
    /// assert_eq!(to, None);
    /// ```
    RemoveQueryParamsMatching(Box<StringMatcher>),
    /// The same operation [`Action::AllowQueryParamsMatching`] does to a [`UrlPart::Query`].
    /// # Errors
    #[doc = edoc!(stringisnone(StringModification), checkerr(StringMatcher, 3))]
    /// # Examples
    /// ```
    /// use url_cleaner_engine::types::*;
    /// url_cleaner_engine::task_state_view!(task_state);
    ///
    /// let mut to = Some("a=2&b=3&%61=4&c=5".into());
    ///
    /// StringModification::AllowQueryParamsMatching(Box::new(StringMatcher::Is("a".into()))).apply(&mut to, &task_state).unwrap();
    /// assert_eq!(to, Some("a=2&%61=4".into()));
    /// StringModification::AllowQueryParamsMatching(Box::new(StringMatcher::Is("b".into()))).apply(&mut to, &task_state).unwrap();
    /// assert_eq!(to, None);
    /// ```
    AllowQueryParamsMatching(Box<StringMatcher>),
    /// The same operation [`Action::RemoveQueryParamsInSetOrStartingWithAnyInList`] does to a [`UrlPart::Query`].
    /// # Errors
    #[doc = edoc!(notfound(Set, StringModification))]
    ///
    /// If the list isn't found, returns the error [`StringModificationError::ListNotFound`].
    RemoveQueryParamsInSetOrStartingWithAnyInList {
        /// The name of the [`Set`] in [`Params::sets`] to use.
        set: String,
        /// The name of the list in [`Params::lists`] to use.
        list: String
    },



    /// Gets a [`Self`] from [`TaskStateView::commons`]'s [`Commons::string_modifications`] and applies it.
    /// # Errors
    #[doc = edoc!(ageterr(StringSource, CommonCall::name), agetnone(StringSource, StringModification, CommonCall::name), commonnotfound(Self, StringModification), callerr(CommonCallArgsSource::build), applyerr(Self))]
    Common(CommonCall),
    /// Gets a [`Self`] from [`TaskStateView::common_args`]'s [`CommonCallArgs::string_modifications`] and applies it.
    /// # Errors
    /// If [`TaskStateView::common_args`] is [`None`], returns the error [`StringModificationError::NotInCommonContext`].
    ///
    #[doc = edoc!(commoncallargnotfound(Self, StringModification), applyerr(Self))]
    CommonCallArg(StringSource),
    /// Calls the contained function.
    ///
    /// Because this uses function pointers, this plays weirdly with [`PartialEq`]/[`Eq`].
    /// # Errors
    #[doc = edoc!(callerr(Self::Custom::0))]
    #[cfg(feature = "custom")]
    #[suitable(never)]
    #[serde(skip)]
    Custom(fn(&mut Option<Cow<'_, str>>, &TaskStateView) -> Result<(), StringModificationError>)
}

string_or_struct_magic!(StringModification);

/// The error returned when trying to deserialize a [`StringModification`] variant with fields that aren't all defaultable.
#[derive(Debug, Error)]
#[error("Tried deserializing undefaultable or unknown StringModification variant {0}.")]
pub struct NonDefaultableStringModificationVariant(pub String);

impl From<&str> for NonDefaultableStringModificationVariant {
    fn from(value: &str) -> Self {
        value.to_string().into()
    }
}

impl From<String> for NonDefaultableStringModificationVariant {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl FromStr for StringModification {
    type Err = NonDefaultableStringModificationVariant;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            #[cfg(feature = "base64")] "Base64Decode" => StringModification::Base64Decode(Default::default()),
            #[cfg(feature = "base64")] "Base64Encode" => StringModification::Base64Encode(Default::default()),
            "PercentEncode"            => StringModification::PercentEncode(Default::default()),
            "PercentDecode"            => StringModification::PercentDecode,
            "LossyPercentDecode"       => StringModification::LossyPercentDecode,
            "None"                     => StringModification::None,
            "Lowercase"                => StringModification::Lowercase,
            "Uppercase"                => StringModification::Uppercase,
            "GetJsStringLiteralPrefix" => StringModification::GetJsStringLiteralPrefix,
            "UnescapeHtmlText"         => StringModification::UnescapeHtmlText,
            _                          => return Err(s.into())
        })
    }
}

/// The enum of errors [`StringModification::apply`] can return.
#[derive(Debug, Error)]
pub enum StringModificationError {
    /// Returned when a [`StringModification::Error`] is used.
    #[error("Explicit error: {0}")]
    ExplicitError(String),
    /// Returned when both [`StringModification`]s in a [`StringModification::TryElse`] return errors.
    #[error("Both StringModifications in a StringModification::TryElse returned errors.")]
    TryElseError {
        /// The error returned by [`StringModification::TryElse::try`].
        try_error: Box<Self>,
        /// The error returned by [`StringModification::TryElse::else`].
        else_error: Box<Self>
    },
    /// Returned when all [`StringModification`]s in a [`StringModification::FirstNotError`] error.
    #[error("All StringModifications in a StringModification::FirstNotError errored.")]
    FirstNotErrorErrors(Vec<Self>),

    /// Returned when a [`StringSourceError`] is encountered.
    #[error(transparent)]
    StringSourceError(#[from] Box<StringSourceError>),
    /// Returned when a [`StringSource`] returns [`None`] where it has to return [`Some`].
    #[error("A StringSource returned None where it had to return Some.")]
    StringSourceIsNone,
    /// Returned when a [`StringMatcherError`] is encountered.
    #[error(transparent)]
    StringMatcherError(#[from] Box<StringMatcherError>),
    /// Returned when a [`StringLocationError`] is encountered.
    #[error(transparent)]
    StringLocationError(#[from] StringLocationError),

    /// Returned when a [`serde_json::Error`] is encountered.
    #[error(transparent)]
    SerdeJsonError(#[from] serde_json::Error),
    /// Returned when a JSON value isn't found.
    #[error("The requested JSON value was not found.")]
    JsonValueNotFound,
    /// Returned when a JSON pointee isn't a string.
    #[error("The requested JSON pointee was not a string.")]
    JsonPointeeIsNotAString,

    /// Returned when a slice is either not on UTF-8 boundaries or out of bounds.
    #[error("The requested slice was either not on a UTF-8 boundaries or out of bounds.")]
    InvalidSlice,
    /// Returned when an index is either not on a UTF-8 boundary or out of bounds.
    #[error("The requested index was either not on a UTF-8 boundary or out of bounds.")]
    InvalidIndex,
    /// Returned when a segment isn't found.
    #[error("The requested segment wasn't found.")]
    SegmentNotFound,
    /// Returned when a segment range isn't found.
    #[error("The requested segment range wasn't found.")]
    SegmentRangeNotFound,

    /// Returned when a StringModification set a string to None when it had to keep/set it to Some.
    #[error("A StringModification set a string to None when it had to keep/set it to Some.")]
    StringModificationSetStringToNone,

    /// Returned when the string being modified doesn't start with the specified prefix.
    #[error("The string being modified didn't start with the provided prefix. Maybe try `StringModification::StripMaybePrefix`?")]
    PrefixNotFound,
    /// Returned when the string being modified doesn't end with the specified suffix.
    #[error("The string being modified didn't end with the provided suffix. Maybe try `StringModification::StripMaybeSuffix`?")]
    SuffixNotFound,

    /// Returned when a [`std::str::Utf8Error`] is encountered.
    #[error(transparent)]
    Utf8Error(#[from] std::str::Utf8Error),
    /// Returned when a [`std::string::FromUtf8Error`] is encountered.
    #[error(transparent)]
    FromUtf8Error(#[from] std::string::FromUtf8Error),

    /// Returned when the [`StringModification::KeepBetween::start`] isn't found in the string.
    #[error("The StringModification::KeepBetween::start isn't found in the string.")]
    KeepBetweenStartNotFound,
    /// Returned when the [`StringModification::KeepBetween::end`] isn't found in the string after the [`StringModification::KeepBetween::start`].
    #[error("The StringModification::KeepBetween::end isn't found in the string after the StringModification::KeepBetween::start.")]
    KeepBetweenEndNotFound,

    /// Returned when a [`parse::js::StringLiteralPrefixError`] is encountered.
    #[error(transparent)]
    JsStringLiteralPrefixError(#[from] parse::js::StringLiteralPrefixError),
    /// Returned when a [`parse::html::UnescapeTextError`] is encountered.
    #[error(transparent)]
    HtmlUnescapeTextError(#[from] parse::html::UnescapeTextError),
    /// Returned when a [`parse::html::GAVError`] is encountered.
    #[error(transparent)]
    HtmlGetAttributeValueError(#[from] parse::html::GAVError),
    /// Returned when the requested HTML attribute isn't found.
    #[error("The requested HTML attribute wasn't found.")]
    HtmlAttributeNotFound,
    /// Returned when the requested HTML attribute doesn't have a value.
    #[error("The requested HTML attribute doesn't have a value.")]
    HtmlAttributeHasNoValue,

    /// Returned when a substring isn't found in the string.
    #[error("The substring wasn't found in the string.")]
    SubstringNotFound,
    /// Returned when the string to modify is [`None`] where it has to be [`Some`].
    #[error("The string to modify was None where it had to be Some")]
    StringIsNone,
    /// Returned when a [`Set`] with the specified name isn't found.
    #[error("A Set with the specified name wasn't found.")]
    SetNotFound,
    /// Returned when a list with the specified name isn't found.
    #[error("A list with the specified name wasn't found.")]
    ListNotFound,

    /// Returned when a [`::regex::Error`] is encountered.
    #[cfg(feature = "regex")]
    #[error(transparent)]
    RegexError(#[from] ::regex::Error),
    /// Returned when a [`Regex`] doesn't find any matches in the string.
    #[cfg(feature = "regex")]
    #[error("The regex didn't find any matches in the string.")]
    RegexMatchNotFound,
    /// Returned when a [`::base64::DecodeError`] is encountered.
    #[cfg(feature = "base64")]
    #[error(transparent)]
    Base64DecodeError(#[from] ::base64::DecodeError),

    /// Returned when a [`CommonCallArgsError`] is encountered.
    #[error(transparent)]
    CommonCallArgsError(#[from] CommonCallArgsError),
    /// Returned when a [`StringModification`] with the specified name isn't found in the [`Commons::string_modifications`].
    #[error("A StringModification with the specified name wasn't found in the Commons::string_modifications.")]
    CommonStringModificationNotFound,
    /// Returned when trying to use [`StringModification::CommonCallArg`] outside of a common context.
    #[error("Tried to use StringModification::CommonCallArg outside of a common context.")]
    NotInCommonContext,
    /// Returned when the [`StringModification`] requested from a [`StringModification::CommonCallArg`] isn't found.
    #[error("The StringModification requested from a StringModification::CommonCallArg wasn't found.")]
    CommonCallArgStringModificationNotFound,

    /// An arbitrary [`std::error::Error`] for use with [`StringModification::Custom`].
    #[cfg(feature = "custom")]
    #[error(transparent)]
    Custom(Box<dyn std::error::Error + Send>)
}

impl From<StringSourceError> for StringModificationError {
    fn from(value: StringSourceError) -> Self {
        Self::StringSourceError(Box::new(value))
    }
}

impl From<StringMatcherError> for StringModificationError {
    fn from(value: StringMatcherError) -> Self {
        Self::StringMatcherError(Box::new(value))
    }
}

impl StringModification {
    /// Modified a string.
    /// # Errors
    /// See each variant of [`Self`] for when each variant returns an error.
    #[allow(clippy::missing_panics_doc, reason = "Shouldn't be possible.")]
    pub fn apply(&self, to: &mut Option<Cow<'_, str>>, task_state: &TaskStateView) -> Result<(), StringModificationError> {
        debug!(StringModification::apply, self, to);
        match self {
            Self::None => {},
            Self::Error(msg) => Err(StringModificationError::ExplicitError(msg.clone()))?,
            Self::Debug(modification) => {
                let to_before_mapper=to.clone();
                let modification_result=modification.apply(to, task_state);
                eprintln!("=== StringModification::Debug ===\nModification: {modification:?}\ntask_state: {task_state:?}\nString before mapper: {to_before_mapper:?}\nModification return value: {modification_result:?}\nString after mapper: {to:?}");
                modification_result?;
            },
            Self::IgnoreError(modification) => {let _=modification.apply(to, task_state);},
            Self::RevertOnError(modification) => {
                let old_to = to.clone();
                if let Err(e) = modification.apply(to, task_state) {
                    *to = old_to;
                    Err(e)?
                }
            },
            Self::TryElse{r#try, r#else} => r#try.apply(to, task_state).or_else(|try_error| r#else.apply(to, task_state).map_err(|else_error| StringModificationError::TryElseError {try_error: Box::new(try_error), else_error: Box::new(else_error)}))?,
            Self::All(modifications) => {
                for modification in modifications {
                    modification.apply(to, task_state)?;
                }
            },
            Self::FirstNotError(modifications) => {
                let mut errors = Vec::new();
                for modification in modifications {
                    match modification.apply(to, task_state) {
                        Ok(()) => return Ok(()),
                        Err(e) => errors.push(e)
                    }
                }
                Err(StringModificationError::FirstNotErrorErrors(errors))?
            },
            Self::IfSome(modification) => if to.is_some() {modification.apply(to, task_state)?;}
            Self::IfMatches {matcher, then, r#else} => if matcher.check(to.as_deref(), task_state)? {
                then.apply(to, task_state)?;
            } else if let Some(r#else) = r#else {
                r#else.apply(to, task_state)?
            },
            Self::IfContains {value, at, then, r#else} => if at.check(to.as_deref().ok_or(StringModificationError::StringIsNone)?, &value.get(task_state)?.ok_or(StringModificationError::StringSourceIsNone)?)? {
                then.apply(to, task_state)?;
            } else if let Some(r#else) = r#else {
                r#else.apply(to, task_state)?;
            },
            Self::IfContainsAny {values, at, then, r#else} => {
                for value in values {
                    if at.check(to.as_deref().ok_or(StringModificationError::StringIsNone)?, &value.get(task_state)?.ok_or(StringModificationError::StringSourceIsNone)?)? {
                        return then.apply(to, task_state);
                    }
                }
                if let Some(r#else) = r#else {
                    r#else.apply(to, task_state)?;
                }
            },
            Self::Map {value, map} => if let Some(x) = map.get(value.get(task_state)?) {x.apply(to, task_state)?;},



            Self::Set(value)     => *to = value.get(task_state)?.map(|x| Cow::Owned(x.into_owned())),
            Self::Append(value)  => to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut().push_str(get_str!(value, task_state, StringModificationError)),
            Self::Prepend(value) => to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut().insert_str(0, get_str!(value, task_state, StringModificationError)),
            Self::Insert{index, value} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                let index = neg_index(*index, to.len()).ok_or(StringModificationError::InvalidIndex)?;
                if to.is_char_boundary(index) {
                    to.insert_str(index, get_str!(value, task_state, StringModificationError));
                } else {
                    Err(StringModificationError::InvalidIndex)?;
                }
            },
            Self::Lowercase => *to = Some(Cow::Owned(to.as_ref().ok_or(StringModificationError::StringIsNone)?.to_lowercase())),
            Self::Uppercase => *to = Some(Cow::Owned(to.as_ref().ok_or(StringModificationError::StringIsNone)?.to_uppercase())),



            Self::StripPrefix(prefix) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let prefix = get_str!(prefix, task_state, StringModificationError);
                match to {
                    Cow::Owned(inner) => if inner.starts_with(prefix) {inner.drain(..prefix.len());} else {Err(StringModificationError::PrefixNotFound)?;},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(inner.strip_prefix(prefix).ok_or(StringModificationError::PrefixNotFound)?)
                }
            },
            Self::StripMaybePrefix(prefix) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let prefix = get_str!(prefix, task_state, StringModificationError);
                match to {
                    Cow::Owned(inner) => if inner.starts_with(prefix) {inner.drain(..prefix.len());},
                    Cow::Borrowed(inner) => if let Some(x) = inner.strip_prefix(prefix) {*to = Cow::Borrowed(x);}
                }
            },
            Self::StripSuffix(suffix) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let suffix = get_str!(suffix, task_state, StringModificationError);
                #[expect(clippy::arithmetic_side_effects, reason = "`suffix.len()>=to.len()` is guaranteed by `to.ends_with(suffix)`.")]
                match to {
                    Cow::Owned(inner) => if inner.ends_with(suffix) {inner.truncate(inner.len()-suffix.len())} else {Err(StringModificationError::SuffixNotFound)?;},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(inner.strip_suffix(suffix).ok_or(StringModificationError::SuffixNotFound)?)
                }
            },
            Self::StripMaybeSuffix(suffix) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let suffix = get_str!(suffix, task_state, StringModificationError);
                #[expect(clippy::arithmetic_side_effects, reason = "`suffix.len()>=to.len()` is guaranteed by `to.ends_with(suffix)`.")]
                match to {
                    Cow::Owned(inner) => if inner.ends_with(suffix) {inner.truncate(inner.len() - suffix.len());},
                    Cow::Borrowed(inner) => if let Some(x) = inner.strip_suffix(suffix) {*to = Cow::Borrowed(x);}
                }
            },
            Self::RemoveChar(index) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                if to.is_char_boundary(neg_index(*index, to.len()).ok_or(StringModificationError::InvalidIndex)?) {
                    to.remove(neg_index(*index, to.len()).ok_or(StringModificationError::InvalidIndex)?);
                } else {
                    Err(StringModificationError::InvalidIndex)?;
                }
            },



            Self::KeepBefore(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                match to {
                    Cow::Owned(inner) => {inner.drain(inner.find(s).ok_or(StringModificationError::SubstringNotFound)?..);},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[..inner.find(s).ok_or(StringModificationError::SubstringNotFound)?])
                }
            },
            Self::StripBefore(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                match to {
                    Cow::Owned(inner) => {inner.drain(..inner.find(s).ok_or(StringModificationError::SubstringNotFound)?);},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[inner.find(s).ok_or(StringModificationError::SubstringNotFound)?..])
                }
            },
            Self::KeepBetween {start, end} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = match to {
                    Cow::Borrowed(inner) => Cow::Borrowed(inner
                        .split_once(get_str!(start, task_state, StringSourceError)).ok_or(StringModificationError::KeepBetweenStartNotFound)?.1
                        .split_once(get_str!(end  , task_state, StringSourceError)).ok_or(StringModificationError::KeepBetweenEndNotFound  )?.0
                    ),
                    Cow::Owned(inner) => Cow::Owned(inner
                        .split_once(get_str!(start, task_state, StringSourceError)).ok_or(StringModificationError::KeepBetweenStartNotFound)?.1
                        .split_once(get_str!(end  , task_state, StringSourceError)).ok_or(StringModificationError::KeepBetweenEndNotFound  )?.0
                        .to_string()
                    )
                }
            },
            Self::StripAfter(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                #[allow(clippy::arithmetic_side_effects, reason = "Can't happen.")]
                match to {
                    Cow::Owned(inner) => {inner.drain((inner.find(s).ok_or(StringModificationError::SubstringNotFound)? + s.len())..);},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[..inner.find(s).ok_or(StringModificationError::SubstringNotFound)? + s.len()])
                }
            },
            Self::KeepAfter(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                #[allow(clippy::arithmetic_side_effects, reason = "Can't happen.")]
                match to {
                    Cow::Owned(inner) => {inner.drain(..(inner.find(s).ok_or(StringModificationError::SubstringNotFound)? + s.len()));},
                    Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[inner.find(s).ok_or(StringModificationError::SubstringNotFound)? + s.len()..])
                }
            },



            Self::KeepMaybeBefore(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                if let Some(i) = to.find(s) {
                    match to {
                        Cow::Owned(inner) => {inner.drain(i..);},
                        Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[..i])
                    }
                }
            },
            Self::StripMaybeBefore(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                if let Some(i) = to.find(s) {
                    match to {
                        Cow::Owned(inner) => {inner.drain(..i);},
                        Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[i..])
                    }
                }
            },
            Self::KeepMaybeBetween {start, end} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = match to {
                    Cow::Borrowed(inner) => {
                        let mut temp = &**inner;
                        temp = temp.split_once(get_str!(start, task_state, StringSourceError)).map_or(temp, |(_, x)| x);
                        temp = temp.split_once(get_str!(end  , task_state, StringSourceError)).map_or(temp, |(x, _)| x);
                        Cow::Borrowed(temp)
                    },
                    Cow::Owned(inner) => {
                        let mut temp = &**inner;
                        temp = temp.split_once(get_str!(start, task_state, StringSourceError)).map_or(temp, |(_, x)| x);
                        temp = temp.split_once(get_str!(end  , task_state, StringSourceError)).map_or(temp, |(x, _)| x);
                        Cow::Owned(temp.to_string())
                    }
                }
            },
            Self::StripMaybeAfter(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                if let Some(i) = to.find(s) {
                    #[allow(clippy::arithmetic_side_effects, reason = "Can't happen.")]
                    match to {
                        Cow::Owned(inner) => {inner.drain((i + s.len())..);},
                        Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[..i + s.len()])
                    }
                }
            },
            Self::KeepMaybeAfter(s) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                let s = get_str!(s, task_state, StringModificationError);
                if let Some(i) = to.find(s) {
                    #[allow(clippy::arithmetic_side_effects, reason = "Can't happen.")]
                    match to {
                        Cow::Owned(inner) => {inner.drain(..(i + s.len()));},
                        Cow::Borrowed(inner) => *to = Cow::Borrowed(&inner[i + s.len()..])
                    }
                }
            },



            Self::Replacen{find, replace, count}     => *to=Some(Cow::Owned(to.as_ref().ok_or(StringModificationError::StringIsNone)?.replacen(get_str!(find, task_state, StringModificationError), get_str!(replace, task_state, StringModificationError), *count))),
            Self::ReplaceAll{find, replace}             => *to=Some(Cow::Owned(to.as_ref().ok_or(StringModificationError::StringIsNone)?.replace (get_str!(find, task_state, StringModificationError), get_str!(replace, task_state, StringModificationError)))),



            Self::ReplaceRange{start, end, replace}  => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                let range=neg_range(*start, *end, to.len()).ok_or(StringModificationError::InvalidSlice)?;
                if to.get(range).is_some() {
                    to.replace_range(range, get_str!(replace, task_state, StringModificationError));
                } else {
                    Err(StringModificationError::InvalidSlice)?;
                }
            },
            Self::KeepRange{start, end} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                match to {
                    Cow::Owned(inner) => *inner = inner.get(neg_range(*start, *end, inner.len()).ok_or(StringModificationError::InvalidSlice)?).ok_or(StringModificationError::InvalidSlice)?.to_string(),
                    Cow::Borrowed(inner) => *inner = inner.get(neg_range(*start, *end, inner.len()).ok_or(StringModificationError::InvalidSlice)?).ok_or(StringModificationError::InvalidSlice)?
                }
            },



            Self::SetSegment {split, index, value, join} => {
                let split = get_str!(split, task_state, StringModificationError);
                let join = match join {
                    Some(join) => get_str!(join, task_state, StringModificationError),
                    None => split
                };
                let mut segments = to.as_ref().ok_or(StringModificationError::StringIsNone)?.split(split).map(Cow::Borrowed).collect::<Vec<_>>();
                let fixed_index = neg_index(*index, segments.len()).ok_or(StringModificationError::SegmentNotFound)?;
                match value.get(task_state)? {
                    Some(value) => *segments.get_mut(fixed_index).expect("StringModification::SetSegment to be implemented correctly") = value,
                    None => {segments.remove(fixed_index);}
                }
                *to = Some(Cow::Owned(segments.join(join)));
            },
            Self::InsertSegment {split, index, value, join} => {
                let split = get_str!(split, task_state, StringModificationError);
                let join = match join {
                    Some(join) => get_str!(join, task_state, StringModificationError),
                    None => split
                };
                let mut segments = to.as_ref().ok_or(StringModificationError::StringIsNone)?.split(split).map(Cow::Borrowed).collect::<Vec<_>>();
                let fixed_index = neg_range_boundary(*index, segments.len()).ok_or(StringModificationError::SegmentNotFound)?;
                if let Some(value) = value.get(task_state)? {
                    segments.insert(fixed_index, value);
                }
                *to = Some(Cow::Owned(segments.join(join)));
            },
            Self::KeepSegment {split, index} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = match to {
                    Cow::Owned(inner) => Cow::Owned(neg_nth(inner.split(get_str!(split, task_state, StringModificationError)), *index).ok_or(StringModificationError::SegmentNotFound)?.to_string()),
                    Cow::Borrowed(inner) => Cow::Borrowed(neg_nth(inner.split(get_str!(split, task_state, StringModificationError)), *index).ok_or(StringModificationError::SegmentNotFound)?),
                }
            },
            Self::KeepSegmentRange {split, start, end, join} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                let split = get_str!(split, task_state, StringModificationError);
                let join = match join {
                    Some(join) => get_str!(join, task_state, StringModificationError),
                    None => split
                };
                *to = neg_vec_keep(to.split(split), *start, *end).ok_or(StringModificationError::SegmentRangeNotFound)?.join(join);
            },
            Self::KeepSegments {split, indices, join} => {
                let temp = to.as_ref().ok_or(StringModificationError::StringIsNone)?;
                let split = get_str!(split, task_state, StringModificationError);
                let join = match join {
                    Some(join) => get_str!(join, task_state, StringModificationError),
                    None => split
                };
                let segments = temp.split(split).collect::<Vec<_>>();
                let segment_count = segments.len();
                let mut ret = String::with_capacity(temp.len());
                let mut first = true;
                for (i, segment) in segments.into_iter().enumerate() {
                    for index in indices.iter().copied() {
                        if neg_index(index, segment_count).ok_or(StringModificationError::SegmentNotFound)? == i {
                            if !first {
                                ret.push_str(join);
                            }
                            first = false;
                            ret.push_str(segment);
                        }
                    }
                }
                *to = Some(Cow::Owned(ret));
            },
            Self::KeepModifiedSegments {split, indices, modification, join} => {
                let temp = to.as_ref().ok_or(StringModificationError::StringIsNone)?;
                let split = get_str!(split, task_state, StringModificationError);
                let join = match join {
                    Some(join) => get_str!(join, task_state, StringModificationError),
                    None => split
                };
                let segments = temp.split(split).collect::<Vec<_>>();
                let segment_count = segments.len();
                let mut ret = String::with_capacity(temp.len());
                let mut first = true;
                for (i, segment) in segments.into_iter().enumerate() {
                    for index in indices.iter().copied() {
                        if neg_index(index, segment_count).ok_or(StringModificationError::SegmentNotFound)? == i {
                            if !first {
                                ret.push_str(join);
                            }
                            first = false;
                            let mut temp = Some(Cow::Borrowed(segment));
                            modification.apply(&mut temp, task_state)?;
                            ret.push_str(&temp.ok_or(StringModificationError::StringModificationSetStringToNone)?);
                        }
                    }
                }
                *to = Some(Cow::Owned(ret));
            }


            Self::GetJsStringLiteralPrefix => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = Cow::Owned(parse::js::string_literal_prefix(to)?);
            },
            Self::UnescapeHtmlText => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = Cow::Owned(parse::html::unescape_text(to)?);
            },
            Self::GetHtmlAttribute(name) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?;
                *to = Cow::Owned(parse::html::get_attribute_value(to, get_str!(name, task_state, StringModificationError))?.ok_or(StringModificationError::HtmlAttributeNotFound)?.ok_or(StringModificationError::HtmlAttributeHasNoValue)?);
            },



            #[cfg(feature = "regex")]
            Self::RegexFind(regex) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = regex.get()?.find(to).ok_or(StringModificationError::RegexMatchNotFound)?.as_str().to_string();
            },
            #[cfg(feature = "regex")]
            Self::RegexSubstitute {regex, replace} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                let replace = get_str!(replace, task_state, StringModificationError);
                let mut temp = "".to_string();
                regex.get()?.captures(to).ok_or(StringModificationError::RegexMatchNotFound)?.expand(replace, &mut temp);
                *to = temp;
            },
            #[cfg(feature = "regex")]
            Self::JoinAllRegexSubstitutions {regex, replace, join} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                let replace = get_str!(replace, task_state, StringModificationError);
                let join = get_str!(join, task_state, StringModificationError);
                let regex = regex.get()?;
                let mut temp = "".to_string();
                if join.is_empty() {
                    for captures in regex.captures_iter(to) {
                        captures.expand(replace, &mut temp);
                    }
                } else {
                    let mut iter = regex.captures_iter(to).peekable();
                    while let Some(captures) = iter.next() {
                        captures.expand(replace, &mut temp);
                        if iter.peek().is_some() {temp.push_str(join);}
                    }
                }
                *to = temp;
            },
            #[cfg(feature = "regex")]
            Self::RegexReplaceOne {regex,replace} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = regex.get()?.replace(to,get_str!(replace, task_state, StringModificationError)).into_owned();
            },
            #[cfg(feature = "regex")]
            Self::RegexReplaceAll {regex,replace} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = regex.get()?.replace_all(to,get_str!(replace, task_state, StringModificationError)).into_owned();
            },
            #[cfg(feature = "regex")]
            Self::RegexReplacen {regex, n, replace} => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = regex.get()?.replacen(to, *n, get_str!(replace, task_state, StringModificationError)).into_owned();
            },



            Self::JsonPointer(pointer) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                match serde_json::from_str::<serde_json::Value>(to)?.pointer_mut(get_str!(pointer, task_state, StringModificationError)).ok_or(StringModificationError::JsonValueNotFound)?.take() {
                    serde_json::Value::String(s) => *to = s,
                    _ => Err(StringModificationError::JsonPointeeIsNotAString)?
                }
            },



            Self::PercentEncode(alphabet) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = utf8_percent_encode(to, alphabet.get()).to_string();
            },
            Self::PercentDecode => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = percent_decode_str(to).decode_utf8()?.into_owned();
            },
            Self::LossyPercentDecode => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = percent_decode_str(to).decode_utf8_lossy().into_owned();
            },



            #[cfg(feature = "base64")]
            Self::Base64Encode(config) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = config.build().encode(to.as_bytes());
            },
            #[cfg(feature = "base64")]
            Self::Base64Decode(config) => {
                let to = to.as_mut().ok_or(StringModificationError::StringIsNone)?.to_mut();
                *to = String::from_utf8(config.build().decode(to.as_bytes())?)?;
            },



            Self::RemoveQueryParamsMatching(matcher) => if let Some(inner) = to {
                let mut new = String::with_capacity(inner.len());
                for param in inner.split('&') {
                    if !matcher.check(Some(&pds(param.split('=').next().expect("The first segment to always exist")).decode_utf8_lossy()), task_state)? {
                        if !new.is_empty() {new.push('&');}
                        new.push_str(param);
                    }
                }
                if new.len() != inner.len() {
                    *to = Some(Cow::<str>::Owned(new)).filter(|new| !new.is_empty());
                }
            },
            Self::AllowQueryParamsMatching(matcher) => if let Some(inner) = to {
                let mut new = String::with_capacity(inner.len());
                for param in inner.split('&') {
                    if matcher.check(Some(&pds(param.split('=').next().expect("The first segment to always exist")).decode_utf8_lossy()), task_state)? {
                        if !new.is_empty() {new.push('&');}
                        new.push_str(param);
                    }
                }
                if new.len() != inner.len() {
                    *to = Some(Cow::<str>::Owned(new)).filter(|new| !new.is_empty());
                }
            },
            Self::RemoveQueryParamsInSetOrStartingWithAnyInList {set, list} => if let Some(inner) = to {
                let mut new = String::with_capacity(inner.len());
                let set = task_state.params.sets.get(set).ok_or(StringModificationError::SetNotFound)?;
                let list = task_state.params.lists.get(list).ok_or(StringModificationError::ListNotFound)?;
                for param in inner.split('&') {
                    let name = pds(param.split('=').next().expect("The first segment to always exist.")).decode_utf8_lossy();
                    if !(set.contains(Some(&*name)) || list.iter().any(|x| name.starts_with(x))) {
                        if !new.is_empty() {new.push('&');}
                        new.push_str(param);
                    }
                }
                if new.len() != inner.len() {
                    *to = Some(Cow::<str>::Owned(new)).filter(|x| !x.is_empty());
                }
            },



            Self::Common(common_call) => {
                task_state.commons.string_modifications.get(get_str!(common_call.name, task_state, StringModificationError)).ok_or(StringModificationError::CommonStringModificationNotFound)?.apply(
                    to,
                    &TaskStateView {
                        common_args: Some(&common_call.args.build(task_state)?),
                        url        : task_state.url,
                        scratchpad : task_state.scratchpad,
                        context    : task_state.context,
                        job_context: task_state.job_context,
                        params     : task_state.params,
                        commons    : task_state.commons,
                        #[cfg(feature = "cache")]
                        cache      : task_state.cache,
                        unthreader : task_state.unthreader
                    }
                )?;
            },
            Self::CommonCallArg(name) => task_state.common_args.ok_or(StringModificationError::NotInCommonContext)?.string_modifications.get(get_str!(name, task_state, StringModificationError)).ok_or(StringModificationError::CommonCallArgStringModificationNotFound)?.apply(to, task_state)?,
            #[cfg(feature = "custom")]
            Self::Custom(function) => function(to, task_state)?
        };
        Ok(())
    }
}