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
use crate::error::{Error as IriError, ErrorKind, Result as IriResult}; use crate::{Authority, Fragment, Normalize, Path, Port, Query, Scheme}; use regex::Regex; use std::convert::TryFrom; use std::fmt::{Display, Formatter}; use std::path::PathBuf; use std::str::FromStr; use std::sync::Arc; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ /// /// The IRI type comprised of [`Scheme`](scheme/struct.Scheme.html), /// [`Authority`](authority/struct.Authority.html), [`Path`](path/struct.Path.html), /// [`Query`](query/struct.Query.html), and [`Fragment`](fragment/struct.Fragment.html) components. /// Note that for most APIs the use of [`IRIRef`](type.IRIRef.html) is preferred over `IRI` directly. /// /// # Example /// /// The following example creates a new `IRI` from a string, but also then uses that as a template /// to create an additional one. The `normalize` method in this example will convert the host name /// to lower case. The `without_query` method creates a new IRI with all components _except_ the /// query copied over. /// /// ```rust,no_run /// use rdftk_iri::{IRI, Normalize}; /// use std::str::FromStr; /// /// let iri = IRI::from_str( /// "https://john.doe@www.EXAMPLE.com:123/forum/questions/?tag=networking&order=newest#top", /// ).unwrap(); /// /// let new_uri = iri.normalize().unwrap().without_query(); /// ``` /// /// # Definitions (from Wikipedia) /// /// Each URI begins with a scheme name that refers to a specification for assigning identifiers /// within that scheme. As such, the URI syntax is a federated and extensible naming system wherein /// each scheme's specification may further restrict the syntax and semantics of identifiers using /// that scheme. The URI generic syntax is a superset of the syntax of all URI schemes. It was /// first defined in RFC 2396, and finalized in RFC 3986. /// /// The URI generic syntax consists of a hierarchical sequence of five components:[8] /// /// > `URI = scheme:[//authority]path[?query][#fragment]` /// /// where the authority component divides into three subcomponents: /// /// > `authority = [userinfo@]host[:port]` /// /// The URI comprises: /// /// * A non-empty **scheme** component followed by a colon (:), consisting of a sequence of characters /// beginning with a letter and followed by any combination of letters, digits, plus (+), period /// (.), or hyphen (-). Although schemes are case-insensitive, the canonical form is lowercase /// and documents that specify schemes must do so with lowercase letters. Examples of popular /// schemes include http, https, ftp, mailto, file, data, and irc. URI schemes should be /// registered with the Internet Assigned Numbers Authority (IANA), although non-registered /// schemes are used in practice. /// * An optional **authority** component preceded by two slashes (//), comprising: /// * An optional **userinfo** subcomponent that may consist of a user name and an optional password /// preceded by a colon (:), followed by an at symbol (@). Use of the format username:password /// in the userinfo subcomponent is deprecated for security reasons. Applications should not /// render as clear text any data after the first colon (:) found within a userinfo subcomponent /// unless the data after the colon is the empty string (indicating no password). /// * A **host** subcomponent, consisting of either a registered name (including but not limited to a /// hostname), or an IP address. IPv4 addresses must be in dot-decimal notation, and IPv6 /// addresses must be enclosed in brackets ([]). /// * An optional **port** subcomponent preceded by a colon (:). /// * A **path** component, consisting of a sequence of path segments separated by a slash (/). A /// path is always defined for a URI, though the defined path may be empty (zero length). A /// segment may also be empty, resulting in two consecutive slashes (//) in the path component. A /// path component may resemble or map exactly to a file system path, but does not always imply a /// relation to one. If an authority component is present, then the path component must either be /// empty or begin with a slash (/). If an authority component is absent, then the path cannot /// begin with an empty segment, that is with two slashes (//), as the following characters would /// be interpreted as an authority component. The final segment of the path may be referred to as /// a 'slug'. /// * An optional **query** component preceded by a question mark (?), containing a query string of /// non-hierarchical data. Its syntax is not well defined, but by convention is most often a /// sequence of attribute–value pairs separated by a delimiter. /// * An optional **fragment** component preceded by a hash (#). The fragment contains a fragment /// identifier providing direction to a secondary resource, such as a section heading in an /// article identified by the remainder of the URI. When the primary resource is an HTML document, /// the fragment is often an id attribute of a specific element, and web browsers will scroll this /// element into view. /// /// Strings of data octets within a URI are represented as characters. Permitted characters within a /// URI are the ASCII characters[*] for the lowercase and uppercase letters of the modern English /// alphabet, the Arabic numerals, hyphen, period, underscore, and tilde. Octets represented by any /// other character must be percent-encoded. /// /// Of the ASCII character set, the characters : / ? # [ ] @ are reserved for use as delimiters of /// the generic URI components and must be percent-encoded – for example, %3F for a question mark. /// The characters ! $ & ' ( ) * + , ; = are permitted by generic URI syntax to be used unencoded in /// the user information, host, and path as delimiters. Additionally, : and @ may appear /// unencoded within the path, query, and fragment; and ? and / may appear unencoded as data within /// the query or fragment. /// /// [*] While URIs are limited to a subset of the ASCII character set, IRIs may additionally contain /// most characters from the Universal Character Set (Unicode/ISO 10646), including Chinese, /// Japanese, Korean, and Cyrillic characters. /// #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct IRI { scheme: Option<Scheme>, authority: Option<Authority>, path: Path, query: Option<Query>, fragment: Option<Fragment>, } /// /// A preferred reference-counted type to wrap an `IRI`. For RDF where IRIs are extensively reused /// as graph nodes, the requirement to use a reference type is very important to reduce duplication. /// /// As such, the APIs across the RDFtk crates use `IRIRef` exclusively. /// #[allow(clippy::upper_case_acronyms)] pub type IRIRef = Arc<IRI>; // ------------------------------------------------------------------------------------------------ // Implementations // ------------------------------------------------------------------------------------------------ impl Default for IRI { fn default() -> Self { Self::new(&Path::default()) } } impl Display for IRI { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "{}{}", match &self.scheme { None => String::new(), Some(scheme) => scheme.to_string(), }, &self.scheme_specific_part() ) } } impl FromStr for IRI { type Err = IriError; fn from_str(s: &str) -> Result<Self, Self::Err> { parse_iri(s) } } impl From<Path> for IRI { fn from(path: Path) -> Self { Self::from(&path) } } impl From<&Path> for IRI { fn from(path: &Path) -> Self { Self::new(path) } } #[cfg(feature = "path_iri")] impl TryFrom<PathBuf> for IRI { type Error = IriError; fn try_from(path: PathBuf) -> Result<Self, Self::Error> { Self::try_from(&path) } } #[cfg(feature = "path_iri")] impl TryFrom<&PathBuf> for IRI { type Error = IriError; fn try_from(path: &PathBuf) -> Result<Self, Self::Error> { Self::new_file(path) } } #[cfg(feature = "uuid_iri")] impl TryFrom<uuid::Uuid> for IRI { type Error = IriError; fn try_from(path: uuid::Uuid) -> Result<Self, Self::Error> { Self::try_from(&path) } } #[cfg(feature = "uuid_iri")] impl TryFrom<&uuid::Uuid> for IRI { type Error = IriError; fn try_from(path: &uuid::Uuid) -> Result<Self, Self::Error> { Self::new_name("uuid", &path.to_hyphenated().to_string()) } } impl Normalize for IRI { fn normalize(self) -> IriResult<Self> { let scheme = match &self.scheme { None => None, Some(scheme) => Some(scheme.clone().normalize()?), }; let authority = match &self.authority { None => None, Some(authority) => { let mut authority = authority.clone().normalize()?; if self.has_scheme() && !authority.has_port() { let scheme = self.scheme().as_ref().unwrap(); let scheme = scheme.clone().normalize().unwrap(); if let Some(port) = Port::default_for(&scheme) { authority.set_port(port); } } Some(authority) } }; let mut path = self.path.normalize()?; if let Some(scheme) = &scheme { if vec!["file", "ftp", "http", "https", "tftp"].contains(&scheme.value().as_str()) && path.is_empty() { path = Path::root(); } } let query = match self.query { None => None, Some(query) => Some(query.normalize()?), }; let fragment = match self.fragment { None => None, Some(fragment) => Some(fragment.normalize()?), }; Ok(Self { scheme, authority, path, query, fragment, }) } } impl IRI { /// /// Create a new `IRI` with only the specified path, this is a valid relative value /// -- see [is_absolute](#method.is_absolute). /// /// This is also provided as an implementation of `From<&Path>` and `From<Path>` for `IRI`. /// /// # Example /// /// ```rust /// use rdftk_iri::{IRI, Path}; /// use std::str::FromStr; /// /// let iri = IRI::new( /// &Path::from_str("/forum/questions/").unwrap() /// ); /// ``` /// pub fn new(path: &Path) -> Self { Self { scheme: None, authority: None, path: path.clone(), query: None, fragment: None, } } /// /// Construct a new `IRI` with the "file" scheme and the provided file system path. /// /// This is also provided as an implementation of `TryFrom<&PathBuf>` and `TryFrom<PathBuf>` /// for `IRI` if the "path_iri" feature has been enabled. /// /// # Example /// /// ```rust /// use rdftk_iri::IRI; /// use std::path::PathBuf; /// /// let iri = IRI::new_file(&PathBuf::from("Documents/test-plan.md")).unwrap(); /// ``` /// /// This results in the `IRI` `file://Documents/test-plan.md`. /// #[allow(clippy::ptr_arg)] pub fn new_file(path: &PathBuf) -> IriResult<Self> { Ok(Self { scheme: Some(Scheme::file()), authority: None, path: Path::from_str(&path.to_string_lossy().to_string())?, query: None, fragment: None, }) } /// /// Construct a new URN `IRI` with the given namespace identifier and namespace-specific /// string. /// /// # Example /// /// ```rust /// use rdftk_iri::IRI; /// /// let iri = IRI::new_name("uuid", "f3b4958c-52a1-11e7-802a-010203040506").unwrap(); /// ``` /// /// This results in the `IRI` `urn:uuid:f3b4958c-52a1-11e7-802a-010203040506`. /// pub fn new_name( namespace_identifier: &str, namespace_specific_string: &str, ) -> IriResult<Self> { Ok(Self { scheme: Some(Scheme::urn()), authority: None, path: Path::from_str(&format!( "{}:{}", namespace_identifier, namespace_specific_string ))?, query: None, fragment: None, }) } // -------------------------------------------------------------------------------------------- /// /// Return a new `IRI` as a copy of `self` with the path component replaced by the provided /// `path` value. /// pub fn with_new_path(&self, path: Path) -> Self { Self { path, ..self.clone() } } /// /// Return a new `IRI` as a copy of `self` with the path component replaced with the value of /// `Path::default()`. /// pub fn without_path(&self) -> Self { Self { path: Path::default(), ..self.clone() } } /// /// Return a new `IRI` as a copy of `self` with the query component replaced by the provided /// `query` value. /// pub fn with_new_query(&self, query: Query) -> Self { Self { query: Some(query), ..self.clone() } } /// /// Return a new `IRI` as a copy of `self` with the query component removed. /// pub fn without_query(&self) -> Self { Self { query: None, ..self.clone() } } /// /// Return a new `IRI` as a copy of `self` with the fragment component replaced by the provided /// `fragment` value. /// pub fn with_new_fragment(&self, fragment: Fragment) -> Self { Self { fragment: Some(fragment), ..self.clone() } } /// /// Return a new `IRI` as a copy of `self` with the fragment component removed. /// pub fn without_fragment(&self) -> Self { Self { fragment: None, ..self.clone() } } // -------------------------------------------------------------------------------------------- /// /// Resolves the `IRI` value `relative` using `self` as the base. /// /// If the given URI is already absolute, or if this URI is opaque, then the given URI is /// returned. Otherwise this method constructs a new hierarchical URI in a manner consistent /// with RFC 2396, §5.2;. /// pub fn resolve(&self, relative: &IRI) -> IriResult<Self> { if relative.is_absolute() || self.is_opaque() { Ok(relative.clone()) } else if !relative.has_scheme() && !relative.has_authority() && relative.path().is_empty() && !relative.has_query() && relative.has_fragment() { Ok(self.with_new_fragment(relative.fragment().as_ref().unwrap().clone())) } else { // Otherwise construct a new hierarchical URI in a manner consistent with RFC 2396, section 5.2. unimplemented!() } } /// /// Relativizes the `IRI` `other` against this `IRI`. /// /// The relativization of the `IRI` `other` against this `IRI` is computed as follows: /// /// 1. If either this `IRI` or the given `IRI` are opaque, or if the scheme and authority /// components of the two `IRI`s are not identical, or if the path of this `IRI` is not a /// prefix of the path of the given `IRI`, then the given `IRI` is returned. /// 2. Otherwise a new relative hierarchical `IRI` is constructed with query and fragment /// components taken from the given `IRI` and with a path component computed by removing /// this `IRI`'s path from the beginning of the given `IRI`'s path. /// pub fn relativize(&self, _other: &IRIRef) -> IriResult<Self> { unimplemented!() } // -------------------------------------------------------------------------------------------- /// /// Returns `true` if this is an absolute `IRI`, else `false`. An `IRI` is absolute if, and only /// if, it has a scheme component and does not have a fragment component. /// /// # Examples /// /// ```rust /// # use rdftk_iri::IRI; /// # use std::str::FromStr; /// assert!(IRI::from_str("mailto:a@b.com").unwrap().is_absolute()); /// assert!(IRI::from_str("http://example.com").unwrap().is_absolute()); /// assert!(IRI::from_str("http://example.com/path").unwrap().is_absolute()); /// assert!(IRI::from_str("scheme://example.com").unwrap().is_absolute()); /// assert!(IRI::from_str("scheme:example.com").unwrap().is_absolute()); /// assert!(IRI::from_str("scheme:example.com/path").unwrap().is_absolute()); /// /// assert!(!IRI::from_str("//example.com/path#foo").unwrap().is_absolute()); /// assert!(!IRI::from_str("http://example.com/path#foo").unwrap().is_absolute()); /// assert!(!IRI::from_str("scheme:example.com#foo").unwrap().is_absolute()); /// assert!(!IRI::from_str("path").unwrap().is_absolute()); /// assert!(!IRI::from_str("/path").unwrap().is_absolute()); /// ``` /// pub fn is_absolute(&self) -> bool { self.has_scheme() && !self.has_fragment() } /// /// Returns `true` if this is a relative `IRI` reference, else `false`. An `IRI` is a relative /// reference if, and only if, it does not have a scheme component. /// /// # Examples /// /// ```rust /// # use rdftk_iri::IRI; /// # use std::str::FromStr; /// assert!(IRI::from_str("//example.com/path#foo").unwrap().is_relative_reference()); /// assert!(IRI::from_str("path").unwrap().is_relative_reference()); /// assert!(IRI::from_str("/path").unwrap().is_relative_reference()); /// /// assert!(!IRI::from_str("mailto:a@b.com").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("http://example.com").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("http://example.com/path").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("scheme://example.com").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("scheme:example.com").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("scheme:example.com/path").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("http://example.com/path#foo").unwrap().is_relative_reference()); /// assert!(!IRI::from_str("scheme:example.com#foo").unwrap().is_relative_reference()); /// ``` /// pub fn is_relative_reference(&self) -> bool { !self.has_scheme() } /// /// Returns `true` if this is an opaque `IRI`, else `false`. An `IRI` is opaque if, and only if, i /// t is absolute and its scheme-specific part does not begin with a slash character ('/'). An /// opaque `IRI` has a scheme, a scheme-specific part, and possibly a fragment; all other /// components are undefined. /// /// # Examples /// /// ```rust /// # use rdftk_iri::IRI; /// # use std::str::FromStr; /// assert!(IRI::from_str("mailto:a@b.com").unwrap().is_opaque()); /// assert!(IRI::from_str("scheme:example.com").unwrap().is_opaque()); /// assert!(IRI::from_str("scheme:example.com/path").unwrap().is_opaque()); /// /// assert!(!IRI::from_str("http://example.com").unwrap().is_opaque()); /// assert!(!IRI::from_str("http://example.com/path").unwrap().is_opaque()); /// assert!(!IRI::from_str("scheme://example.com").unwrap().is_opaque()); /// assert!(!IRI::from_str("path").unwrap().is_opaque()); /// assert!(!IRI::from_str("/path").unwrap().is_opaque()); /// ``` /// pub fn is_opaque(&self) -> bool { let ssp = self.scheme_specific_part(); self.is_absolute() && !ssp.is_empty() && !ssp.starts_with('/') } // -------------------------------------------------------------------------------------------- /// Return `true` if this `IRI` include a scheme, else `false`. pub fn has_scheme(&self) -> bool { self.scheme.is_some() } /// Return the current value of the scheme component. pub fn scheme(&self) -> &Option<Scheme> { &self.scheme } /// Return the scheme-specific part of the `IRI`, basically any part of the `IRI` that isn't /// the scheme itself. pub fn scheme_specific_part(&self) -> String { format!( "{}{}{}{}", match &self.authority { None => String::new(), Some(authority) => authority.to_string(), }, &self.path.to_string(), match &self.query { None => String::new(), Some(query) => query.to_string(), }, match &self.fragment { None => String::new(), Some(fragment) => fragment.to_string(), }, ) } /// Return `true` if this `IRI` include a authority, else `false`. pub fn has_authority(&self) -> bool { self.authority.is_some() } /// Return the current value of the authority component. pub fn authority(&self) -> &Option<Authority> { &self.authority } /// Return `true` if this `IRI` include a path, else `false`. pub fn has_path(&self) -> bool { !self.path.is_empty() } /// Return the current value of the path component. pub fn path(&self) -> &Path { &self.path } /// Return `true` if this `IRI` include a query, else `false`. pub fn has_query(&self) -> bool { self.query.is_some() } /// Return the current value of the query component. pub fn query(&self) -> &Option<Query> { &self.query } /// Return `true` if this `IRI` include a fragment, else `false`. pub fn has_fragment(&self) -> bool { self.fragment.is_some() } /// Return the current value of the fragment component. pub fn fragment(&self) -> &Option<Fragment> { &self.fragment } // -------------------------------------------------------------------------------------------- /// Set the value of the scheme component. pub fn set_scheme(&mut self, scheme: Option<Scheme>) { self.scheme = scheme; } /// Set the value of the authority component. pub fn set_authority(&mut self, authority: Option<Authority>) { self.authority = authority; } /// Set the value of the path component. pub fn set_path(&mut self, path: Path) { self.path = path; } /// Set the value of the query component. pub fn set_query(&mut self, query: Option<Query>) { self.query = query; } /// Set the value of the fragment component. pub fn set_fragment(&mut self, fragment: Option<Fragment>) { self.fragment = fragment; } } // ------------------------------------------------------------------------------------------------ // Private Functions // ------------------------------------------------------------------------------------------------ const GRP_SCHEME: usize = 2; const GRP_AUTHORITY: usize = 4; const GRP_PATH: usize = 5; const GRP_QUERY: usize = 7; const GRP_FRAGMENT: usize = 9; fn parse_iri(s: &str) -> IriResult<IRI> { // From RFC-2396, appendix B. Parsing a URI Reference with a Regular Expression let regex = Regex::new(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?").unwrap(); match regex.captures(s) { Some(captures) => Ok(IRI { scheme: match captures.get(GRP_SCHEME) { None => None, Some(grp) => Some(Scheme::from_str(grp.as_str())?), }, authority: match captures.get(GRP_AUTHORITY) { None => None, Some(grp) => Some(Authority::from_str(grp.as_str())?), }, path: match captures.get(GRP_PATH) { None => Path::default(), Some(grp) => Path::from_str(grp.as_str())?, }, query: match captures.get(GRP_QUERY) { None => None, Some(grp) => Some(Query::from_str(grp.as_str())?), }, fragment: match captures.get(GRP_FRAGMENT) { None => None, Some(grp) => Some(Fragment::from_str(grp.as_str())?), }, }), None => Err(ErrorKind::Syntax(s.to_string()).into()), } }