-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_modification.rs
1450 lines (1426 loc) · 75 KB
/
string_modification.rs
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
//! Provides [`StringModification`] which provides an easy API for all the ways one might want to modify a [`String`].
use std::borrow::Cow;
use std::str::FromStr;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC};
#[allow(unused_imports, reason = "Used in a doc comment.")]
#[cfg(feature = "regex")]
use ::regex::Regex;
#[cfg(feature = "base64")]
use ::base64::prelude::*;
use crate::types::*;
use crate::glue::*;
use crate::util::*;
/// Various ways to modify a [`String`].
///
/// [`isize`] is used to allow Python-style negative indexing.
#[derive(Debug, Clone,Serialize, Deserialize, PartialEq, Eq)]
#[serde(remote = "Self")]
pub enum StringModification {
/// Does nothing.
None,
/// Always returns the error [`StringModificationError::ExplicitError`].
/// # Errors
/// Always returns the error [`StringModificationError::ExplicitError`].
Error,
/// Prints debugging information about the contained [`Self`] and the details of its application to STDERR.
///
/// Intended primarily for debugging logic errors.
/// # Errors
/// If the call to [`Self::apply`] returns an error, that error is returned after the debug info is printed.
Debug(Box<Self>),
/// If `matcher` passes, apply `modification`, otherwise apply `else_modification`.
/// # Errors
/// If the call to [`StringMatcher::satisfied_by`] returns an error, that error is returned.
///
/// If either possible call to [`StringModification::apply`] returns an error, that error is returned.
IfStringMatches {
/// The [`StringMatcher`] that decides if `modification` or `else_modification` is used.
matcher: Box<StringMatcher>,
/// The [`Self`] to use if `matcher` passes.
modification: Box<Self>,
/// The [`Self`] to use if `matcher` fails.
///
/// Defaults to [`None`].
#[serde(default)]
else_modification: Option<Box<Self>>
},
/// Effectively a [`Self::IfStringMatches`] where each subsequent link is put inside the previous link's [`Self::IfStringMatches::else_modification`].
/// # Errors
/// If a call to [`StringMatcher::satisfied_by`] returns an error, that error is returned.
///
/// If a call to [`StringModification::apply`] returns an error, that error is returned.
StringMatcherChain(Vec<StringMatcherChainLink>),
/// Ignores any error the call to [`Self::apply`] may return.
IgnoreError(Box<Self>),
/// If `try` returns an error, `else` is applied.
///
/// If `try` does not return an er
/// # Errors
/// If `else` returns an error, that error is returned.
TryElse {
/// The [`Self`] to try first.
r#try: Box<Self>,
/// If `try` fails, instead return the result of this one.
r#else: Box<Self>
},
/// Applies the contained [`Self`]s in order.
/// # Errors
/// If one of the calls to [`Self::apply`] return an error, the string is left unchanged and the error is returned.
All(Vec<Self>),
/// Applies the contained [`Self`]s in order. If an error occurs, the string remains changed by the previous calls to [`Self::apply`] and the error is returned.
///
/// Technically the name is wrong as [`Self::All`] only actually applies the change after all the calls to [`Self::apply`] pass, but this is conceptually simpler.
/// # Errors
/// If one of the calls to [`Self::apply`] return an error, the string is left as whatever the previous contained mapper set it to and the error is returned.
AllNoRevert(Vec<Self>),
/// If any of the calls to [`Self::apply`] return an error, the error is ignored and subsequent [`Self`]s are still applied.
///
/// This is equivalent to wrapping every contained [`Self`] in a [`Self::IgnoreError`].
AllIgnoreError(Vec<Self>),
/// Effectively a [`Self::TryElse`] chain but less ugly.
/// # Errors
/// If all calls to [`Self::apply`] return an error, returns the last error.
FirstNotError(Vec<Self>),
/// Replaces the entire target string to the specified string.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::Set("ghi".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "ghi");
/// ```
/// # Errors
/// If the call to [`StringSource::get`] returns an error, that error is returned.
Set(StringSource),
/// Append the contained string.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::Append("ghi".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "abcdefghi");
/// ```
/// # Errors
/// If the call to [`StringSource::get`] returns an error, that error is returned.
Append(StringSource),
/// Prepend the contained string.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::Prepend("ghi".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "ghiabcdef");
/// ```
/// # Errors
/// If the call to [`StringSource::get`] returns an error, that error is returned.
Prepend(StringSource),
/// Replace all instances of `find` with `replace`.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcabc".to_string();
/// StringModification::Replace{find: "ab".into(), replace: "xy".into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "xycxyc");
/// ```
Replace {
/// The value to look for.
find: StringSource,
/// The value to replace with.
replace: StringSource
},
/// Replace the specified range with `replace`.
/// # Errors
/// If either end of the specified range is out of bounds or not on a UTF-8 character boundary, returns the error [`StringModificationError::InvalidSlice`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::ReplaceRange{start: Some( 6), end: Some( 7), replace: "123" .into()}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// assert_eq!(&x, "abcdef");
/// StringModification::ReplaceRange{start: Some( 1), end: Some( 4), replace: "ab" .into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "aabef");
/// StringModification::ReplaceRange{start: Some(-3), end: Some(-1), replace: "abcd".into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "aaabcdf");
/// StringModification::ReplaceRange{start: Some(-3), end: None , replace: "efg" .into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "aaabefg");
/// StringModification::ReplaceRange{start: Some(-8), end: None , replace: "hij" .into()}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// assert_eq!(&x, "aaabefg");
/// ```
ReplaceRange {
/// The start of the range to replace.
start: Option<isize>,
/// The end of the range to replace.
end: Option<isize>,
/// The value to replace the range with.
replace: StringSource
},
/// [`str::to_lowercase`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "ABCdef".to_string();
/// StringModification::Lowercase.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "abcdef");
/// ```
Lowercase,
/// [`str::to_uppercase`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcDEF".to_string();
/// StringModification::Uppercase.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "ABCDEF");
/// ```
Uppercase,
/// Mimics [`str::strip_prefix`] using [`str::starts_with`] and [`String::drain`]. Should be faster due to not needing an additional heap allocation.
/// # Errors
/// If the target string doesn't begin with the specified prefix, returns the error [`StringModificationError::PrefixNotFound`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::StripPrefix("abc".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "def");
/// StringModification::StripPrefix("abc".into()).apply(&mut x, &job_state.to_view()).unwrap_err();
/// assert_eq!(&x, "def");
/// ```
StripPrefix(StringSource),
/// Mimics [`str::strip_suffix`] using [`str::ends_with`] and [`String::truncate`]. Should be faster due to not needing an additional heap allocation.
/// # Errors
/// If the target string doesn't end with the specified suffix, returns the error [`StringModificationError::SuffixNotFound`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::StripSuffix("def".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "abc");
/// StringModification::StripSuffix("def".into()).apply(&mut x, &job_state.to_view()).unwrap_err();
/// assert_eq!(&x, "abc");
/// ```
StripSuffix(StringSource),
/// [`Self::StripPrefix`] but does nothing if the target string doesn't begin with the specified prefix.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::StripMaybePrefix("abc".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "def");
/// StringModification::StripMaybePrefix("abc".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "def");
/// ```
StripMaybePrefix(StringSource),
/// [`Self::StripSuffix`] but does nothing if the target string doesn't end with the specified suffix.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::StripMaybeSuffix("def".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "abc");
/// StringModification::StripMaybeSuffix("def".into()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "abc");
/// ```
StripMaybeSuffix(StringSource),
/// [`str::replacen`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "aaaaa".to_string();
/// StringModification::Replacen{find: "a" .into(), replace: "x".into(), count: 2}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "xxaaa");
/// StringModification::Replacen{find: "xa".into(), replace: "x".into(), count: 2}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "xxaa");
/// ```
Replacen {
/// The value to look for.
find: StringSource,
/// The value to replace with.
replace: StringSource,
/// The number of times to do the replacement.
count: usize
},
/// [`String::insert_str`].
/// # Errors
/// If `where` is out of bounds or not on a UTF-8 character boundary, returns the error [`StringModificationError::InvalidIndex`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abc".to_string();
/// StringModification::Insert{r#where: 0, value: "def".into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "defabc");
/// StringModification::Insert{r#where: 2, value: "ghi".into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "deghifabc");
/// StringModification::Insert{r#where: -1, value: "jhk".into()}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "deghifabjhkc");
/// ```
Insert {
/// The location to insert `value`.
r#where: isize,
/// The string to insert.
value: StringSource
},
/// [`String::remove`].
/// # Errors
/// If the specified index is out of bounds or not on a UTF-8 character boundary, returns the error [`StringModificationError::InvalidIndex`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdef".to_string();
/// StringModification::Remove( 1).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "acdef");
/// StringModification::Remove(-1).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "acde");
/// ```
Remove(isize),
/// Discards everything outside the specified range.
/// # Errors
/// If either end of the specified range is out of bounds or not on a UTF-8 character boundary, returns the error [`StringModificationError::InvalidSlice`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abcdefghi".into();
/// StringModification::KeepRange{start: Some( 1), end: Some( 8)}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "bcdefgh");
/// StringModification::KeepRange{start: None , end: Some( 6)}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "bcdefg");
/// StringModification::KeepRange{start: Some(-3), end: None }.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "efg");
/// StringModification::KeepRange{start: Some(-3), end: Some(-1)}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "ef");
/// ```
KeepRange {
/// The start of the range to keep.
start: Option<isize>,
/// The end of the range to keep.
end: Option<isize>
},
/// [`Regex::captures`] and [`::regex::Captures::expand`].
/// # Errors
/// When the call to [`Regex::captures`] returns [`None`], returns the error [`StringModificationError::RegexMatchNotFound`]
#[cfg(feature = "regex")]
RegexCaptures {
/// The regex to search with.
regex: RegexWrapper,
/// The replacement string to call [`::regex::Captures::expand`] with.
replace: StringSource
},
/// [`Regex::captures_iter`] and [`::regex::Captures::expand`].
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// # use url_cleaner::glue::*;
/// # use std::str::FromStr;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "...a2..a3....a4".to_string();
/// StringModification::JoinAllRegexCaptures {
/// regex: RegexWrapper::from_str(r"a(\d)").unwrap(),
/// replace: "A$1$1".into(),
/// join: "---".into()
/// }.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "A22---A33---A44");
/// ```
/// # Errors
/// If the call to [`RegexWrapper::get_regex`] returns an error, that error is returned,
#[cfg(feature = "regex")]
JoinAllRegexCaptures {
/// The regex to search with.
regex: RegexWrapper,
/// The replacement string to call [`::regex::Captures::expand`] with.
replace: StringSource,
/// The value to join the captures with. Does not default to anything.
join: StringSource
},
/// [`Regex::find`].
/// # Errors
/// When the call to [`Regex::find`] returns [`None`], returns the error [`StringModificationError::RegexMatchNotFound`]
#[cfg(feature = "regex")]
RegexFind(RegexWrapper),
/// [`Regex::replace`]
/// Please note that this only does one replacement. See [`Self::RegexReplaceAll`] and [`Self::RegexReplacen`] for alternatives.
#[cfg(feature = "regex")]
RegexReplace {
/// The regex to do replacement with.
regex: RegexWrapper,
/// The replacement string.
replace: StringSource
},
/// [`Regex::replace_all`]
#[cfg(feature = "regex")]
RegexReplaceAll {
/// The regex to do replacement with.
regex: RegexWrapper,
/// The replacement string.
replace: StringSource
},
/// [`Regex::replacen`]
#[cfg(feature = "regex")]
RegexReplacen {
/// The regex to do replacement with.
regex: RegexWrapper,
/// The number of replacements to do.
n: usize,
/// The replacement string.
replace: StringSource
},
/// Choose which string modification to apply based on of a flag is set.
IfFlag {
/// The flag to check the setness of.
flag: StringSource,
/// The string modification to apply if the flag is set.
then: Box<Self>,
/// The string modification to apply if the flag is not set.
r#else: Box<Self>
},
/// Uses [`percent_encoding::utf8_percent_encode`] to percent encode all bytes that are not alphanumeric ASCII.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "a/b/c".to_string();
/// StringModification::UrlEncode.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a%2Fb%2Fc");
/// ```
UrlEncode,
/// [`percent_encoding::percent_decode_str`]
/// # Errors
/// If the call to [`percent_encoding::percent_decode_str`] errors, returns that error.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "a%2fb%2Fc".to_string();
/// StringModification::UrlDecode.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a/b/c");
/// ```
UrlDecode,
/// Encode the string using [`::base64::prelude::BASE64_STANDARD`].
#[cfg(feature = "base64")]
Base64Encode(#[serde(default)] Base64Config),
/// Decode the string using [`::base64::prelude::BASE64_STANDARD`].
/// # Errors
/// If the call to [`::base64::engine::Engine::decode`] returns an error, that error is returned.
///
/// If the call to [`String::from_utf8`] returns an error, that error is returned.
#[cfg(feature = "base64")]
Base64Decode(#[serde(default)] Base64Config),
/// [`serde_json::Value::pointer`].
/// Does not do any string conversions. I should probably add an option for that.
/// # Errors
/// If the pointer doesn't point to anything, returns the error [`StringModificationError::JsonValueNotFound`].
///
/// If the pointer points to a non-string value, returns the error [`StringModificationError::JsonValueIsNotAString`].
JsonPointer(StringSource),
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abc xyz".to_string();
/// StringModification::ModifyNthSegment {
/// split: " ".into(),
/// n: 1,
/// modification: Box::new(StringModification::Set("abc".into()))
/// }.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "abc abc");
/// ```
/// # Errors
/// If the segment is not found, returns the error [`StringModificationError::SegmentNotFound`].
///
/// If the modification returns an error, that error is returned.
ModifyNthSegment {
/// The value to split the siring by.
split: StringSource,
/// The index of the segment to modify.
n: isize,
/// The modification to apply.
modification: Box<Self>
},
/// Splits the provided string by `split` and keeps only the `n`th segment.
/// # Errors
/// If the `n`th segment is not found, returns the error [`StringModificationError::SegmentNotFound`].
KeepNthSegment {
/// The value to split the string by.
split: StringSource,
/// The index of the segment to keep.
n: isize
},
/// Splits the provided string by `split` and keeps only the segments in the specified range.
/// # Errors
/// If the segment range is not found, returns the error [`StringModificationError::SegmentRangeNotFound`].
KeepSegmentRange {
/// The value to split the string by.
split: StringSource,
/// The start of the range of segments to keep.
start: Option<isize>,
/// The end of the range of segments to keep.
end: Option<isize>
},
/// Splits the provided string by `split`, replaces the `n`th segment with `value` or removes the segment if `value` is `None`, then joins the segments back together.
/// # Errors
/// If `n` is not in the range of of segments, returns the error [`StringModificationError::SegmentNotFound`].
///
/// If either call to [`StringSource::get`] returns an error, that error is returned.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "a.b.c.d.e.f".to_string();
/// StringModification::SetNthSegment{split: ".".into(), n: 1, value: Some( "1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.c.d.e.f");
/// StringModification::SetNthSegment{split: ".".into(), n: -1, value: Some("-1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.c.d.e.-1");
/// StringModification::SetNthSegment{split: ".".into(), n: -2, value: None}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.c.d.-1");
/// StringModification::SetNthSegment{split: ".".into(), n: 5, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::SetNthSegment{split: ".".into(), n: -6, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::SetNthSegment{split: ".".into(), n: -5, value: Some("-5".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "-5.1.c.d.-1");
/// ```
SetNthSegment {
/// The value to split the string by.
split: StringSource,
/// The index of the segment to modify.
n: isize,
/// The value to set. If `None` then the segment is removed.
value: Option<StringSource>
},
/// Finds the `n`th segment matching `matcher` and sets it to `value`.
/// # Errors
/// If `n` is not in the range of segments, returns the error [`StringModificationError::SegmentNotFound`].
///
/// If the call to [`StringMatcher::satisfied_by`] returns an error, that error is returned.
///
/// If either call to [`StringSource::get`] returns an error, that error is returned.
SetNthMatchingSegment {
/// The value to split the siring by.
split: StringSource,
/// The index of the segments to modify.
n: isize,
/// The [`StringMatcher`] to test each segment with.
matcher: Box<StringMatcher>,
/// The value to set. If `None` then the segment is removed.
value: Option<StringSource>
},
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let modification = StringModification::SetAroundNthMatchingSegment {
/// split: " ".into(),
/// n: 0,
/// matcher: Box::new(StringMatcher::Equals("b".into())),
/// shift: 1,
/// value: None
/// };
///
/// let mut x = "a b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "a b");
///
/// let mut x = "a b".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap_err();
///
///
///
/// let modification = StringModification::SetAroundNthMatchingSegment {
/// split: " ".into(),
/// n: 0,
/// matcher: Box::new(StringMatcher::Equals("b".into())),
/// shift: -1,
/// value: None
/// };
///
/// let mut x = "a b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "b c");
///
/// let mut x = "b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap_err();
/// ```
SetAroundNthMatchingSegment {
/// The value to split the siring by.
split: StringSource,
/// The index of the segments to modify.
n: isize,
/// The [`StringMatcher`] to test each segment with.
matcher: Box<StringMatcher>,
/// The offset of the segment to set.
shift: isize,
/// The value to set. If `None` then the segment is removed.
value: Option<StringSource>
},
/// Splits the provided string by `split`, replaces the range of segments specified by `start` and `end` with `value`, then joins the segments back together.
/// # Errors
/// If either call to [`StringSource::get`] returns an error, that error is returned.
///
/// If there is no segment at `start` (or `0` if `start` is [`None`]), returns the error [`StringModificationError::SegmentNotFound`].
///
/// If the segment range is not found, returns the error [`StringModificationError::SegmentRangeNotFound`].
SetSegmentRange {
/// The value to split the string by.
split: StringSource,
/// The start of the range of segments to replace.
start: Option<isize>,
/// The end of the range of segments to replace.
end: Option<isize>,
/// The value to replace the segments with.
value: Option<StringSource>
},
/// Like [`Self::SetNthSegment`] except it inserts `value` before the `n`th segment instead of overwriting.
/// # Errors
/// If `n` is not in the range of of segments, returns the error [`StringModificationError::SegmentNotFound`].
///
/// Please note that trying to append a new segment at the end still errors.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "a.b.c".to_string();
/// StringModification::InsertSegmentBefore{split: ".".into(), n: 1, value: Some( "1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.b.c");
/// StringModification::InsertSegmentBefore{split: ".".into(), n: -1, value: Some("-1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.b.-1.c");
/// StringModification::InsertSegmentBefore{split: ".".into(), n: 4, value: Some( "4".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.b.-1.4.c");
/// StringModification::InsertSegmentBefore{split: ".".into(), n: 6, value: Some( "6".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.1.b.-1.4.c.6");
/// StringModification::InsertSegmentBefore{split: ".".into(), n: 8, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::InsertSegmentBefore{split: ".".into(), n: -8, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::InsertSegmentBefore{split: ".".into(), n: -7, value: Some("-7".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "-7.a.1.b.-1.4.c.6");
/// ```
InsertSegmentBefore {
/// The value to split the string by.
split: StringSource,
/// The segment index to insert before.
n: isize,
/// The value to insert.
value: Option<StringSource>
},
/// Like [`Self::SetNthSegment`] except it inserts `value` after the `n`th segment instead of overwriting.
/// # Errors
/// If `n` is not in the range of of segments, returns the error [`StringModificationError::SegmentNotFound`].
///
/// Please note that trying to append a new segment at the end still errors.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "a.b.c".to_string();
/// StringModification::InsertSegmentAfter{split: ".".into(), n: 1, value: Some( "1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.b.1.c");
/// StringModification::InsertSegmentAfter{split: ".".into(), n: -1, value: Some("-1".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.b.1.c.-1");
/// StringModification::InsertSegmentAfter{split: ".".into(), n: 4, value: Some( "4".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.b.1.c.-1.4");
/// StringModification::InsertSegmentAfter{split: ".".into(), n: 6, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::InsertSegmentAfter{split: ".".into(), n: -7, value: Some( "E".into())}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// StringModification::InsertSegmentAfter{split: ".".into(), n: -6, value: Some("-6".into())}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(&x, "a.-6.b.1.c.-1.4");
/// ```
InsertSegmentAfter {
/// The value to split the string by.
split: StringSource,
/// The segment index to insert before.
n: isize,
/// The value to insert.
value: Option<StringSource>
},
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abc def xyz".to_string();
/// StringModification::ModifySegments {
/// split: " ".into(),
/// ns: vec![1, 2],
/// modification: Box::new(StringModification::Set("a b c".into()))
/// }.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "abc a b c a b c");
/// ```
/// # Errors
/// If a segment is not found, returns the error [`StringModificationError::SegmentNotFound`].
///
/// If the modification returns an error, that error is returned.
ModifySegments {
/// The value to split the siring by.
split: StringSource,
/// The indices of the segments to modify.
ns: Vec<isize>,
/// The modification to apply.
modification: Box<Self>
},
/// Modifies the `n`th segment that matches `matcher`.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "aaa aaaa aaaa".to_string();
/// StringModification::ModifyNthMatchingSegment {
/// split: " ".into(),
/// n: 1,
/// matcher: Box::new(StringMatcher::LengthIs(4)),
/// modification: Box::new(StringModification::Set("zzzz".into()))
/// }.apply(&mut x, &job_state.to_view()).unwrap();
///
/// assert_eq!(x, "aaa aaaa zzzz");
/// ```
ModifyNthMatchingSegment {
/// The value to split the siring by.
split: StringSource,
/// The index of the segments to modify.
n: isize,
/// The [`StringMatcher`] to test each segment with.
matcher: Box<StringMatcher>,
/// The [`Self`] to apply.
modification: Box<Self>
},
/// For each `n` in `ns`, modifies the `n`th segment that matches `matcher`.
ModifyMatchingSegments {
/// The value to split the siring by.
split: StringSource,
/// The indices of the segments to modify.
ns: Vec<isize>,
/// The [`StringMatcher`] to test each segment with.
matcher: Box<StringMatcher>,
/// The [`Self`] to apply.
modification: Box<Self>
},
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let modification = StringModification::ModifyAroundNthMatchingSegment {
/// split: " ".into(),
/// n: 0,
/// matcher: Box::new(StringMatcher::Equals("b".into())),
/// shift: 1,
/// modification: Box::new(StringModification::Set("-".into()))
/// };
///
/// let mut x = "a b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "a b -");
///
/// let mut x = "a b".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap_err();
///
///
///
/// let modification = StringModification::ModifyAroundNthMatchingSegment {
/// split: " ".into(),
/// n: 0,
/// matcher: Box::new(StringMatcher::Equals("b".into())),
/// shift: -1,
/// modification: Box::new(StringModification::Set("-".into()))
/// };
///
/// let mut x = "a b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "- b c");
///
/// let mut x = "b c".to_string();
/// modification.apply(&mut x, &job_state.to_view()).unwrap_err();
/// ```
ModifyAroundNthMatchingSegment {
/// The value to split the siring by.
split: StringSource,
/// The index of the segments to modify.
n: isize,
/// The [`StringMatcher`] to test each segment with.
matcher: Box<StringMatcher>,
/// The offset of the segment to modify.
shift: isize,
/// The value to set. If `None` then the segment is removed.
modification: Box<Self>
},
/// If the provided string is in the specified map, return the value of its corresponding [`StringSource`].
/// # Errors
/// If the provided string is not in the specified map, returns the error [`StringModificationError::StringNotInMap`].
Map(HashMap<String, StringSource>),
/// Extracts the substring of `source` found between the first `start` and the first subsequent `end`.
///
/// The same as [`StringSource::ExtractBetween`] but doesn't preserve borrowedness.
/// # Errors
/// If either call to [`StringSource::get`] returns an error, that error is returned.
///
/// If either call to [`StringSource::get`] returns [`None`], returns the error [`StringModificationError::StringSourceIsNone`].
///
/// If `start` is not found in `source`, returns the error [`StringModificationError::ExtractBetweenStartNotFound`].
///
/// If `end` is not found in `source` after `start`, returns the error [`StringModificationError::ExtractBetweenEndNotFound`].
ExtractBetween {
/// The [`StringSource`] to look for before the substring.
start: StringSource,
/// The [`StringSource`] to look for after the substring.
end: StringSource
},
/// Takes every [`char`] and maps it according to the specified map.
/// # Examples
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "abc".to_string();
/// StringModification::MapChars {map: [('a', Some('A')), ('b', None)].into_iter().collect(), not_found_behavior: CharNotFoundBehavior::Nothing}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "Ac");
///
/// let mut x = "abc".to_string();
/// StringModification::MapChars {map: [('a', Some('A')), ('b', None)].into_iter().collect(), not_found_behavior: CharNotFoundBehavior::Error}.apply(&mut x, &job_state.to_view()).unwrap_err();
/// assert_eq!(x, "abc");
/// let mut x = "abc".to_string();
/// StringModification::MapChars {map: [('a', Some('A')), ('b', None), ('c', Some('c'))].into_iter().collect(), not_found_behavior: CharNotFoundBehavior::Error}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "Ac");
///
/// let mut x = "abc".to_string();
/// StringModification::MapChars {map: [('a', Some('A')), ('b', None)].into_iter().collect(), not_found_behavior: CharNotFoundBehavior::Replace(None)}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "A");
/// let mut x = "abc".to_string();
/// StringModification::MapChars {map: [('a', Some('A')), ('b', None)].into_iter().collect(), not_found_behavior: CharNotFoundBehavior::Replace(Some('?'))}.apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "A?");
/// ````
MapChars {
/// The map to map [`char`]s by
map: HashMap<char, Option<char>>,
/// What do do when a [`char`] that isn't in `map` is found.
not_found_behavior: CharNotFoundBehavior
},
/// Be careful to make sure no element key is a prefix of any other element key.
///
/// The current implementation sucks and can't handle that.
/// # Tests
/// ```
/// # use url_cleaner::types::*;
/// url_cleaner::job_state!(job_state;);
///
/// let mut x = "\\/a\\n\\\\n".to_string();
/// StringModification::RunEscapeCodes([
/// ("\\/" .to_string(), "/" .to_string()),
/// ("\\\\".to_string(), "\\".to_string()),
/// ("\\n" .to_string(), "\n".to_string())
/// ].into_iter().collect()).apply(&mut x, &job_state.to_view()).unwrap();
/// assert_eq!(x, "/a\n\\n");
/// ```
RunEscapeCodes(HashMap<String, String>),
/// Uses a [`Self`] from the [`JobState::commons`]'s [`Commons::string_modifications`].
Common(CommonCall),
/// Uses a function pointer.
///
/// Cannot be serialized or deserialized.
#[expect(clippy::type_complexity, reason = "Who cares")]
#[cfg(feature = "custom")]
Custom(FnWrapper<fn(&mut String, &JobStateView) -> Result<(), StringModificationError>>)
}
/// Tells [`StringModification::MapChars`] what to do when a [`char`] isn't found in the map.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CharNotFoundBehavior {
/// Leave the [`char`] as-is.
Nothing,
/// Return an error.
Error,
/// Replace with the specified [`char`].
Replace(Option<char>)
}
string_or_struct_magic!(StringModification);
/// Individual links in the [`StringModification::StringMatcherChain`] chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StringMatcherChainLink {
/// The [`StringMatcher`] to apply [`Self::modification`] under.
matcher: StringMatcher,
/// The [`StringModification`] to apply if [`Self::matcher`] is satisfied.
modification: StringModification
}
/// Returned when trying to call [`StringModification::from_str`] with a variant name that has non-defaultable fields.
#[derive(Debug, Error)]
#[error("Tried deserializing a StringModification variant with non-defaultable fields from a string.")]
pub struct NonDefaultableVariant;
impl FromStr for StringModification {
type Err = NonDefaultableVariant;
/// Used for allowing deserializing [`Self::Base64Decode`] and [`Self::Base64Encode`] from strings using the default values for their fields.
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()),
"UrlDecode" => StringModification::UrlDecode,
"UrlEncode" => StringModification::UrlEncode,
"None" => StringModification::None,
"Error" => StringModification::Error,
"Lowercase" => StringModification::Lowercase,
"Uppercase" => StringModification::Uppercase,
_ => Err(NonDefaultableVariant)?
})
}
}
/// The enum of all possible errors [`StringModification::apply`] can return.
#[allow(clippy::enum_variant_names, reason = "I disagree.")]
#[derive(Debug, Error)]
pub enum StringModificationError {
/// Returned when [`StringModification::Error`] is used.
#[error("StringModification::Error was used.")]
ExplicitError,
/// Returned when a [`std::str::Utf8Error`] is encountered.
#[error(transparent)]
Utf8Error(#[from] std::str::Utf8Error),
/// Returned when a [`serde_json::Error`] is encountered.
#[error(transparent)]
SerdeJsonError(#[from] serde_json::Error),
/// Returned when [`serde_json::Value::pointer`] returns [`None`].
#[error("The requested JSON value was not found.")]
JsonValueNotFound,
/// Returned when [`serde_json::Value::pointer`] returns a value that is not a string.
#[error("The requested JSON value was not a string.")]
JsonValueIsNotAString,
/// Returned when the requested slice is either not on a UTF-8 boundary or out of bounds.
#[error("The requested slice was either not on a UTF-8 boundary or out of bounds.")]
InvalidSlice,
/// Returned when the requested 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 the requested segment is not found.
#[error("The requested segment was not found.")]
SegmentNotFound,
/// Returned when the requested segments are not found.
#[error("The requested segments were not found.")]
SegmentRangeNotFound,
/// Returned when the provided string does not start with the requested prefix.
#[error("The string being modified did not start with the provided prefix. Maybe try `StringModification::StripMaybePrefix`?")]
PrefixNotFound,
/// Returned when the provided string does not end with the requested prefix.
#[error("The string being modified did not end with the provided suffix. Maybe try `StringModification::StripMaybeSuffix`?")]
SuffixNotFound,
/// Returned when the requested regex pattern is not found in the provided string.
#[error("The requested regex pattern was not found in the provided string.")]
RegexMatchNotFound,
/// Returned when a [`::regex::Error`] is encountered.
#[cfg(feature = "regex")]
#[error(transparent)]
RegexError(#[from] ::regex::Error),
/// Returned when both the `try` and `else` of a [`StringModification::TryElse`] both return errors.
#[error("A `StringModification::TryElse` had both `try` and `else` return an error.")]
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 a [`::base64::DecodeError`] is encountered.
#[error(transparent)]
#[cfg(feature = "base64")]
Base64DecodeError(#[from] ::base64::DecodeError),
/// Returned when a [`std::string::FromUtf8Error`] is encountered.
#[error(transparent)]
FromUtf8Error(#[from] std::string::FromUtf8Error),
/// Returned when a [`StringSourceError`] is encountered.
#[error(transparent)]
StringSourceError(#[from] Box<StringSourceError>),
/// Returned when a call to [`StringSource::get`] returns `None` where it has to be `Some`.
#[error("The specified StringSource returned None where it had to be Some.")]
StringSourceIsNone,
/// Returned when the provided string is not in the specified map.
#[error("The provided string was not in the specified map.")]
StringNotInMap,
/// Returned when a [`StringMatcherError`] is encountered.
#[error(transparent)]
StringMatcherError(#[from] Box<StringMatcherError>),
/// Returned when a [`MakeBase64EngineError`] is encountered.
#[error(transparent)]
#[cfg(feature = "base64")]
MakeBase64EngineError(#[from] MakeBase64EngineError),
/// Returned when the `start` of a [`StringModification::ExtractBetween`] is not found in the provided string.
#[error("The `start` of an `ExtractBetween` was not found in the provided string.")]
ExtractBetweenStartNotFound,
/// Returned when the `start` of a [`StringModification::ExtractBetween`] is not found in the provided string.
#[error("The `end` of an `ExtractBetween` was not found in the provided string.")]
ExtractBetweenEndNotFound,
/// Returned by [`StringModification::MapChars`] when [`StringModification::MapChars::not_found_behavior`] is set to [`CharNotFoundBehavior::Error`] and a character not in [`StringModification::MapChars::map`] is encountered.
#[error("Attempted to map a character not found in the mapping map.")]
CharNotInMap,
/// Returned when the common [`StringModification`] is not found.
#[error("The common StringModification was not found.")]
CommonStringModificationNotFound,
/// Returned when a [`CommonCallArgsError`] is encountered.
#[error(transparent)]
CommonCallArgsError(#[from] CommonCallArgsError),
/// Custom error.
#[error(transparent)]