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
//! URI and IRI resolvers.
//!
//! # IRI resolution can fail
//!
//! Though this is not explicitly stated in RFC 3986, IRI resolution can fail.
//! Below are examples:
//!
//! * base=`scheme:`, ref=`.///bar`.
//!     + Resulting IRI should have scheme `scheme` and path `//bar`, but does not have authority.
//! * base=`scheme:foo`, ref=`.///bar`.
//!     + Resulting IRI should have scheme `scheme` and path `//bar`, but does not have authority.
//! * base=`scheme:`, ref=`/..//baz`.
//!     + Resulting IRI should have scheme `scheme` and path `//bar`, but does not have authority.
//! * base=`scheme:foo/bar`, ref=`..//baz`.
//!     + Resulting IRI should have scheme `scheme` and path `//bar`, but does not have authority.
//!
//! IRI without authority (note that this is different from "with empty authority")
//! cannot have a path starting with `//`, since it is ambiguous and can be
//! interpreted as an IRI with authority. For the above examples, `scheme://bar`
//! is not valid output, as `bar` in `scheme://bar` will be interpreted as an
//! authority, not a path.
//!
//! Thus, IRI resolution can fail for some abnormal cases.
//!
//! Note that this kind of failure can happen only when the base IRI has no
//! authority and empty path. This would be rare in the wild, since many people
//! would use an IRI with authority part, such as `http://`.
//!
//! If you are handling `scheme://`-style URIs and IRIs, don't worry about the
//! failure. Currently no cases are known to fail when at least one of the base
//! IRI or the relative IRI contains authorities.
//!
//! If you want this kind of abnormal IRI resolution to succeed and to be
//! idempotent, use WHATWG variation of resolution and normalization.
//!
//! ## Examples
//!
//! ```
//! # #[cfg(feature = "alloc")] {
//! use iri_string::task::Error as TaskError;
//! use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
//!
//! let base = IriAbsoluteStr::new("scheme:")?;
//! {
//!     let reference = IriReferenceStr::new(".///not-a-host")?;
//!     let err = reference.resolve_against(base)
//!         .expect_err("this resolution should fail");
//!     assert!(matches!(err, TaskError::Process(_)), "normalization error");
//!
//!     // WHATWG version.
//!     let resolved_whatwg = reference.resolve_whatwg_against(base)
//!         .expect("memory allocation failed");
//!     assert_eq!(*resolved_whatwg, "scheme:/.//not-a-host");
//! }
//!
//! {
//!     let reference2 = IriReferenceStr::new("/..//not-a-host")?;
//!     // Resulting string will be `scheme://not-a-host`, but `not-a-host`
//!     // should be a path segment, not a host. So, the semantically correct
//!     // target IRI cannot be represented by RFC 3986 IRI resolution.
//!     let err2 = reference2.resolve_against(base)
//!         .expect_err("this resolution should fail");
//!     assert!(matches!(err2, TaskError::Process(_)), "normalization error");
//!
//!     // Algorithm defined in WHATWG URL Standard addresses this case.
//!     let resolved_whatwg2 = reference2.resolve_whatwg_against(base)
//!         .expect("memory allocation failed");
//!     assert_eq!(*resolved_whatwg2, "scheme:/.//not-a-host");
//! }
//! # }
//! # Ok::<_, iri_string::validate::Error>(())
//! ```

#[cfg(test)]
mod tests;

#[cfg(feature = "alloc")]
use core::convert::Infallible;

use crate::components::RiReferenceComponents;
#[cfg(feature = "alloc")]
use crate::normalize::Error;
use crate::normalize::{
    NormalizationOp, NormalizationTask, NormalizationTaskCommon, Path, PathToNormalize,
};
use crate::spec::Spec;
#[cfg(feature = "alloc")]
use crate::task::{Error as TaskError, ProcessAndWrite};
#[cfg(feature = "alloc")]
use crate::types::RiString;
use crate::types::{RiAbsoluteStr, RiReferenceStr, RiStr};

/// Resolves the IRI reference.
///
/// It is recommended to use methods such as [`RiReferenceStr::resolve_against()`] and
/// [`RiRelativeStr::resolve_against()`], rather than this freestanding function.
///
/// If you are going to resolve multiple references against the common base,
/// consider using [`FixedBaseResolver`].
///
/// Enabled by `alloc` or `std` feature.
///
/// # Failures
///
/// This fails if
///
/// * memory allocation failed, or
/// * the IRI referernce is unresolvable against the base.
///
/// To see examples of unresolvable IRIs, visit the documentation
/// for [`normalize::Error`][`crate::normalize::Error`].
///
/// # Examples
///
/// ```
/// # #[derive(Debug)] struct Error;
/// # impl From<iri_string::validate::Error> for Error {
/// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
/// # impl<T> From<iri_string::task::Error<T>> for Error {
/// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
/// use iri_string::resolve::{resolve, FixedBaseResolver};
/// use iri_string::task::ProcessAndWrite;
/// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
///
/// let base = IriAbsoluteStr::new("http://example.com/base/")?;
/// let reference = IriReferenceStr::new("../there")?;
///
/// // Resolve `reference` against `base`.
/// let resolved = resolve(reference, base)?;
/// assert_eq!(resolved, "http://example.com/there");
///
/// // These two produces the same result with the same type.
/// assert_eq!(
///     FixedBaseResolver::new(base).resolve(reference)?,
///     "http://example.com/there"
/// );
/// assert_eq!(
///     FixedBaseResolver::new(base).create_task(reference).allocate_and_write()?,
///     "http://example.com/there"
/// );
/// # Ok::<_, Error>(())
/// ```
///
/// [`RiReferenceStr::resolve_against()`]: `RiReferenceStr::resolve_against`
/// [`RiRelativeStr::resolve_against()`]: `crate::types::RiRelativeStr::resolve_against`
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn resolve<S: Spec>(
    reference: impl AsRef<RiReferenceStr<S>>,
    base: impl AsRef<RiAbsoluteStr<S>>,
) -> Result<RiString<S>, TaskError<Error>> {
    FixedBaseResolver::new(base.as_ref()).resolve(reference.as_ref())
}

/// Resolves the IRI reference.
///
/// It is recommended to use methods such as [`RiReferenceStr::resolve_whatwg_against()`]
/// and [`RiRelativeStr::resolve_whatwg_against()`], rather than this freestanding function.
///
/// If you are going to resolve multiple references against the common base,
/// consider using [`FixedBaseResolver`].
///
/// Enabled by `alloc` or `std` feature.
///
/// # Failures
///
/// This fails if memory allocation failed.
///
/// # Examples
///
/// ```
/// # #[derive(Debug)] struct Error;
/// # impl From<iri_string::validate::Error> for Error {
/// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
/// # impl<T> From<iri_string::task::Error<T>> for Error {
/// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
/// use iri_string::resolve::{resolve_whatwg, FixedBaseResolver};
/// use iri_string::task::ProcessAndWrite;
/// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
///
/// let base = IriAbsoluteStr::new("scheme:/path")?;
/// let reference = IriReferenceStr::new("..//not-a-host")?;
///
/// // Resolve `reference` against `base`.
/// let resolved = resolve_whatwg(reference, base)?;
/// // Note that the result is not `scheme://not-a-host`.
/// assert_eq!(resolved, "scheme:/.//not-a-host");
/// # Ok::<_, Error>(())
/// ```
///
/// [`RiReferenceStr::resolve_whatwg_against()`]: `RiReferenceStr::resolve_whatwg_against`
/// [`RiRelativeStr::resolve_whatwg_against()`]:
///     `crate::types::RiRelativeStr::resolve_whatwg_against`
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn resolve_whatwg<S: Spec>(
    reference: impl AsRef<RiReferenceStr<S>>,
    base: impl AsRef<RiAbsoluteStr<S>>,
) -> Result<RiString<S>, TaskError<Infallible>> {
    let mut task = FixedBaseResolver::new(base.as_ref()).create_task(reference.as_ref());
    task.enable_whatwg_serialization();
    task.allocate_and_write().map_err(|e| match e {
        TaskError::Buffer(e) => TaskError::Buffer(e),
        TaskError::Process(_) => unreachable!("WHATWG normaliation algorithm should not fail"),
    })
}

/// Resolves and normalizes the IRI reference.
///
/// It is recommended to use methods such as [`RiReferenceStr::resolve_normalize_against()`]
/// and [`RiRelativeStr::resolve_normalize_against()`], rather than this
/// freestanding function.
///
/// If you are going to resolve multiple references against the common base,
/// consider using [`FixedBaseResolver`].
///
/// Enabled by `alloc` or `std` feature.
///
/// # Failures
///
/// This fails if
///
/// * memory allocation failed, or
/// * the IRI referernce is unresolvable against the base.
///
/// To see examples of unresolvable IRIs, visit the
/// [module documentation][`self`].
///
/// # Examples
///
/// ```
/// # #[derive(Debug)] struct Error;
/// # impl From<iri_string::validate::Error> for Error {
/// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
/// # impl<T> From<iri_string::task::Error<T>> for Error {
/// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
/// use iri_string::resolve::{resolve_normalize, FixedBaseResolver};
/// use iri_string::task::ProcessAndWrite;
/// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
///
/// let base = IriAbsoluteStr::new("http://example.com/base/")?;
/// let reference = IriReferenceStr::new("../there")?;
///
/// // Resolve and normalize `reference` against `base`.
/// let resolved = resolve_normalize(reference, base)?;
/// assert_eq!(resolved, "http://example.com/there");
///
/// // These two produces the same result with the same type.
/// assert_eq!(
///     FixedBaseResolver::new(base).resolve(reference)?,
///     "http://example.com/there"
/// );
/// assert_eq!(
///     FixedBaseResolver::new(base)
///         .create_normalizing_task(reference)
///         .allocate_and_write()?,
///     "http://example.com/there"
/// );
///
/// # Ok::<_, Error>(())
/// ```
///
/// [RFC 3986 section 5.2]: https://tools.ietf.org/html/rfc3986#section-5.2
/// [`RiReferenceStr::resolve_normalize_against()`]: `RiReferenceStr::resolve_normalize_against`
/// [`RiRelativeStr::resolve_normalize_against()`]: `crate::types::RiRelativeStr::resolve_normalize_against`
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn resolve_normalize<S: Spec>(
    reference: impl AsRef<RiReferenceStr<S>>,
    base: impl AsRef<RiAbsoluteStr<S>>,
) -> Result<RiString<S>, TaskError<Error>> {
    FixedBaseResolver::new(base.as_ref()).resolve_normalize(reference.as_ref())
}

/// Resolves and normalizes the IRI reference.
///
/// It is recommended to use methods such as
/// [`RiReferenceStr::resolve_normalize_whatwg_against()`] and
/// [`RiRelativeStr::resolve_normalize_whatwg_against()`], rather than this
/// freestanding function.
///
/// If you are going to resolve multiple references against the common base,
/// consider using [`FixedBaseResolver`].
///
/// Enabled by `alloc` or `std` feature.
///
/// # Failures
///
/// This fails if memory allocation failed.
///
/// # Examples
///
/// ```
/// # #[derive(Debug)] struct Error;
/// # impl From<iri_string::validate::Error> for Error {
/// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
/// # impl<T> From<iri_string::task::Error<T>> for Error {
/// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
/// use iri_string::resolve::{resolve_normalize_whatwg, FixedBaseResolver};
/// use iri_string::task::ProcessAndWrite;
/// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
///
/// let base = IriAbsoluteStr::new("scheme:/path")?;
/// let reference = IriReferenceStr::new("..//not-a-host")?;
///
/// // Resolve and normalize `reference` against `base`.
/// let resolved = resolve_normalize_whatwg(reference, base)?;
/// assert_eq!(resolved, "scheme:/.//not-a-host");
/// # Ok::<_, Error>(())
/// ```
///
/// [RFC 3986 section 5.2]: https://tools.ietf.org/html/rfc3986#section-5.2
/// [`RiReferenceStr::resolve_normalize_whatwg_against()`]:
///     `RiReferenceStr::resolve_normalize_whatwg_against`
/// [`RiRelativeStr::resolve_normalize_whatwg_against()`]:
///     `crate::types::RiRelativeStr::resolve_normalize_whatwg_against`
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn resolve_normalize_whatwg<S: Spec>(
    reference: impl AsRef<RiReferenceStr<S>>,
    base: impl AsRef<RiAbsoluteStr<S>>,
) -> Result<RiString<S>, TaskError<Infallible>> {
    let mut task =
        FixedBaseResolver::new(base.as_ref()).create_normalizing_task(reference.as_ref());
    task.enable_whatwg_serialization();
    task.allocate_and_write().map_err(|e| match e {
        TaskError::Buffer(e) => TaskError::Buffer(e),
        TaskError::Process(_) => unreachable!("WHATWG normaliation algorithm should not fail"),
    })
}

/// A resolver against the fixed base.
///
/// If you want more control over how to resolve the buffer, create
/// [`NormalizationTask`] by [`create_task`] or [`create_normalizing_task`] method.
///
/// [`create_normalizing_task`]: `Self::create_normalizing_task`
/// [`create_task`]: `Self::create_task`
#[derive(Debug, Clone, Copy)]
pub struct FixedBaseResolver<'a, S: Spec> {
    /// Components of the base IRI.
    base_components: RiReferenceComponents<'a, S>,
}

impl<'a, S: Spec> FixedBaseResolver<'a, S> {
    /// Creates a new resolver with the given base.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// # #[cfg(feature = "alloc")] {
    /// # // `FixedBaseResolver::resolve()` is available only when
    /// # // `alloc` feature is enabled.
    /// let base = IriAbsoluteStr::new("http://example.com/base/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// let reference = IriReferenceStr::new("../there")?;
    /// let resolved = resolver.resolve(reference)?;
    ///
    /// assert_eq!(resolved, "http://example.com/there");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[must_use]
    pub fn new(base: &'a RiAbsoluteStr<S>) -> Self {
        Self {
            base_components: RiReferenceComponents::from(base.as_ref()),
        }
    }

    /// Returns the base.
    ///
    /// # Examples
    ///
    /// ```
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// let base = IriAbsoluteStr::new("http://example.com/base/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// assert_eq!(resolver.base(), base);
    /// # Ok::<_, iri_string::validate::Error>(())
    /// ```
    #[must_use]
    pub fn base(&self) -> &'a RiAbsoluteStr<S> {
        unsafe {
            // SAFETY: `base_components` can only be created from `&RiAbsoluteStr<S>`.
            RiAbsoluteStr::new_maybe_unchecked(self.base_components.iri().as_str())
        }
    }
}

impl<'a, S: Spec> FixedBaseResolver<'a, S> {
    /// Resolves the given reference against the fixed base.
    ///
    /// Enabled by `alloc` or `std` feature.
    ///
    /// The task returned by this method does **not** normalize the resolution
    /// result. However, `..` and `.` are recognized even when they are
    /// percent-encoded.
    ///
    /// # Failures
    ///
    /// This fails if
    ///
    /// * memory allocation failed, or
    /// * the IRI referernce is unresolvable against the base.
    ///
    /// To see examples of unresolvable IRIs, visit the
    /// [module documentation][`self`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// let base = IriAbsoluteStr::new("http://example.com/base/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// let reference = IriReferenceStr::new("../there")?;
    /// let resolved = resolver.resolve(reference)?;
    ///
    /// assert_eq!(resolved, "http://example.com/there");
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// Note that `..` and `.` path segments are recognized even when they are
    /// percent-encoded.
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::task::ProcessAndWrite;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// # #[cfg(feature = "alloc")] {
    /// # // `ResolutionTask::allocate_and_write()` is available only when
    /// # // `alloc` feature is enabled.
    /// let base = IriAbsoluteStr::new("HTTP://example.COM/base/base2/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// // `%2e%2e` is recognized as `..`.
    /// // However, `dot%2edot` is NOT normalized into `dot.dot`.
    /// let reference = IriReferenceStr::new("%2e%2e/../dot%2edot")?;
    /// let task = resolver.create_task(reference);
    ///
    /// let resolved = task.allocate_and_write()?;
    /// // Resolved but not normalized.
    /// assert_eq!(resolved, "HTTP://example.COM/dot%2edot");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// [`create_normalizing_task`]: `Self::create_normalizing_task`
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn resolve(&self, reference: &RiReferenceStr<S>) -> Result<RiString<S>, TaskError<Error>> {
        self.create_task(reference).allocate_and_write()
    }

    /// Resolves the given reference against the fixed base, and normalizes the result.
    ///
    /// Enabled by `alloc` or `std` feature.
    ///
    /// The task returned by this method is normalized.
    ///
    /// If you don't want the result to be normalized, use [`create_task`] method.
    ///
    /// # Failures
    ///
    /// This fails if
    ///
    /// * memory allocation failed, or
    /// * the IRI referernce is unresolvable against the base.
    ///
    /// To see examples of unresolvable IRIs, visit the
    /// [module documentation][`self`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::task::ProcessAndWrite;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// # #[cfg(feature = "alloc")] {
    /// # // `ResolutionTask::allocate_and_write()` is available only when
    /// # // `alloc` feature is enabled.
    /// let base = IriAbsoluteStr::new("HTTP://example.COM/base/base2/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// // `%2e%2e` is recognized as `..`.
    /// let reference = IriReferenceStr::new("%2e%2e/../dot%2edot")?;
    /// let task = resolver.create_normalizing_task(reference);
    ///
    /// let resolved = task.allocate_and_write()?;
    /// // Not only resolved, but also normalized.
    /// assert_eq!(resolved, "http://example.com/dot.dot");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// [`create_task`]: `Self::create_task`
    /// [`unreserved` characters]: https://datatracker.ietf.org/doc/html/rfc3986#section-2.3
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn resolve_normalize(
        &self,
        reference: &RiReferenceStr<S>,
    ) -> Result<RiString<S>, TaskError<Error>> {
        self.create_normalizing_task(reference).allocate_and_write()
    }

    /// Creates a resolution task.
    ///
    /// The returned [`NormalizationTask`] allows you to resolve the IRI without
    /// memory allocation, resolve to existing buffers, estimate required
    /// memory size, etc. If you need more control than
    /// [`resolve`][`Self::resolve`] method, use this.
    ///
    /// The task returned by this method does not normalize the resolution
    /// result. However, note that `..` and `.` is recognized even when they
    /// are percent-encoded.
    ///
    /// If you want to normalize the result, use
    /// [`create_normalizing_task`][`Self::create_normalizing_task`]
    /// method instead, or call [`NormalizationTask::enable_normalization`] for
    /// the returned task.
    ///
    /// If you want to avoid resolution failure by using resolution described in
    /// WHATWG URL Standard, call
    /// [`NormalizationTask::enable_whatwg_serialization`] for the returned task.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::task::ProcessAndWrite;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// # #[cfg(feature = "alloc")] {
    /// # // `ResolutionTask::allocate_and_write()` is available only when
    /// # // `alloc` feature is enabled.
    /// let base = IriAbsoluteStr::new("HTTP://example.COM/base/base2/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// // `%2e%2e` is recognized as `..`.
    /// // However, `dot%2edot` is NOT normalized into `dot.dot`.
    /// let reference = IriReferenceStr::new("%2e%2e/../dot%2edot")?;
    /// let task = resolver.create_task(reference);
    ///
    /// let resolved = task.allocate_and_write()?;
    /// // Resolved but not normalized.
    /// assert_eq!(resolved, "HTTP://example.COM/dot%2edot");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// [`create_task`]: `Self::create_task`
    #[must_use]
    pub fn create_task(&self, reference: &'a RiReferenceStr<S>) -> NormalizationTask<'a, RiStr<S>> {
        let b = self.base_components;
        let r = RiReferenceComponents::from(reference);

        let (r_scheme, r_authority, r_path, r_query, r_fragment) = r.to_major();
        let (b_scheme, b_authority, b_path, b_query, _) = b.to_major();
        let b_scheme = b_scheme.expect("[validity] non-relative IRI must have a scheme");

        /// The toplevel component the reference has.
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        enum RefToplevel {
            /// Scheme.
            Scheme,
            /// Authority.
            Authority,
            /// Path.
            Path,
            /// Query.
            Query,
            /// Reference is empty or has only fragment.
            None,
        }

        impl RefToplevel {
            /// Choose a component from either of the reference or the base,
            /// based on the toplevel component of the reference.
            fn choose<T>(self, component: RefToplevel, reference: T, base: T) -> T {
                if self <= component {
                    reference
                } else {
                    base
                }
            }
        }

        let ref_toplevel = if r_scheme.is_some() {
            RefToplevel::Scheme
        } else if r_authority.is_some() {
            RefToplevel::Authority
        } else if !r_path.is_empty() {
            RefToplevel::Path
        } else if r_query.is_some() {
            RefToplevel::Query
        } else {
            RefToplevel::None
        };

        let path = match ref_toplevel {
            RefToplevel::Scheme | RefToplevel::Authority => {
                Path::NeedsProcessing(PathToNormalize::from_single_path(r_path))
            }
            RefToplevel::Path => {
                if r_path.starts_with('/') {
                    Path::NeedsProcessing(PathToNormalize::from_single_path(r_path))
                } else {
                    // About this branch, see
                    // <https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.3>.
                    //
                    // > o  If the base URI has a defined authority component and an empty
                    // >    path, then return a string consisting of "/" concatenated with the
                    // >    reference's path; otherwise,
                    let b_path = if b_authority.is_some() && b_path.is_empty() {
                        "/"
                    } else {
                        b_path
                    };
                    Path::NeedsProcessing(PathToNormalize::from_paths_to_be_resolved(
                        b_path, r_path,
                    ))
                }
            }
            RefToplevel::Query | RefToplevel::None => Path::Done(b_path),
        };

        NormalizationTaskCommon {
            scheme: r_scheme.unwrap_or(b_scheme),
            authority: ref_toplevel.choose(RefToplevel::Authority, r_authority, b_authority),
            path,
            query: ref_toplevel.choose(RefToplevel::Query, r_query, b_query),
            fragment: r_fragment,
            op: NormalizationOp {
                case_pct_normalization: false,
                whatwg_serialization: false,
            },
        }
        .into()
    }

    /// Creates a resolution task.
    ///
    /// The returned [`NormalizationTask`] allows you to resolve the IRI without
    /// memory allocation, resolve to existing buffers, estimate required
    /// memory size, etc. If you need more control than
    /// [`resolve_normalize`][`Self::resolve_normalize`] method, use this.
    ///
    /// The task returned by this method normalizes the resolution result.
    /// If you don't want to normalize the result, use
    /// [`create_task`][`Self::create_task`] instead.
    ///
    /// If you want to avoid resolution and normalization failure by using
    /// resolution described in WHATWG URL Standard, call
    /// [`NormalizationTask::enable_whatwg_serialization`] for the returned task.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug)] struct Error;
    /// # impl From<iri_string::validate::Error> for Error {
    /// #     fn from(e: iri_string::validate::Error) -> Self { Self } }
    /// # impl<T> From<iri_string::task::Error<T>> for Error {
    /// #     fn from(e: iri_string::task::Error<T>) -> Self { Self } }
    /// use iri_string::resolve::FixedBaseResolver;
    /// use iri_string::task::ProcessAndWrite;
    /// use iri_string::types::{IriAbsoluteStr, IriReferenceStr};
    ///
    /// # #[cfg(feature = "alloc")] {
    /// # // `ResolutionTask::allocate_and_write()` is available only when
    /// # // `alloc` feature is enabled.
    /// let base = IriAbsoluteStr::new("HTTP://example.COM/base/base2/")?;
    /// let resolver = FixedBaseResolver::new(base);
    ///
    /// let reference = IriReferenceStr::new("%2e%2e/../dot%2edot")?;
    /// let task = resolver.create_normalizing_task(reference);
    ///
    /// let resolved = task.allocate_and_write()?;
    /// // Not only resolved, but also normalized.
    /// assert_eq!(resolved, "http://example.com/dot.dot");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[must_use]
    pub fn create_normalizing_task(
        &self,
        reference: &'a RiReferenceStr<S>,
    ) -> NormalizationTask<'a, RiStr<S>> {
        let mut task = self.create_task(reference);
        task.enable_normalization();
        task
    }
}