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
//! Rules for looking for a string in another string.
use std::ops::Bound;
use serde::{Serialize, Deserialize};
use thiserror::Error;
#[expect(unused_imports, reason = "Used in docs.")]
use crate::types::*;
use crate::util::*;
/// Search a string for a substring in one of various ways.
///
/// Defaults to [`Self::Anywhere`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Suitability)]
#[serde(deny_unknown_fields)]
pub enum StringLocation {
/// Always satisfied.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::Always.check("a", "b").unwrap());
/// ```
Always,
/// Never satisfied.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::Never.check("a", "a").unwrap());
/// ```
Never,
/// Always returns the error [`StringLocationError::ExplicitError`] with the included message.
/// # Errors
/// Always returns the error [`StringLocationError::ExplicitError`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// StringLocation::Error("aaa".to_string()).check("a", "a").unwrap_err();
/// ```
Error(String),
/// Prints debug info about the contained [`Self`] and the current [`TaskState`], then returns its return value.
/// # Errors
/// If the call to [`Self::check`] returns an error, that error is returned after the debug info is printed.
#[suitable(never)]
Debug(Box<Self>),
/// Swap the haystack and the needle.
/// # Errors
#[doc = edoc!(checkerr(Self))]
Swap(Box<Self>),
// Logic
/// If [`Self::IfContains::at`] is satisfied, return the value of [`Self::IfContains::then`].
///
/// If [`Self::IfContains::at`] is unsatisfied, return the value of [`Self::IfContains::else`].
/// # Errors
/// If any call to [`Self::check`] returns an error, that error is returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::IfContains {
/// at: Box::new(StringLocation::Always),
/// then : Box::new(StringLocation::Always),
/// r#else : Box::new(StringLocation::Never)
/// }.check("a", "a").unwrap());
///
/// assert!(!StringLocation::IfContains {
/// at: Box::new(StringLocation::Never),
/// then : Box::new(StringLocation::Always),
/// r#else : Box::new(StringLocation::Never)
/// }.check("a", "a").unwrap());
/// ```
IfContains {
/// The [`Self`] to decide between [`Self::IfContains::then`] and [`Self::IfContains::else`].
at: Box<Self>,
/// The [`Self`] to use if [`Self::IfContains::at`] is satisfied.
then: Box<Self>,
/// The [`Self`] to use if [`Self::IfContains::at`] is unsatisfied.
r#else: Box<Self>
},
/// Inverts the satisfaction of the contained [`Self`].
/// # Errors
/// If the call to [`Self::check`] returns an error, that error is returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::Not(Box::new(StringLocation::Anywhere)).check("abc", "a").unwrap());
/// ```
Not(Box<Self>),
/// Satisfied if all contained [`Self`]s are satisfied.
/// # Errors
/// If any call to [`Self::check`] returns an error, that error is returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::All(vec![
/// StringLocation::Start,
/// StringLocation::End
/// ]).check("abcba", "a").unwrap());
/// ```
All(Vec<Self>),
/// Satisfied if any contained [`Self`] is satisfied.
/// # Errors
/// If any call to [`Self::check`] returns an error, that error is returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::Any(vec![
/// StringLocation::Start,
/// StringLocation::End
/// ]).check("cba", "a").unwrap());
/// ```
Any(Vec<Self>),
// Error handling
/// Satisfied if the contained [`Self`] is satisfied or errors.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::ErrorToSatisfied(Box::new(StringLocation::Error("".to_string()))).check("a", "a").unwrap());
/// ```
ErrorToSatisfied(Box<Self>),
/// Satisfied if the contained [`Self`] is satisfied.
///
/// Unsatisfied if the contained [`Self`] errors.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::ErrorToUnsatisfied(Box::new(StringLocation::Error("".to_string()))).check("a", "a").unwrap());
/// ```
ErrorToUnsatisfied(Box<Self>),
/// If [`Self::TryElse::try`]'s call to [`Self::check`] returns an error, return the value of [`Self::TryElse::else`].
/// # Errors
/// If both calls to [`Self::check`] return errors, both errors are returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::TryElse {
/// r#try : Box::new(StringLocation::Error("".to_string())),
/// r#else: Box::new(StringLocation::Always)
/// }.check("a", "a").unwrap());
/// ```
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>
},
/// Return the first non-error value.
/// # Errors
/// If all calls to [`Self::check`] return errors, the last error is returned. In the future this should be changed to return all errors.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::FirstNotError(vec![
/// StringLocation::Error("".to_string()),
/// StringLocation::Error("".to_string()),
/// StringLocation::Always
/// ]).check("a", "a").unwrap());
/// ```
FirstNotError(Vec<Self>),
// Other
/// Satisfied if the needle exists anywhere in the haystack.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::Anywhere.check("abc", "a").unwrap());
/// assert!(StringLocation::Anywhere.check("cba", "a").unwrap());
/// assert!(StringLocation::Anywhere.check("bca", "a").unwrap());
/// ```
#[default]
Anywhere,
/// Satisfied if the haystack begins with the needle.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!( StringLocation::Start.check("abc", "a").unwrap());
/// assert!(!StringLocation::Start.check("cac", "a").unwrap());
/// assert!(!StringLocation::Start.check("bca", "a").unwrap());
/// ```
Start,
/// Satisfied if the haystack ends with the needle.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::End.check("abc", "a").unwrap());
/// assert!(!StringLocation::End.check("cac", "a").unwrap());
/// assert!( StringLocation::End.check("bca", "a").unwrap());
/// ```
End,
/// Satisfied if the needle starts at the specified location in the haystack.
/// # Errors
/// If the specified index is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::StartsAt(0).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::StartsAt(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::StartsAt(2).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::StartsAt(3).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::StartsAt(4).check("#abc#", "abc").unwrap());
/// ```
StartsAt(isize),
/// Satisfied if the needle ends at the specified location in the haystack.
/// # Errors
/// If the specified index is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::EndsAt(0).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::EndsAt(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::EndsAt(2).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::EndsAt(3).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::EndsAt(4).check("#abc#", "abc").unwrap());
/// ```
EndsAt(isize),
/// Satisfied if the haystack contains the needle at or after the specified index.
/// # Errors
/// If the specified index is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!( StringLocation::AtOrAfter(0).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::AtOrAfter(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::AtOrAfter(2).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::AtOrAfter(3).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::AtOrAfter(4).check("#abc#", "abc").unwrap());
/// ```
AtOrAfter(isize),
/// Satisfied if the haystack contains the needle before or at the specified index.
/// # Errors
/// If the specified index is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::BeforeOrAt(0).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::BeforeOrAt(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::BeforeOrAt(2).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::BeforeOrAt(3).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::BeforeOrAt(4).check("#abc#", "abc").unwrap());
/// ```
BeforeOrAt(isize),
/// Satisfied if the haystack contains the needle after the specified index.
/// # Errors
/// If the specified range is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!( StringLocation::After(0).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::After(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::After(2).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::After(3).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::After(4).check("#abc#", "abc").unwrap());
/// ```
After(isize),
/// Satisfied if the haystack contains the needle before the specified index.
/// # Errors
/// If the specified range is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidIndex`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::Before(0).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::Before(1).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::Before(2).check("#abc#", "abc").unwrap());
/// assert!(!StringLocation::Before(3).check("#abc#", "abc").unwrap());
/// assert!( StringLocation::Before(4).check("#abc#", "abc").unwrap());
/// ```
Before(isize),
/// Satisfied if the haystack is equal to the needle.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!( StringLocation::Equals.check( "abc" , "abc").unwrap());
/// assert!(!StringLocation::Equals.check("#abc" , "abc").unwrap());
/// assert!(!StringLocation::Equals.check( "abc#", "abc").unwrap());
/// assert!(!StringLocation::Equals.check("#abc#", "abc").unwrap());
/// ```
Equals,
/// Satisfied if the haystack contains the needle in the specified range at [`Self::InRange::at`].
/// # Errors
/// If the specified range is either out of bounds or doesn't fall on UTF-8 character boundaries, returns the error [`StringLocationError::InvalidSlice`].
///
/// If the call to [`Self::check`] returns an error, that error is returned.
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::InRange {
/// start: 0,
/// end : Some(3),
/// at : Box::new(StringLocation::Equals)
/// }.check("abc##", "abc").unwrap());
/// ```
InRange {
/// The start of the range to search in.
start: isize,
/// The end of the range to search in, exclusive.
///
/// Set to [`None`] to keep it unbounded.
end: Option<isize>,
/// The [`Self`] to search for the needle in the range.
at: Box<Self>
},
/// Satisfied if any segment of the haystack, split by [`Self::AnySegment::split`], contains the needle at [`Self::AnySegment::at`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(StringLocation::AnySegment {
/// split: "/".to_string(),
/// at : Box::new(StringLocation::Equals)
/// }.check("123/abc/456", "abc").unwrap());
/// ```
AnySegment {
/// The string to split the haystack with.
split: String,
/// The [`Self`] to search for the needle in each segment.
at: Box<Self>
},
/// Satisfied if the [`Self::NthSegment::n`]th segment of the haystack, split by [`Self::NthSegment::split`], contains the needle at [`Self::NthSegment::at`].
/// # Examples
/// ```
/// use url_cleaner_engine::types::*;
///
/// assert!(!StringLocation::NthSegment {
/// split: "/".to_string(),
/// n : 0,
/// at : Box::new(StringLocation::Equals)
/// }.check("123/abc/456", "abc").unwrap());
///
/// assert!(StringLocation::NthSegment {
/// split: "/".to_string(),
/// n : 1,
/// at : Box::new(StringLocation::Equals)
/// }.check("123/abc/456", "abc").unwrap());
///
/// assert!(!StringLocation::NthSegment {
/// split: "/".to_string(),
/// n : 2,
/// at : Box::new(StringLocation::Equals)
/// }.check("123/abc/456", "abc").unwrap());
/// ```
NthSegment {
/// The string to split the haystack with.
split: String,
/// The index of the segment to search in.
n: isize,
/// The [`Self`] to search for the needle in the [`Self::NthSegment::n`]th segment.
at: Box<Self>
}
}
/// The enum of errors [`StringLocation::check`] can return.
#[derive(Debug, Error)]
pub enum StringLocationError {
/// Returned when a [`StringLocation::Error`] is used.
#[error("Explicit error: {0}")]
ExplicitError(String),
/// Returned when both [`StringLocation`]s in a [`StringLocation::TryElse`] return errors.
#[error("Both StringLocations in a StringLocation::TryElse returned errors.")]
TryElseError {
/// The error returned by [`StringLocation::TryElse::try`].
try_error: Box<Self>,
/// The error returned by [`StringLocation::TryElse::else`].
else_error: Box<Self>
},
/// 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
}
impl StringLocation {
/// Checks if `needle` occurs in `haystack` at the specified location.
/// # Errors
/// See each variant of [`Self`] for when each variant returns an error.
pub fn check(&self, haystack: &str, needle: &str) -> Result<bool, StringLocationError> {
debug!(StringLocation::check, self, haystack, needle);
Ok(match self {
Self::Always => true,
Self::Never => false,
Self::Error(msg) => Err(StringLocationError::ExplicitError(msg.clone()))?,
Self::Debug(location) => {
let is_satisfied=location.check(haystack, needle);
eprintln!("=== StringLocation::Debug ===\nLocation: {location:?}\nHaystack: {haystack:?}\nNeedle: {needle:?}\nSatisfied?: {is_satisfied:?}");
is_satisfied?
},
Self::Swap(location) => location.check(needle, haystack)?,
// Logic.
Self::IfContains {at, then, r#else} => if at.check(haystack, needle)? {then} else {r#else}.check(haystack, needle)?,
Self::All(locations) => {
for location in locations {
if !location.check(haystack, needle)? {
return Ok(false);
}
}
true
},
Self::Any(locations) => {
for location in locations {
if location.check(haystack, needle)? {
return Ok(true);
}
}
false
},
Self::Not(location) => !location.check(haystack, needle)?,
// Error handling.
Self::ErrorToSatisfied (location) => location.check(haystack, needle).unwrap_or(true),
Self::ErrorToUnsatisfied(location) => location.check(haystack, needle).unwrap_or(false),
Self::TryElse{r#try, r#else} => r#try.check(haystack, needle).or_else(|try_error| r#else.check(haystack, needle).map_err(|else_error| StringLocationError::TryElseError {try_error: Box::new(try_error), else_error: Box::new(else_error)}))?,
Self::FirstNotError(locations) => {
let mut result = Ok(false); // Initial value doesn't mean anything.
for location in locations {
result = location.check(haystack, needle);
if result.is_ok() {return result}
}
result?
}
// Other.
Self::Anywhere => haystack.contains(needle),
Self::Start => haystack.starts_with(needle),
Self::StartsAt (start) => haystack.get((Bound::Included(neg_index(*start, haystack.len()).ok_or(StringLocationError::InvalidIndex)?), Bound::Unbounded)).ok_or(StringLocationError::InvalidSlice)?.starts_with(needle),
Self::AtOrAfter(start) => haystack.get((Bound::Included(neg_index(*start, haystack.len()).ok_or(StringLocationError::InvalidIndex)?), Bound::Unbounded)).ok_or(StringLocationError::InvalidSlice)?.contains(needle),
Self::After (start) => haystack.get((Bound::Excluded(neg_index(*start, haystack.len()).ok_or(StringLocationError::InvalidIndex)?), Bound::Unbounded)).ok_or(StringLocationError::InvalidSlice)?.contains(needle),
Self::End => haystack.ends_with(needle),
Self::EndsAt (end) => haystack.get((Bound::Unbounded, Bound::Included(neg_index(*end, haystack.len()).ok_or(StringLocationError::InvalidIndex)?))).ok_or(StringLocationError::InvalidSlice)?.ends_with(needle),
Self::BeforeOrAt(end) => haystack.get((Bound::Unbounded, Bound::Included(neg_index(*end, haystack.len()).ok_or(StringLocationError::InvalidIndex)?))).ok_or(StringLocationError::InvalidSlice)?.contains(needle),
Self::Before (end) => haystack.get((Bound::Unbounded, Bound::Excluded(neg_index(*end, haystack.len()).ok_or(StringLocationError::InvalidIndex)?))).ok_or(StringLocationError::InvalidSlice)?.contains(needle),
Self::InRange {start, end, at} => at.check(
haystack.get(neg_range(*start, *end, haystack.len()).ok_or(StringLocationError::InvalidSlice)?).ok_or(StringLocationError::InvalidSlice)?,
needle
)?,
Self::Equals => haystack==needle,
Self::AnySegment {split, at} => {
for segment in haystack.split(split) {
if at.check(segment, needle)? {
return Ok(true)
}
}
return Ok(false)
},
Self::NthSegment {split, n, at} => at.check(neg_nth(haystack.split(split), *n).ok_or(StringLocationError::SegmentNotFound)?, needle)?
})
}
}