iref 4.0.0

Uniform & Internationalized Resource Identifiers (URIs/IRIs), borrowed and owned.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
use core::fmt;
use std::ops::{Deref, Range};

use crate::PathContext;

use super::{InvalidPath, InvalidSegment, Path, PathBuf, Segment};

const CURRENT_SEGMENT: &[u8] = b".";

const PARENT_SEGMENT: &[u8] = b"..";

/// Stack size (in bytes) allocated for the [`PathMut::normalize`] method. If it
/// needs more space, it will allocate memory on the heap.
const NORMALIZE_IN_PLACE_BUFFER_LEN: usize = 512;

/// Mutable URI path reference.
///
/// This type allows in-place modification of a URI path within a larger
/// buffer, handling ambiguities that may arise during path manipulation.
///
/// # Example
///
/// ```rust
/// use iref::uri::PathBuf;
///
/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
/// path.as_path_mut().pop();
/// assert_eq!(path, "/foo");
/// ```
pub struct PathMut<'a> {
	/// Arbitrary byte buffer containing the path.
	buffer: &'a mut Vec<u8>,

	/// Path range.
	range: Range<usize>,

	context: PathContext,
}

impl<'a> Deref for PathMut<'a> {
	type Target = Path;

	fn deref(&self) -> &Self::Target {
		self.as_path()
	}
}

impl<'a> PathMut<'a> {
	/// Creates a new mutable path reference.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathMut;
	///
	/// let mut buffer = b"/foo/bar".to_vec();
	/// let path_mut = PathMut::new(&mut buffer, 0..8).unwrap();
	/// assert_eq!(path_mut.as_path(), "/foo/bar");
	/// ```
	pub fn new(
		buffer: &'a mut Vec<u8>,
		range: Range<usize>,
	) -> Result<Self, InvalidPath<&'a [u8]>> {
		if Path::validate_bytes(&buffer[range.clone()]) {
			Ok(unsafe { Self::new_unchecked(buffer, range) })
		} else {
			Err(InvalidPath(buffer))
		}
	}

	/// Creates a new mutable path reference.
	///
	/// # Safety
	///
	/// The buffer content between in the range `start..end` must be a valid
	/// IRI path.
	pub unsafe fn new_unchecked(buffer: &'a mut Vec<u8>, range: Range<usize>) -> Self {
		let context = PathContext::from_bytes(&buffer[..range.start]);

		Self {
			buffer,
			range,
			context,
		}
	}

	/// Creates a mutable path reference from a path buffer.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{PathBuf, PathMut};
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// let path_mut = PathMut::from_path(&mut path);
	/// assert_eq!(path_mut.as_path(), "/foo/bar");
	/// ```
	pub fn from_path(path: &'a mut PathBuf) -> Self {
		let buffer = unsafe {
			// Safe because `PathMut` preserves well formed paths.
			path.as_mut_vec()
		};
		let end = buffer.len();

		Self {
			buffer,
			range: 0..end,
			context: PathContext::default(),
		}
	}

	pub fn from_path_with_context(path: &'a mut PathBuf, context: PathContext) -> Self {
		assert!(!context.has_authority || path.is_absolute() || path.is_empty());

		let buffer = unsafe {
			// Safe because `PathMut` preserves well formed paths.
			path.as_mut_vec()
		};
		let end = buffer.len();

		Self {
			buffer,
			range: 0..end,
			context,
		}
	}

	/// Returns the path as a reference.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// assert_eq!(path.as_path_mut().as_path(), "/foo/bar");
	/// ```
	pub fn as_path(&self) -> &Path {
		unsafe { Path::new_unchecked_from_bytes(&self.buffer[self.range.clone()]) }
	}

	/// Returns the byte index where the first path segment begins.
	fn first_segment_offset(&self) -> usize {
		if self.is_absolute() {
			self.range.start + 1
		} else {
			self.range.start
		}
	}

	/// Add a segment at the end of the path.
	///
	/// Same as [`Self::push`] but does not interpret the `.` and `..`
	/// segments. They will be added literally to the path.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{PathBuf, Segment};
	///
	/// let mut path = PathBuf::new("/foo".to_string()).unwrap();
	/// path.as_path_mut().lazy_push(Segment::new("bar").unwrap());
	/// assert_eq!(path, "/foo/bar");
	///
	/// // It is possible to push empty segments.
	/// path.as_path_mut().lazy_push(Segment::new("").unwrap());
	/// assert_eq!(path, "/foo/bar/");
	/// path.as_path_mut().lazy_push(Segment::new("").unwrap());
	/// assert_eq!(path, "/foo/bar//");
	/// ```
	pub fn lazy_push(&mut self, segment: &super::Segment) -> &mut Self {
		let prepend_slash = !self.is_empty() || (self.context.has_authority && self.is_relative());
		let prepend_dot = self.is_empty()
			&& ((!self.context.has_scheme
				&& !self.context.has_authority
				&& segment.looks_like_scheme())
				|| segment.is_empty());

		let prefix: &[u8] = match (prepend_slash, prepend_dot) {
			(true, true) => b"/./",
			(true, false) => b"/",
			(false, true) => b"./",
			(false, false) => b"",
		};

		let i = self.range.end;
		let len = prefix.len() + segment.len();
		self.range.end += len;

		crate::utils::allocate_range(self.buffer, i..i, len);
		self.buffer[i..(i + prefix.len())].copy_from_slice(prefix);
		self.buffer[(i + prefix.len())..self.range.end].copy_from_slice(segment.as_bytes());

		self
	}

	/// Adds a segment at the end of the path.
	///
	/// Same as [`Self::lazy_push`] but accepts a `&str` instead of a
	/// [`&Segment`](super::Segment). Returns an error if the input
	/// string is not a valid path segment.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo".to_string()).unwrap();
	/// path.as_path_mut().try_lazy_push("bar").unwrap();
	/// assert_eq!(path, "/foo/bar");
	/// ```
	pub fn try_lazy_push<'s>(
		&mut self,
		segment: &'s str,
	) -> Result<&mut Self, super::InvalidSegment<&'s str>> {
		self.lazy_push(segment.try_into()?);
		Ok(self)
	}

	/// Push the given segment to this path using the `.` and `..` segments
	/// semantics.
	///
	/// Returns wether or not a special segment has been pushed and
	/// should be followed by an empty segment when doing reference
	/// resolution.
	#[inline]
	pub(crate) fn push_inner(&mut self, segment: &super::Segment) -> bool {
		match segment.as_bytes() {
			CURRENT_SEGMENT => true,
			PARENT_SEGMENT => {
				self.pop();
				true
			}
			_ => {
				if !segment.is_empty() || !self.is_empty() {
					self.lazy_push(segment);
				}

				false
			}
		}
	}

	/// Adds a segment at the end of the path.
	///
	/// # Ambiguities
	///
	/// Adding a segment to an empty path may introduce ambiguities in several
	/// cases. Here is how this function deals with those cases.
	///
	/// ## Empty segment
	///
	/// Adding an empty segment on an empty path may add ambiguity in two
	/// cases:
	/// 1. if the path is relative, adding a `/` would make the path
	///    absolute (e.g. `scheme:` becomes `scheme:/`) ;
	/// 2. if the path is absolute adding a `/` would add two empty segments
	///    (e.g. `scheme:/` becomes `scheme://`), and it may be confused with an
	///    authority part ;
	///
	/// To avoid such ambiguity, in both cases this function will add a `.`
	/// segment to the path, preserving its semantics:
	/// 1. `scheme:` becomes `scheme:./` instead of `scheme:/` ;
	/// 2. `scheme:/` becomes `scheme:/./` instead of `scheme://`.
	///
	/// ## Relative empty path with authority
	///
	/// If the path is empty, but an authority is present, the path is turned
	/// absolute so the segment is not concatenated to the authority.
	///
	/// ## Segment containing a `:`
	///
	/// If the path does not follow a scheme and/or authority part, a `:` in
	/// the first segment may be confused with a scheme separator
	/// (e.g. `looks-like-a-scheme:rest`).
	/// To avoid such ambiguity, this function will add a `.` segment to the
	/// path, preserving its semantics (e.g. `./looks-like-a-scheme:rest`).
	///
	/// ## `.` and `..`
	///
	/// This method will interpret `.` and `..` such that pushing `.`
	/// has no effect, and `..` is equivalent to [`Self::pop`].
	/// Use [`Self::lazy_push`] to not interpret those segments.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{PathBuf, Segment};
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().push(Segment::new("..").unwrap());
	/// assert_eq!(path, "/foo/");
	/// ```
	#[inline]
	pub fn push(&mut self, segment: &super::Segment) -> &mut Self {
		if self.push_inner(segment) && !self.is_empty() {
			self.lazy_push(super::Segment::EMPTY)
		} else {
			self
		}
	}

	/// Pushes the given segment to this path using the `.` and `..` segments
	/// semantics.
	///
	/// Same as [`Self::push`] but accepts a `&str` instead of
	/// a [`&Segment`](super::Segment). Returns an error if the input
	/// string is not a valid path segment.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_push("..").unwrap();
	/// assert_eq!(path, "/foo/");
	/// ```
	#[inline]
	pub fn try_push<'s>(
		&mut self,
		segment: &'s str,
	) -> Result<&mut Self, super::InvalidSegment<&'s str>> {
		Ok(self.push(segment.try_into()?))
	}

	/// Appends all segments to this path without interpreting `.` and `..`.
	///
	/// Same as [`Self::append`] but does not interpret the `.` and `..`
	/// segments. They will be added literally to the path.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{Path, PathBuf};
	///
	/// let mut path = PathBuf::new("/foo".to_string()).unwrap();
	/// path.as_path_mut().lazy_append(Path::new("bar/baz").unwrap());
	/// assert_eq!(path, "/foo/bar/baz");
	/// ```
	#[inline]
	pub fn lazy_append<'s, S: IntoIterator<Item = &'s Segment>>(&mut self, path: S) -> &mut Self {
		for s in path {
			self.lazy_push(s);
		}

		self
	}

	/// Appends all segments to this path without interpreting `.` and `..`.
	///
	/// Same as [`Self::lazy_append`], but accepts `&str` instead of
	/// [`&Segment`](super::Segment). Returns an error if one item is
	/// not a valid segment.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo".to_string()).unwrap();
	/// path.as_path_mut().try_lazy_append(["bar", "baz"]).unwrap();
	/// assert_eq!(path, "/foo/bar/baz");
	/// ```
	#[inline]
	pub fn try_lazy_append<'s, S: IntoIterator<Item = &'s str>>(
		&mut self,
		path: S,
	) -> Result<&mut Self, InvalidSegment<&'s str>> {
		for segment in path {
			self.try_lazy_push(segment)?;
		}

		Ok(self)
	}

	/// Append the given path to this path using the `.` and `..` segments semantics.
	///
	/// Note that this does not normalize the segments already in the path.
	/// For instance `'/a/b/.'.append('../')` will return `/a/b/` and not
	/// `a/` because the semantics of `..` is applied on the last `.` in the path.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{Path, PathBuf};
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().append(Path::new("../baz").unwrap());
	/// assert_eq!(path, "/foo/baz");
	/// ```
	#[inline]
	pub fn append<'s, S: IntoIterator<Item = &'s Segment>>(&mut self, path: S) -> &mut Self {
		let mut open = false;
		for segment in path {
			open = self.push_inner(segment);
		}

		if open && !self.is_empty() {
			self.lazy_push(super::Segment::EMPTY)
		} else {
			self
		}
	}

	/// Append the given path to this path using the `.` and `..` segments semantics.
	///
	/// Note that this does not normalize the segments already in the path.
	/// For instance `'/a/b/.'.try_append('../')` will return `/a/b/` and not
	/// `a/` because the semantics of `..` is applied on the last `.` in the path.
	///
	/// Same as [`Self::append`], but accepts `&str` instead of
	/// [`&Segment`](super::Segment). Returns an error if one item is
	/// not a valid segment.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_append(["baz", "qux"]).unwrap();
	/// assert_eq!(path, "/foo/bar/baz/qux");
	/// ```
	#[inline]
	pub fn try_append<'s, S: IntoIterator<Item = &'s str>>(
		&mut self,
		path: S,
	) -> Result<&mut Self, InvalidSegment<&'s str>> {
		let mut open = false;
		for segment in path {
			open = self.push_inner(segment.try_into()?);
		}

		if open && !self.is_empty() {
			Ok(self.lazy_push(Segment::EMPTY))
		} else {
			Ok(self)
		}
	}

	/// Joins this path to the given path.
	///
	/// If the input path is absolute, this is equivalent to
	/// [`Self::replace`]. If the input path is relative, this is
	/// equivalent to [`Self::append`].
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{Path, PathBuf};
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().join(Path::new("baz/qux").unwrap());
	/// assert_eq!(path, "/foo/bar/baz/qux");
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().join(Path::new("/baz").unwrap());
	/// assert_eq!(path, "/baz");
	/// ```
	pub fn join(&mut self, path: &Path) -> &mut Self {
		if path.is_absolute() {
			self.replace(path)
		} else {
			self.append(path)
		}
	}

	/// Joins this path to the given path.
	///
	/// Same as [`Self::join`] but accepts a `&str` instead of a
	/// [`&Path`](Path). Returns an error if the input string is not
	/// a valid path.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_join("baz/qux").unwrap();
	/// assert_eq!(path, "/foo/bar/baz/qux");
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_join("/baz").unwrap();
	/// assert_eq!(path, "/baz");
	/// ```
	pub fn try_join<'s>(&mut self, path: &'s str) -> Result<&mut Self, InvalidPath<&'s str>> {
		self.join(Path::new(path)?);
		Ok(self)
	}

	/// Pop the last non-`..` segment of the path.
	///
	/// If the path is empty and relative, or ends in `..`, then a `..` segment
	/// will be added instead.
	///
	/// Has no effect if the path is empty and absolute.
	/// Use [`Self::try_pop`] if you need to know if the path has been modified.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().pop();
	/// assert_eq!(path, "/foo");
	/// ```
	pub fn pop(&mut self) -> &mut Self {
		self.try_pop();
		self
	}

	/// Pop the last non-`..` segment of the path.
	///
	/// If the path is empty and relative, or ends in `..`, then a `..` segment
	/// will be added instead.
	///
	/// Returns `true` if the path has been modified, or `false` otherwise.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_pop();
	/// assert_eq!(path, "/foo");
	/// ```
	pub fn try_pop(&mut self) -> bool {
		let is_empty = self.is_empty();

		if (is_empty && self.is_relative()) || self.last() == Some(super::Segment::PARENT) {
			self.lazy_push(super::Segment::PARENT);
			true
		} else if !is_empty {
			let start = self.first_segment_offset();
			let mut i = self.range.end - 1;

			while i > start && self.buffer[i] != b'/' {
				i -= 1
			}

			crate::utils::replace(self.buffer, i..self.range.end, &[]);
			self.range.end = i;
			true
		} else {
			false
		}
	}

	/// Clears the path, removing all segments.
	///
	/// Keeps the path absolute if it was absolute.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().clear();
	/// assert_eq!(path, "/");
	/// ```
	pub fn clear(&mut self) -> &mut Self {
		let start = self.first_segment_offset();
		crate::utils::replace(self.buffer, start..self.range.end, b"");
		self.range.end = start;
		self
	}

	/// Replaces this path with the given path.
	///
	/// Handles ambiguities that may arise during replacement.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::{Path, PathBuf};
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().replace(Path::new("/baz/qux").unwrap());
	/// assert_eq!(path, "/baz/qux");
	/// ```
	pub fn replace(&mut self, path: &Path) -> &mut Self {
		// Determine disambiguation prefix.
		let prefix: &[u8] = if !self.context.has_authority && path.as_bytes().starts_with(b"//") {
			// AMBIGUITY: `http:old/path` → `http://new_path` would make
			//            `//new_path` look like an authority.
			b"/."
		} else if self.context.has_authority && !path.is_empty() && path.is_relative() {
			// VALIDITY: path must be absolute when an authority is present.
			b"/"
		} else if !self.context.has_scheme
			&& !self.context.has_authority
			&& path.looks_like_scheme()
		{
			// AMBIGUITY: `old/path` → `new:path` would make `new` look
			//            like a scheme.
			b"./"
		} else {
			b""
		};

		let i = self.range.start;
		let len = prefix.len() + path.len();
		crate::utils::allocate_range(self.buffer, self.range.start..self.range.end, len);
		self.buffer[i..(i + prefix.len())].copy_from_slice(prefix);
		self.buffer[(i + prefix.len())..(i + len)].copy_from_slice(path.as_bytes());
		self.range.end = self.range.start + len;

		self
	}

	/// Replaces this path with the given path.
	///
	/// Same as [`Self::replace`] but accepts a `&str` instead of a
	/// [`&Path`](Path). Returns an error if the input string is not
	/// a valid path.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar".to_string()).unwrap();
	/// path.as_path_mut().try_replace("/baz/qux").unwrap();
	/// assert_eq!(path, "/baz/qux");
	/// ```
	pub fn try_replace<'p>(&mut self, path: &'p str) -> Result<&mut Self, InvalidPath<&'p str>> {
		self.replace(Path::new(path)?);
		Ok(self)
	}

	/// Normalizes the path in place.
	///
	/// Resolves `.` and `..` segments using the usual path semantics.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::PathBuf;
	///
	/// let mut path = PathBuf::new("/foo/bar/../baz".to_string()).unwrap();
	/// path.as_path_mut().normalize();
	/// assert_eq!(path, "/foo/baz");
	/// ```
	#[inline]
	pub fn normalize(&mut self) -> &mut Self {
		let mut buffer: smallvec::SmallVec<[u8; NORMALIZE_IN_PLACE_BUFFER_LEN]> =
			smallvec::SmallVec::new();

		if self.is_absolute() {
			buffer.push(b'/')
		}

		for (i, segment) in self.normalized_segments().enumerate() {
			if i > 0 {
				buffer.push(b'/')
			}

			buffer.extend_from_slice(segment.as_bytes())
		}

		self.replace(unsafe { Path::new_unchecked_from_bytes(buffer.as_slice()) })
	}
}

impl<'a> fmt::Display for PathMut<'a> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		self.as_path().fmt(f)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::uri::{PathBuf, Segment};

	#[test]
	fn lazy_push() {
		let vectors: [(&str, &str, &str); _] = [
			("", "foo", "foo"),
			("/", "foo", "/foo"),
			("", "", "./"),
			("/", "", "/./"),
			("foo", "bar", "foo/bar"),
			("/foo", "bar", "/foo/bar"),
			("foo", "", "foo/"),
			("foo/bar", "", "foo/bar/"),
			("foo/", "", "foo//"),
			("a/b/c", "d", "a/b/c/d"),
			("/a/b/c", "d", "/a/b/c/d"),
			("a/b/c/", "d", "a/b/c//d"),
		];

		for (path, segment, expected) in vectors {
			let mut path = PathBuf::new(path.to_owned()).unwrap();
			let mut path_mut = PathMut::from_path(&mut path);
			let segment = Segment::new(&segment).unwrap();
			path_mut.lazy_push(segment);
			assert_eq!(path_mut.as_str(), expected)
		}
	}

	#[test]
	fn lazy_push_following_authority() {
		let vectors: [(&[u8], &[u8], &[u8]); _] = [
			(b"", b"foo", b"/foo"),
			(b"/", b"foo", b"/foo"),
			(b"", b"", b"/./"),
			(b"/", b"", b"/./"),
			(b"/foo", b"bar", b"/foo/bar"),
			(b"/a/b/c", b"d", b"/a/b/c/d"),
		];

		for (path, segment, expected) in vectors {
			let mut path = PathBuf::new(path.to_vec()).unwrap();
			let mut path_mut = PathMut::from_path_with_context(
				&mut path,
				PathContext {
					has_scheme: false,
					has_authority: true,
				},
			);
			let segment = Segment::new(&segment).unwrap();
			path_mut.lazy_push(segment);
			assert_eq!(path_mut.as_bytes(), expected)
		}
	}

	#[test]
	fn push() {
		let vectors: [(&str, &str, &str); _] =
			[("foo/bar", "..", "foo/"), ("foo/bar", ".", "foo/bar/")];

		for (path, segment, expected) in vectors {
			let mut path = PathBuf::new(path.to_owned()).unwrap();
			let mut path_mut = PathMut::from_path(&mut path);
			let segment = Segment::new(&segment).unwrap();
			path_mut.push(segment);
			assert_eq!(path_mut.as_str(), expected)
		}
	}

	#[test]
	fn append() {
		let vectors: [(&str, &str, &str); _] = [("foo/bar", "..", "foo/")];

		for (a, b, expected) in vectors {
			let mut a = PathBuf::new(a.to_owned()).unwrap();
			let mut a_mut = PathMut::from_path(&mut a);
			let b = Path::new(b).unwrap();
			a_mut.append(b.segments());
			assert_eq!(a_mut.as_str(), expected)
		}
	}

	#[test]
	fn replace() {
		let vectors = [
			("a", "foo", "foo"),
			("a/b", "//foo", "/.//foo"), // AMBIGUITY: may be confused with an authority.
			("a/b/c", "foo:bar", "./foo:bar"), // AMBIGUITY: may be confused with a scheme.
			("../", "/foo:bar", "/foo:bar"),
		];

		for (a, b, expected) in vectors {
			let mut path = PathBuf::new(a.to_owned()).unwrap();
			PathMut::from_path(&mut path).try_replace(b).unwrap();
			assert_eq!(path.as_str(), expected)
		}
	}

	#[test]
	fn replace_following_authority() {
		let vectors = [
			("", "foo", "/foo"), // AMBIGUITY: may be confused with (part of) the authority
			("/", "//foo", "//foo"),
		];

		for (a, b, expected) in vectors {
			let mut path = PathBuf::new(a.to_owned()).unwrap();
			PathMut::from_path_with_context(
				&mut path,
				PathContext {
					has_scheme: false,
					has_authority: true,
				},
			)
			.try_replace(b)
			.unwrap();
			assert_eq!(path.as_str(), expected)
		}
	}

	#[test]
	fn pop() {
		let vectors: [(&[u8], &[u8]); 6] = [
			(b"", b".."),
			(b"/", b"/"),
			(b"/..", b"/../.."),
			(b"foo", b""),
			(b"foo/bar", b"foo"),
			(b"foo/bar/", b"foo/bar"),
		];

		for (path, expected) in vectors {
			let mut path = PathBuf::new(path.to_vec()).unwrap();
			let mut path_mut = PathMut::from_path(&mut path);
			path_mut.pop();
			assert_eq!(path_mut.as_bytes(), expected)
		}
	}

	#[test]
	fn pop_following_authority() {
		let vectors: [(&[u8], &[u8]); _] = [(b"", b"/.."), (b"/", b"/"), (b"/..", b"/../..")];

		for (path, expected) in vectors {
			let mut path = PathBuf::new(path.to_vec()).unwrap();
			let mut path_mut = PathMut::from_path_with_context(
				&mut path,
				PathContext {
					has_scheme: false,
					has_authority: true,
				},
			);
			path_mut.pop();
			assert_eq!(path_mut.as_bytes(), expected)
		}
	}

	#[test]
	fn normalized() {
		let vectors: [(&str, &str); _] = [
			("", ""),
			("a/b/c", "a/b/c"),
			("a/..", ""),
			("a/b/..", "a/"),
			("a/b/../", "a/"),
			("a/b/c/..", "a/b/"),
			("a/b/c/.", "a/b/c/"),
			("a/../..", "../"),
			("/a/../..", "/"),
		];

		for (input, expected) in vectors {
			let mut path = PathBuf::new(input.to_owned()).unwrap();
			let mut path_mut = PathMut::from_path(&mut path);
			path_mut.normalize();
			assert_eq!(path_mut.as_str(), expected);
		}
	}
}