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
use static_regular_grammar::RegularGrammar;
use std::{
	borrow::{Borrow, Cow},
	hash::{self, Hash},
};

mod authority;
mod authority_mut;
mod fragment;
mod path;
mod path_mut;
mod query;
mod reference;
mod scheme;

pub use authority::*;
pub use authority_mut::*;
pub use fragment::*;
pub use path::*;
pub use path_mut::*;
pub use query::*;
pub use reference::*;
pub use scheme::*;

use crate::{
	common::{bytestr_eq, parse, RiBufImpl, RiImpl, RiRefBufImpl, RiRefImpl},
	Iri, IriBuf, IriRef, IriRefBuf,
};

macro_rules! uri_error {
	($($(#[$meta:meta])* $variant:ident : $ident:ident),*) => {
		#[derive(Debug, thiserror::Error)]
		pub enum UriError<T> {
			$(
				$(#[$meta])*
				$variant(#[from] $ident<T>)
			),*
		}

		$(
			impl<'a> From<$ident<String>> for UriError<Cow<'a, str>> {
				fn from($ident(value): $ident<String>) -> Self {
					Self::$variant($ident(Cow::Owned(value)))
				}
			}

			impl<'a> From<$ident<&'a str>> for UriError<Cow<'a, str>> {
				fn from($ident(value): $ident<&'a str>) -> Self {
					Self::$variant($ident(Cow::Borrowed(value)))
				}
			}

			impl<'a> From<$ident<Vec<u8>>> for UriError<Cow<'a, [u8]>> {
				fn from($ident(value): $ident<Vec<u8>>) -> Self {
					Self::$variant($ident(Cow::Owned(value)))
				}
			}

			impl<'a> From<$ident<&'a [u8]>> for UriError<Cow<'a, [u8]>> {
				fn from($ident(value): $ident<&'a [u8]>) -> Self {
					Self::$variant($ident(Cow::Borrowed(value)))
				}
			}
		)*
	};
}

uri_error! {
	#[error("invalid URI: {0}")]
	Uri: InvalidUri,

	#[error("invalid URI reference: {0}")]
	Reference: InvalidUriRef,

	#[error("invalid URI scheme: {0}")]
	Scheme: InvalidScheme,

	#[error("invalid URI authority: {0}")]
	Authority: InvalidAuthority,

	#[error("invalid URI authority user info: {0}")]
	UserInfo: InvalidUserInfo,

	#[error("invalid URI authority host: {0}")]
	Host: InvalidHost,

	#[error("invalid URI authority port: {0}")]
	Port: InvalidPort,

	#[error("invalid URI path: {0}")]
	Path: InvalidPath,

	#[error("invalid URI path segment: {0}")]
	PathSegment: InvalidSegment,

	#[error("invalid URI query: {0}")]
	Query: InvalidQuery,

	#[error("invalid URI fragment: {0}")]
	Fragment: InvalidFragment
}

/// Uniform Resource Identifier (URI).
#[derive(RegularGrammar)]
#[grammar(
	file = "src/uri/grammar.abnf",
	entry_point = "URI",
	ascii,
	cache = "automata/uri.aut.cbor"
)]
#[grammar(sized(UriBuf, derive(Debug, Display, PartialEq, Eq, PartialOrd, Ord, Hash)))]
#[cfg_attr(feature = "serde", grammar(serde))]
#[cfg_attr(feature = "ignore-grammars", grammar(disable))]
pub struct Uri([u8]);

impl RiRefImpl for Uri {
	type Authority = Authority;
	type Path = Path;
	type Query = Query;
	type Fragment = Fragment;

	type RiRefBuf = UriRefBuf;

	fn as_bytes(&self) -> &[u8] {
		&self.0
	}
}

impl RiImpl for Uri {}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UriParts<'a> {
	pub scheme: &'a Scheme,
	pub authority: Option<&'a Authority>,
	pub path: &'a Path,
	pub query: Option<&'a Query>,
	pub fragment: Option<&'a Fragment>,
}

impl Uri {
	pub fn parts(&self) -> UriParts {
		let bytes = self.as_bytes();
		let ranges = parse::parts(bytes, 0);

		UriParts {
			scheme: unsafe { Scheme::new_unchecked(&bytes[ranges.scheme]) },
			authority: ranges
				.authority
				.map(|r| unsafe { Authority::new_unchecked(&self.0[r]) }),
			path: unsafe { Path::new_unchecked(&self.0[ranges.path]) },
			query: ranges
				.query
				.map(|r| unsafe { Query::new_unchecked(&self.0[r]) }),
			fragment: ranges
				.fragment
				.map(|r| unsafe { Fragment::new_unchecked(&self.0[r]) }),
		}
	}

	/// Converts this URI into an URI reference.
	///
	/// All IRI are valid URI references.
	pub fn as_uri_ref(&self) -> &UriRef {
		unsafe { UriRef::new_unchecked(&self.0) }
	}

	pub fn as_iri(&self) -> &Iri {
		unsafe { Iri::new_unchecked(std::str::from_utf8_unchecked(&self.0)) }
	}

	pub fn as_iri_ref(&self) -> &IriRef {
		unsafe { IriRef::new_unchecked(std::str::from_utf8_unchecked(&self.0)) }
	}

	/// Returns the scheme of the URI.
	#[inline]
	pub fn scheme(&self) -> &Scheme {
		RiImpl::scheme(self)
	}

	/// Returns the authority part of the URI, if any.
	pub fn authority(&self) -> Option<&Authority> {
		RiRefImpl::authority(self)
	}

	/// Returns the path of the URI.
	pub fn path(&self) -> &Path {
		RiRefImpl::path(self)
	}

	pub fn query(&self) -> Option<&Query> {
		RiRefImpl::query(self)
	}

	pub fn fragment(&self) -> Option<&Fragment> {
		RiRefImpl::fragment(self)
	}

	/// Get this IRI relatively to the given IRI reference.
	///
	/// # Example
	/// ```
	/// # use iref::Uri;
	/// let a = Uri::new(b"https://crates.io/").unwrap();
	/// let b = Uri::new(b"https://crates.io/crates/iref").unwrap();
	/// let c = Uri::new(b"https://crates.io/crates/json-ld").unwrap();
	/// assert_eq!(b.relative_to(a.as_uri_ref()), "crates/iref");
	/// assert_eq!(a.relative_to(b.as_uri_ref()), "..");
	/// assert_eq!(b.relative_to(c.as_uri_ref()), "iref");
	/// assert_eq!(c.relative_to(b.as_uri_ref()), "json-ld");
	/// ```
	pub fn relative_to(&self, other: &(impl ?Sized + AsRef<UriRef>)) -> UriRefBuf {
		self.as_uri_ref().relative_to(other)
	}

	/// Get the suffix of this URI, if any, with regard to the given prefix URI.
	///
	/// Returns `Some((suffix, query, fragment))` if this URI is of the form
	/// `prefix/suffix?query#fragment` where `prefix` is given as parameter.
	/// Returns `None` otherwise.
	/// If the `suffix` scheme or authority is different from this path, it will return `None`.
	///
	/// See [`Path::suffix`] for more details.
	#[inline]
	pub fn suffix(
		&self,
		prefix: &(impl ?Sized + AsRef<Uri>),
	) -> Option<(PathBuf, Option<&Query>, Option<&Fragment>)> {
		RiRefImpl::suffix(self, prefix.as_ref())
	}

	/// The URI without the file name, query and fragment.
	///
	/// # Example
	/// ```
	/// # use iref::Uri;
	/// let a = Uri::new(b"https://crates.io/crates/iref?query#fragment").unwrap();
	/// let b = Uri::new(b"https://crates.io/crates/iref/?query#fragment").unwrap();
	/// assert_eq!(a.base(), "https://crates.io/crates/");
	/// assert_eq!(b.base(), "https://crates.io/crates/iref/")
	/// ```
	#[inline]
	pub fn base(&self) -> &Self {
		unsafe { Self::new_unchecked(RiRefImpl::base(self)) }
	}
}

impl AsRef<UriRef> for Uri {
	fn as_ref(&self) -> &UriRef {
		self.as_uri_ref()
	}
}

impl AsRef<Iri> for Uri {
	fn as_ref(&self) -> &Iri {
		self.as_iri()
	}
}

impl AsRef<IriRef> for Uri {
	fn as_ref(&self) -> &IriRef {
		self.as_iri_ref()
	}
}

impl Borrow<UriRef> for Uri {
	fn borrow(&self) -> &UriRef {
		self.as_uri_ref()
	}
}

impl Borrow<Iri> for Uri {
	fn borrow(&self) -> &Iri {
		self.as_iri()
	}
}

impl Borrow<IriRef> for Uri {
	fn borrow(&self) -> &IriRef {
		self.as_iri_ref()
	}
}

bytestr_eq!(Uri);

impl PartialEq for Uri {
	fn eq(&self, other: &Self) -> bool {
		self.parts() == other.parts()
	}
}

impl<'a> PartialEq<&'a Uri> for Uri {
	fn eq(&self, other: &&'a Self) -> bool {
		*self == **other
	}
}

impl PartialEq<UriBuf> for Uri {
	fn eq(&self, other: &UriBuf) -> bool {
		*self == *other.as_uri()
	}
}

impl PartialEq<UriRef> for Uri {
	fn eq(&self, other: &UriRef) -> bool {
		*self.as_uri_ref() == *other
	}
}

impl<'a> PartialEq<&'a UriRef> for Uri {
	fn eq(&self, other: &&'a UriRef) -> bool {
		*self.as_uri_ref() == **other
	}
}

impl PartialEq<UriRefBuf> for Uri {
	fn eq(&self, other: &UriRefBuf) -> bool {
		*self.as_uri_ref() == *other.as_uri_ref()
	}
}

impl Eq for Uri {}

impl PartialOrd for Uri {
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl<'a> PartialOrd<&'a Uri> for Uri {
	fn partial_cmp(&self, other: &&'a Self) -> Option<std::cmp::Ordering> {
		self.partial_cmp(*other)
	}
}

impl PartialOrd<UriBuf> for Uri {
	fn partial_cmp(&self, other: &UriBuf) -> Option<std::cmp::Ordering> {
		self.partial_cmp(other.as_uri())
	}
}

impl PartialOrd<UriRef> for Uri {
	fn partial_cmp(&self, other: &UriRef) -> Option<std::cmp::Ordering> {
		self.as_uri_ref().partial_cmp(other)
	}
}

impl<'a> PartialOrd<&'a UriRef> for Uri {
	fn partial_cmp(&self, other: &&'a UriRef) -> Option<std::cmp::Ordering> {
		self.as_uri_ref().partial_cmp(*other)
	}
}

impl PartialOrd<UriRefBuf> for Uri {
	fn partial_cmp(&self, other: &UriRefBuf) -> Option<std::cmp::Ordering> {
		self.partial_cmp(other.as_uri_ref())
	}
}

impl Ord for Uri {
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.parts().cmp(&other.parts())
	}
}

impl Hash for Uri {
	fn hash<H: hash::Hasher>(&self, state: &mut H) {
		self.parts().hash(state)
	}
}

impl RiRefImpl for UriBuf {
	type Authority = Authority;
	type Path = Path;
	type Query = Query;
	type Fragment = Fragment;

	type RiRefBuf = UriRefBuf;

	fn as_bytes(&self) -> &[u8] {
		&self.0
	}
}

impl RiImpl for UriBuf {}

impl RiRefBufImpl for UriBuf {
	type Ri = Uri;
	type RiBuf = Self;

	unsafe fn new_unchecked(bytes: Vec<u8>) -> Self {
		Self::new_unchecked(bytes)
	}

	unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
		&mut self.0
	}

	fn into_bytes(self) -> Vec<u8> {
		self.0
	}
}

impl RiBufImpl for UriBuf {}

impl UriBuf {
	pub fn from_scheme(scheme: SchemeBuf) -> Self {
		RiBufImpl::from_scheme(scheme)
	}

	pub fn into_uri_ref(self) -> UriRefBuf {
		unsafe { UriRefBuf::new_unchecked(self.0) }
	}

	pub fn into_iri(self) -> IriBuf {
		unsafe { IriBuf::new_unchecked(String::from_utf8_unchecked(self.0)) }
	}

	pub fn into_iri_ref(self) -> IriRefBuf {
		unsafe { IriRefBuf::new_unchecked(String::from_utf8_unchecked(self.0)) }
	}

	/// Returns a mutable reference to the underlying `Vec<u8>` buffer
	/// representing the URI.
	///
	/// # Safety
	///
	/// The caller must ensure that once the mutable reference is dropped, its
	/// content is still a valid URI.
	pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
		&mut self.0
	}

	pub fn path_mut(&mut self) -> PathMut {
		PathMut::from_impl(RiRefBufImpl::path_mut(self))
	}

	pub fn authority_mut(&mut self) -> Option<AuthorityMut> {
		RiRefBufImpl::authority_mut(self).map(AuthorityMut::from_impl)
	}

	/// Sets the scheme part.
	///
	/// # Example
	///
	/// ```
	/// use iref::{UriBuf, uri::Scheme};
	///
	/// let mut a = UriBuf::new(b"http://example.org/path".to_vec()).unwrap();
	/// a.set_scheme(Scheme::new(b"https").unwrap());
	/// assert_eq!(a, b"https://example.org/path");
	/// ```
	pub fn set_scheme(&mut self, new_scheme: &Scheme) {
		RiBufImpl::set_scheme(self, new_scheme)
	}

	/// Sets the authority part.
	///
	/// If the path is relative, this also turns it into an absolute path,
	/// since an authority cannot be followed by a relative path.
	///
	/// To avoid any ambiguity, if `authority` is `None` and the path starts
	/// with `//`, it will be changed into `/.//` as to not be interpreted as
	/// an authority part.
	///
	/// # Example
	///
	/// ```
	/// use iref::{UriBuf, uri::Authority};
	///
	/// let mut a = UriBuf::new(b"scheme:/path".to_vec()).unwrap();
	/// a.set_authority(Some(Authority::new(b"example.org").unwrap()));
	/// assert_eq!(a, b"scheme://example.org/path");
	///
	/// // When an authority is added before a relative path,
	/// // the path becomes absolute.
	/// let mut b = UriBuf::new(b"scheme:path".to_vec()).unwrap();
	/// b.set_authority(Some(Authority::new(b"example.org").unwrap()));
	/// assert_eq!(b, b"scheme://example.org/path");
	///
	/// // When an authority is removed and the path starts with `//`,
	/// // a `/.` prefix is added to the path to avoid any ambiguity.
	/// let mut c = UriBuf::new(b"scheme://example.org//path".to_vec()).unwrap();
	/// c.set_authority(None);
	/// assert_eq!(c, b"scheme:/.//path");
	/// ```
	pub fn set_authority(&mut self, authority: Option<&Authority>) {
		RiRefBufImpl::set_authority(self, authority)
	}

	/// Sets the path part.
	///
	/// If there is an authority and the path is relative, this also turns it
	/// into an absolute path, since an authority cannot be followed by a
	/// relative path.
	///
	/// To avoid any ambiguity, if there is no authority and the path starts
	/// with `//`, it will be changed into `/.//` as to not be interpreted as
	/// an authority part. Similarly if there is no scheme nor authority and the
	/// beginning of the new path looks like a scheme, it is prefixed with `./`
	/// to not be confused with a scheme.
	///
	/// # Example
	///
	/// ```
	/// use iref::{UriBuf, uri::Path};
	///
	/// let mut a = UriBuf::new(b"http://example.org/old/path".to_vec()).unwrap();
	/// a.set_path(Path::new(b"/foo/bar").unwrap());
	/// assert_eq!(a, b"http://example.org/foo/bar");
	///
	/// // If there is an authority and the new path is relative,
	/// // it is turned into an absolute path.
	/// let mut b = UriBuf::new(b"http://example.org/old/path".to_vec()).unwrap();
	/// b.set_path(Path::new(b"relative/path").unwrap());
	/// assert_eq!(b, b"http://example.org/relative/path");
	///
	/// // If there is no authority and the path starts with `//`,
	/// // it is prefixed with `/.` to avoid being confused with an authority.
	/// let mut c = UriBuf::new(b"http:old/path".to_vec()).unwrap();
	/// c.set_path(Path::new(b"//foo/bar").unwrap());
	/// assert_eq!(c, b"http:/.//foo/bar");
	/// ```
	pub fn set_path(&mut self, path: &Path) {
		RiRefBufImpl::set_path(self, path)
	}

	/// Sets the query part.
	pub fn set_query(&mut self, query: Option<&Query>) {
		RiRefBufImpl::set_query(self, query)
	}

	/// Sets the fragment part.
	pub fn set_fragment(&mut self, fragment: Option<&Fragment>) {
		RiRefBufImpl::set_fragment(self, fragment)
	}
}

impl AsRef<UriRef> for UriBuf {
	fn as_ref(&self) -> &UriRef {
		self.as_uri_ref()
	}
}

impl AsRef<Iri> for UriBuf {
	fn as_ref(&self) -> &Iri {
		self.as_iri()
	}
}

impl AsRef<IriRef> for UriBuf {
	fn as_ref(&self) -> &IriRef {
		self.as_iri_ref()
	}
}

impl Borrow<UriRef> for UriBuf {
	fn borrow(&self) -> &UriRef {
		self.as_uri_ref()
	}
}

impl Borrow<Iri> for UriBuf {
	fn borrow(&self) -> &Iri {
		self.as_iri()
	}
}

impl Borrow<IriRef> for UriBuf {
	fn borrow(&self) -> &IriRef {
		self.as_iri_ref()
	}
}

impl From<UriBuf> for UriRefBuf {
	fn from(value: UriBuf) -> Self {
		value.into_uri_ref()
	}
}

bytestr_eq!(UriBuf);

impl PartialEq<UriRef> for UriBuf {
	fn eq(&self, other: &UriRef) -> bool {
		*self.as_uri_ref() == *other
	}
}

impl<'a> PartialEq<&'a UriRef> for UriBuf {
	fn eq(&self, other: &&'a UriRef) -> bool {
		*self.as_uri_ref() == **other
	}
}

impl PartialEq<UriRefBuf> for UriBuf {
	fn eq(&self, other: &UriRefBuf) -> bool {
		*self.as_uri_ref() == *other.as_uri_ref()
	}
}

impl PartialOrd<UriRef> for UriBuf {
	fn partial_cmp(&self, other: &UriRef) -> Option<std::cmp::Ordering> {
		self.as_uri_ref().partial_cmp(other)
	}
}

impl<'a> PartialOrd<&'a UriRef> for UriBuf {
	fn partial_cmp(&self, other: &&'a UriRef) -> Option<std::cmp::Ordering> {
		self.as_uri_ref().partial_cmp(*other)
	}
}

impl PartialOrd<UriRefBuf> for UriBuf {
	fn partial_cmp(&self, other: &UriRefBuf) -> Option<std::cmp::Ordering> {
		self.as_uri_ref().partial_cmp(other.as_uri_ref())
	}
}