pax_global_header00006660000000000000000000000064142201122760014507gustar00rootroot0000000000000052 comment=e55d5333fce879e7d6213b6c1d10e9b1d438922e oxiri-0.2.2/000077500000000000000000000000001422011227600126425ustar00rootroot00000000000000oxiri-0.2.2/.github/000077500000000000000000000000001422011227600142025ustar00rootroot00000000000000oxiri-0.2.2/.github/dependabot.yml000066400000000000000000000001771422011227600170370ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily open-pull-requests-limit: 10 oxiri-0.2.2/.github/workflows/000077500000000000000000000000001422011227600162375ustar00rootroot00000000000000oxiri-0.2.2/.github/workflows/build.yml000066400000000000000000000016121422011227600200610ustar00rootroot00000000000000name: build on: [push, pull_request] jobs: fmt: name: fmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: rustup update - run: rustup component add rustfmt - run: cargo fmt -- --check clippy: name: clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: rustup update - run: rustup component add clippy - run: cargo clippy --all-targets - run: cargo clippy --all-targets --all-features test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: rustup update - run: cargo build --all-features - run: cargo test --verbose - run: cargo test --verbose --all-features env: RUST_BACKTRACE: 1 deny: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: EmbarkStudios/cargo-deny-action@v1 oxiri-0.2.2/.gitignore000066400000000000000000000000231422011227600146250ustar00rootroot00000000000000/target Cargo.lock oxiri-0.2.2/CHANGELOG.md000066400000000000000000000033741422011227600144620ustar00rootroot00000000000000# Changelog ## [0.2.2] - 2022-03-27 ### Added - `Iri` and `IriRef` now implement Serde `Serialize` and `Deserialize` traits if the `serde` crate is present. The serialization is a plain string. ## [0.2.1] - 2021-01-10 ### Changed - Fixes a regression in relative IRI parsing when there is only a host without a training slash. For example `foo` is now resolved against `http://example.org` as `http://example.org/foo` and not anymore as `http://example.orgfoo`. - The validation of unicode character is now carefully following RFC 3987: - Some private use characters are not anymore allowed in path and fragment. - Some surrogates are not allowed anymore in query. - The range F900-FDEF is now allowed in path and fragment following the RFC. ## [0.2.0] - 2021-01-06 ### Added - `IriRef` type that provides the same API as `Iri` but for relative IRIs. - `PartialOrder` implementations between `Iri`s with different container types. ### Changed - Fixes path resolution: the resolver should return `tag:c-d` and not `tag:/c-d` when resolving `c-d` against `tag:a-b`. - Relative IRIs are not anymore allowed to start with a column `:`. - `iprivate` characters (`%xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD`) are not allowed anymore as part of the IRI query component following RFC 3987. ## [0.1.1] - 2020-07-10 ### Added - Accessors for IRI scheme, authority, path, query and fragment. - `PartialEq` and `From` implementations between `Iri` and some string types. - `Iri` order and hash is now the same as `str`. - `Borrow` and `AsRef` implementations for `Iri`. ### Changed - Bug fix in the relative IRI resolution: some character were duplicated. ## [0.1.0] - 2020-05-01 ### Added - `Iri` struct with a parser and relative IRI resolution.oxiri-0.2.2/Cargo.toml000066400000000000000000000010171422011227600145710ustar00rootroot00000000000000[package] name = "oxiri" version = "0.2.2" authors = ["Tpt "] license = "MIT OR Apache-2.0" readme = "README.md" keywords = ["IRI"] repository = "https://github.com/oxigraph/oxiri" description = """ Simple and fast implementation of IRI validation and relative IRI resolution """ edition = "2018" [dependencies] serde = { version = "1", optional = true } [dev-dependencies] criterion = "0.3" serde_test = "1" [[bench]] name = "lib" harness = false [package.metadata.docs.rs] all-features = true oxiri-0.2.2/LICENSE-APACHE000066400000000000000000000251371422011227600145760ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. oxiri-0.2.2/LICENSE-MIT000066400000000000000000000020471422011227600143010ustar00rootroot00000000000000Copyright (c) 2018 Oxigraph developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. oxiri-0.2.2/README.md000066400000000000000000000031671422011227600141300ustar00rootroot00000000000000OxIRI ===== [![actions status](https://github.com/oxigraph/oxiri/workflows/build/badge.svg)](https://github.com/oxigraph/oxiri/actions) [![Latest Version](https://img.shields.io/crates/v/oxiri.svg)](https://crates.io/crates/oxiri) [![Released API docs](https://docs.rs/oxiri/badge.svg)](https://docs.rs/oxiri) OxIRI is a simple and fast implementation of IRIs based on [RFC 3987](https://www.ietf.org/rfc/rfc3987.html). It allows zero stack allocation IRI validation and resolution. Example: ```rust use oxiri::Iri; // Parse and validate base IRI let base_iri = Iri::parse("http://foo.com/bar/baz").unwrap(); // Validate and resolve relative IRI let iri = base_iri.resolve("bat#foo").unwrap(); assert_eq!("http://foo.com/bar/bat#foo", iri.as_str()); // Extract IRI components assert_eq!(iri.scheme(), "http"); assert_eq!(iri.authority(), Some("foo.com")); assert_eq!(iri.path(), "/bar/bat"); assert_eq!(iri.query(), None); assert_eq!(iri.fragment(), Some("foo")); ``` If [`serde`](https://serde.rs/) is available, `Iri` and `IriRef` implement the `Serialize` and `Deserialize` traits and encode the IRI as a string. ## License This project is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ``) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ``) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in OxIRI by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. oxiri-0.2.2/benches/000077500000000000000000000000001422011227600142515ustar00rootroot00000000000000oxiri-0.2.2/benches/lib.rs000066400000000000000000000054571422011227600154000ustar00rootroot00000000000000use criterion::{criterion_group, criterion_main, Criterion}; use oxiri::{Iri, IriRef}; fn abs_examples() -> &'static [&'static str] { &[ "file://foo", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", //"ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "http://example.com", "http://example.com/", "http://example.com/foo", "http://example.com/foo/bar", "http://example.com/foo/bar/", "http://example.com/foo/bar?q=1&r=2", "http://example.com/foo/bar/?q=1&r=2", "http://example.com#toto", "http://example.com/#toto", "http://example.com/foo#toto", "http://example.com/foo/bar#toto", "http://example.com/foo/bar/#toto", "http://example.com/foo/bar?q=1&r=2#toto", "http://example.com/foo/bar/?q=1&r=2#toto", "http://example.com/foo/bar/.././baz", ] } fn bench_iri_parse(c: &mut Criterion) { c.bench_function("Iri::parse", |b| { b.iter(|| { for iri in abs_examples().iter() { Iri::parse(*iri).unwrap(); } }) }); } fn bench_iri_parse_relative(c: &mut Criterion) { c.bench_function("IriRef::parse", |b| { b.iter(|| { for iri in abs_examples().iter() { IriRef::parse(*iri).unwrap(); } }) }); } fn bench_iri_resolve(c: &mut Criterion) { let examples = [ "g:h", "g", "g/", "/g", "//g", "?y", "g?y", "#s", "g#s", "g?y#s", ";x", "g;x", "g;x?y#s", "", ".", "./", "./g", "..", "../", "../g", "../..", "../../", "../../g", "../../../g", "../../../../g", "/./g", "/../g", "g.", ".g", "g..", "..g", "./../g", "./g/.", "g/./h", "g/../h", "g;x=1/./y", "g;x=1/../y", "g?y/./x", "g?y/../x", "g#s/./x", "g#s/../x", "http:g", "./g:h", ]; let base = Iri::parse("http://a/b/c/d;p?q").unwrap(); let mut buf = String::new(); c.bench_function("Iri::resolve_into", |b| { b.iter(|| { for relative in examples.iter() { buf.clear(); base.resolve_into(relative, &mut buf).unwrap(); } }) }); } criterion_group!( iri, bench_iri_parse, bench_iri_parse_relative, bench_iri_resolve ); criterion_main!(iri); oxiri-0.2.2/deny.toml000066400000000000000000000002161422011227600144750ustar00rootroot00000000000000[licenses] unlicensed = "deny" allow = [ "MIT", "Apache-2.0" ] default = "deny" [bans] multiple-versions = "warn" wildcards = "deny" oxiri-0.2.2/fuzz/000077500000000000000000000000001422011227600136405ustar00rootroot00000000000000oxiri-0.2.2/fuzz/.gitignore000066400000000000000000000000271422011227600156270ustar00rootroot00000000000000target corpus artifactsoxiri-0.2.2/fuzz/Cargo.toml000066400000000000000000000005271422011227600155740ustar00rootroot00000000000000[package] name = "oxiri-fuzz" version = "0.0.0" authors = ["Automatically generated"] publish = false edition = "2021" [package.metadata] cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" [dependencies.oxiri] path = ".." [[bin]] name = "parse" path = "fuzz_targets/parse.rs" [[bin]] name = "resolve" path = "fuzz_targets/resolve.rs" oxiri-0.2.2/fuzz/fuzz_targets/000077500000000000000000000000001422011227600163675ustar00rootroot00000000000000oxiri-0.2.2/fuzz/fuzz_targets/parse.rs000066400000000000000000000003011422011227600200410ustar00rootroot00000000000000#![no_main] use libfuzzer_sys::fuzz_target; use oxiri::IriRef; use std::str; fuzz_target!(|data: &[u8]| { if let Ok(s) = str::from_utf8(data) { let _ = IriRef::parse(s); } }); oxiri-0.2.2/fuzz/fuzz_targets/resolve.rs000066400000000000000000000003751422011227600204210ustar00rootroot00000000000000#![no_main] use libfuzzer_sys::fuzz_target; use oxiri::IriRef; use std::str; fuzz_target!(|data: &[u8]| { let base = IriRef::parse("http://a/b/c/d;p?q").unwrap(); if let Ok(s) = str::from_utf8(data) { let _ = base.resolve(s); } }); oxiri-0.2.2/src/000077500000000000000000000000001422011227600134315ustar00rootroot00000000000000oxiri-0.2.2/src/lib.rs000066400000000000000000001255671422011227600145650ustar00rootroot00000000000000#![doc = include_str!("../README.md")] #![deny(unsafe_code)] #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::convert::{TryFrom, TryInto}; use std::error::Error; use std::fmt; use std::hash::{Hash, Hasher}; use std::net::{AddrParseError, Ipv6Addr}; use std::ops::Deref; use std::str::{Chars, FromStr}; /// A [RFC 3987](https://www.ietf.org/rfc/rfc3987.html) IRI reference. /// /// Instances of this type may be absolute or relative, /// unlike [`Iri`]. /// /// ``` /// use oxiri::{Iri, IriRef}; /// /// // Parse and validate base IRI /// let base_iri = IriRef::parse("../bar/baz")?; /// /// // Validate and resolve relative IRI /// let iri = base_iri.resolve("bat#foo")?; /// assert_eq!(iri.into_inner(), "../bar/bat#foo"); /// /// // IriRef's *can* also be absolute. /// assert!(IriRef::parse("http://foo.com/bar/baz").is_ok()); /// /// // It is possible to build an IriRef from an Iri object /// IriRef::from(Iri::parse("http://foo.com/bar")?); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[derive(Clone, Copy)] pub struct IriRef { iri: T, positions: IriElementsPositions, } impl> IriRef { /// Parses and validates the IRI-reference following the grammar from [RFC 3987](https://www.ietf.org/rfc/rfc3987.html). /// /// This operation keeps internally the `iri` parameter and does not allocate. /// /// ``` /// use oxiri::IriRef; /// /// IriRef::parse("//foo.com/bar/baz")?; /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn parse(iri: T) -> Result { let positions = IriParser::parse(&iri, None, &mut VoidOutputBuffer::default())?; Ok(Self { iri, positions }) } /// Validates and resolved a relative IRI against the current IRI /// following [RFC 3986](https://www.ietf.org/rfc/rfc3986.html) relative URI resolution algorithm. /// /// ``` /// use oxiri::IriRef; /// /// let base_iri = IriRef::parse("//foo.com/bar/baz")?; /// let iri = base_iri.resolve("bat#foo")?; /// assert_eq!(iri.into_inner(), "//foo.com/bar/bat#foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn resolve(&self, iri: &str) -> Result, IriParseError> { let mut target_buffer = String::with_capacity(self.iri.len() + iri.len()); let positions = IriParser::parse(iri, Some(self.as_ref()), &mut target_buffer)?; Ok(IriRef { iri: target_buffer, positions, }) } /// Validates and resolved a relative IRI against the current IRI /// following [RFC 3986](https://www.ietf.org/rfc/rfc3986.html) relative URI resolution algorithm. /// /// It outputs the resolved IRI into `target_buffer` to avoid any memory allocation. /// /// ``` /// use oxiri::IriRef; /// /// let base_iri = IriRef::parse("//foo.com/bar/baz")?; /// let mut result = String::default(); /// let iri = base_iri.resolve_into("bat#foo", &mut result)?; /// assert_eq!(result, "//foo.com/bar/bat#foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn resolve_into(&self, iri: &str, target_buffer: &mut String) -> Result<(), IriParseError> { IriParser::parse(iri, Some(self.as_ref()), target_buffer)?; Ok(()) } /// Returns an `IriRef` borrowing this IRI's text. #[inline] pub fn as_ref(&self) -> IriRef<&str> { IriRef { iri: &self.iri, positions: self.positions, } } /// Returns the underlying IRI representation. /// /// ``` /// use oxiri::IriRef; /// /// let iri = IriRef::parse("//example.com/foo")?; /// assert_eq!(iri.as_str(), "//example.com/foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn as_str(&self) -> &str { &self.iri } /// Returns the underlying IRI representation. /// /// ``` /// use oxiri::IriRef; /// /// let iri = IriRef::parse("//example.com/foo")?; /// assert_eq!(iri.into_inner(), "//example.com/foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn into_inner(self) -> T { self.iri } /// Whether this IRI is an absolute IRI reference or not. /// /// ``` /// use oxiri::IriRef; /// /// assert!(IriRef::parse("http://example.com/foo")?.is_absolute()); /// assert!(!IriRef::parse("/foo")?.is_absolute()); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn is_absolute(&self) -> bool { self.positions.scheme_end != 0 } /// Returns the IRI scheme if it exists. /// /// Beware: the scheme case is not normalized. Use case insensitive comparisons if you look for a specific scheme. /// ``` /// use oxiri::IriRef; /// /// let iri = IriRef::parse("hTTp://example.com")?; /// assert_eq!(iri.scheme(), Some("hTTp")); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn scheme(&self) -> Option<&str> { if self.positions.scheme_end == 0 { None } else { Some(&self.iri[..self.positions.scheme_end - 1]) } } /// Returns the IRI authority if it exists. /// /// Beware: the host case is not normalized. Use case insensitive comparisons if you look for a specific host. /// /// ``` /// use oxiri::IriRef; /// /// let http = IriRef::parse("http://foo:pass@example.com:80/my/path")?; /// assert_eq!(http.authority(), Some("foo:pass@example.com:80")); /// /// let mailto = IriRef::parse("mailto:foo@bar.com")?; /// assert_eq!(mailto.authority(), None); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn authority(&self) -> Option<&str> { if self.positions.scheme_end + 2 > self.positions.authority_end { None } else { Some(&self.iri[self.positions.scheme_end + 2..self.positions.authority_end]) } } /// Returns the IRI path. /// /// ``` /// use oxiri::IriRef; /// /// let http = IriRef::parse("http://foo:pass@example.com:80/my/path?foo=bar")?; /// assert_eq!(http.path(), "/my/path"); /// /// let mailto = IriRef::parse("mailto:foo@bar.com")?; /// assert_eq!(mailto.path(), "foo@bar.com"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn path(&self) -> &str { &self.iri[self.positions.authority_end..self.positions.path_end] } /// Returns the IRI query if it exists. /// /// ``` /// use oxiri::IriRef; /// /// let iri = IriRef::parse("http://example.com/my/path?query=foo#frag")?; /// assert_eq!(iri.query(), Some("query=foo")); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn query(&self) -> Option<&str> { if self.positions.path_end >= self.positions.query_end { None } else { Some(&self.iri[self.positions.path_end + 1..self.positions.query_end]) } } /// Returns the IRI fragment if it exists. /// /// ``` /// use oxiri::IriRef; /// /// let iri = IriRef::parse("http://example.com/my/path?query=foo#frag")?; /// assert_eq!(iri.fragment(), Some("frag")); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn fragment(&self) -> Option<&str> { if self.positions.query_end >= self.iri.len() { None } else { Some(&self.iri[self.positions.query_end + 1..]) } } } impl, Rhs> PartialEq> for IriRef { #[inline] fn eq(&self, other: &IriRef) -> bool { self.iri.eq(&other.iri) } } impl> PartialEq for IriRef { #[inline] fn eq(&self, other: &str) -> bool { self.iri.eq(other) } } impl<'a, T: PartialEq<&'a str>> PartialEq<&'a str> for IriRef { #[inline] fn eq(&self, other: &&'a str) -> bool { self.iri.eq(other) } } impl> PartialEq for IriRef { #[inline] fn eq(&self, other: &String) -> bool { self.iri.eq(other) } } impl<'a, T: PartialEq>> PartialEq> for IriRef { #[inline] fn eq(&self, other: &Cow<'a, str>) -> bool { self.iri.eq(other) } } impl> PartialEq> for str { #[inline] fn eq(&self, other: &IriRef) -> bool { other.iri.eq(self) } } impl<'a, T: PartialEq<&'a str>> PartialEq> for &'a str { #[inline] fn eq(&self, other: &IriRef) -> bool { other.iri.eq(self) } } impl> PartialEq> for String { #[inline] fn eq(&self, other: &IriRef) -> bool { other.iri.eq(self) } } impl<'a, T: PartialEq>> PartialEq> for Cow<'a, str> { #[inline] fn eq(&self, other: &IriRef) -> bool { other.iri.eq(self) } } impl Eq for IriRef {} impl Hash for IriRef { #[inline] fn hash(&self, state: &mut H) { self.iri.hash(state) } } impl, Rhs> PartialOrd> for IriRef { #[inline] fn partial_cmp(&self, other: &IriRef) -> Option { self.iri.partial_cmp(&other.iri) } } impl Ord for IriRef { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.iri.cmp(&other.iri) } } impl> Deref for IriRef { type Target = str; #[inline] fn deref(&self) -> &str { self.iri.deref() } } impl> AsRef for IriRef { #[inline] fn as_ref(&self) -> &str { self.iri.as_ref() } } impl> Borrow for IriRef { #[inline] fn borrow(&self) -> &str { self.iri.borrow() } } impl fmt::Debug for IriRef { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.iri.fmt(f) } } impl fmt::Display for IriRef { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.iri.fmt(f) } } impl FromStr for IriRef { type Err = IriParseError; #[inline] fn from_str(iri: &str) -> Result { Self::parse(iri.to_owned()) } } impl<'a> From> for IriRef { #[inline] fn from(iri: IriRef<&'a str>) -> Self { Self { iri: iri.iri.into(), positions: iri.positions, } } } impl<'a> From>> for IriRef { #[inline] fn from(iri: IriRef>) -> Self { Self { iri: iri.iri.into(), positions: iri.positions, } } } impl From>> for IriRef { #[inline] fn from(iri: IriRef>) -> Self { Self { iri: iri.iri.into(), positions: iri.positions, } } } impl<'a> From> for IriRef> { #[inline] fn from(iri: IriRef<&'a str>) -> Self { Self { iri: iri.iri.into(), positions: iri.positions, } } } impl<'a> From> for IriRef> { #[inline] fn from(iri: IriRef) -> Self { Self { iri: iri.iri.into(), positions: iri.positions, } } } impl<'a> From<&'a IriRef> for IriRef<&'a str> { #[inline] fn from(iri: &'a IriRef) -> Self { Self { iri: &iri.iri, positions: iri.positions, } } } impl<'a> From<&'a IriRef>> for IriRef<&'a str> { #[inline] fn from(iri: &'a IriRef>) -> Self { Self { iri: &iri.iri, positions: iri.positions, } } } #[cfg(feature = "serde")] impl Serialize for IriRef { fn serialize(&self, serializer: S) -> Result { self.iri.serialize(serializer) } } #[cfg(feature = "serde")] impl<'de, T: Deref + Deserialize<'de>> Deserialize<'de> for IriRef { fn deserialize>(deserializer: D) -> Result { use serde::de::Error; Self::parse(T::deserialize(deserializer)?).map_err(D::Error::custom) } } /// A [RFC 3987](https://www.ietf.org/rfc/rfc3987.html) IRI. /// /// Instances of this type are guaranteed to be absolute, /// unlike [`IriRef`]. /// /// ``` /// use std::convert::TryFrom; /// use oxiri::{Iri, IriRef}; /// /// // Parse and validate base IRI /// let base_iri = Iri::parse("http://foo.com/bar/baz")?; /// /// // Validate and resolve relative IRI /// let iri = base_iri.resolve("bat#foo")?; /// assert_eq!(iri.into_inner(), "http://foo.com/bar/bat#foo"); /// /// // Iri::parse will err on relative IRIs. /// assert!(Iri::parse("../bar/baz").is_err()); /// /// // It is possible to build an Iri from an IriRef object /// Iri::try_from(IriRef::parse("http://foo.com/bar")?)?; /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[derive(Clone, Copy)] pub struct Iri(IriRef); impl> Iri { /// Parses and validates the IRI following the grammar from [RFC 3987](https://www.ietf.org/rfc/rfc3987.html). /// /// This operation keeps internally the `iri` parameter and does not allocate. /// /// ``` /// use oxiri::Iri; /// /// Iri::parse("http://foo.com/bar/baz")?; /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn parse(iri: T) -> Result { IriRef::parse(iri)?.try_into() } /// Validates and resolved a relative IRI against the current IRI /// following [RFC 3986](https://www.ietf.org/rfc/rfc3986.html) relative URI resolution algorithm. /// /// ``` /// use oxiri::Iri; /// /// let base_iri = Iri::parse("http://foo.com/bar/baz")?; /// let iri = base_iri.resolve("bat#foo")?; /// assert_eq!(iri.into_inner(), "http://foo.com/bar/bat#foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn resolve(&self, iri: &str) -> Result, IriParseError> { Ok(Iri(self.0.resolve(iri)?)) } /// Validates and resolved a relative IRI against the current IRI /// following [RFC 3986](https://www.ietf.org/rfc/rfc3986.html) relative URI resolution algorithm. /// /// It outputs the resolved IRI into `target_buffer` to avoid any memory allocation. /// /// ``` /// use oxiri::Iri; /// /// let base_iri = Iri::parse("http://foo.com/bar/baz")?; /// let mut result = String::default(); /// let iri = base_iri.resolve_into("bat#foo", &mut result)?; /// assert_eq!(result, "http://foo.com/bar/bat#foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` pub fn resolve_into(&self, iri: &str, target_buffer: &mut String) -> Result<(), IriParseError> { self.0.resolve_into(iri, target_buffer) } /// Returns an IRI borrowing this IRI's text #[inline] pub fn as_ref(&self) -> Iri<&str> { Iri(self.0.as_ref()) } /// Returns the underlying IRI representation. /// /// ``` /// use oxiri::Iri; /// /// let iri = Iri::parse("http://example.com/foo")?; /// assert_eq!(iri.as_str(), "http://example.com/foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn as_str(&self) -> &str { self.0.as_str() } /// Returns the underlying IRI representation. /// /// ``` /// use oxiri::Iri; /// /// let iri = Iri::parse("http://example.com/foo")?; /// assert_eq!(iri.into_inner(), "http://example.com/foo"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn into_inner(self) -> T { self.0.into_inner() } /// Returns the IRI scheme. /// /// Beware: the scheme case is not normalized. Use case insensitive comparisons if you look for a specific scheme. /// /// ``` /// use oxiri::Iri; /// /// let iri = Iri::parse("hTTp://example.com")?; /// assert_eq!(iri.scheme(), "hTTp"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn scheme(&self) -> &str { self.0.scheme().expect("The IRI should be absolute") } /// Returns the IRI authority if it exists. /// /// Beware: the host case is not normalized. Use case insensitive comparisons if you look for a specific host. /// /// ``` /// use oxiri::Iri; /// /// let http = Iri::parse("http://foo:pass@example.com:80/my/path")?; /// assert_eq!(http.authority(), Some("foo:pass@example.com:80")); /// /// let mailto = Iri::parse("mailto:foo@bar.com")?; /// assert_eq!(mailto.authority(), None); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn authority(&self) -> Option<&str> { self.0.authority() } /// Returns the IRI path. /// /// ``` /// use oxiri::Iri; /// /// let http = Iri::parse("http://foo:pass@example.com:80/my/path?foo=bar")?; /// assert_eq!(http.path(), "/my/path"); /// /// let mailto = Iri::parse("mailto:foo@bar.com")?; /// assert_eq!(mailto.path(), "foo@bar.com"); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn path(&self) -> &str { self.0.path() } /// Returns the IRI query if it exists. /// /// ``` /// use oxiri::Iri; /// /// let iri = Iri::parse("http://example.com/my/path?query=foo#frag")?; /// assert_eq!(iri.query(), Some("query=foo")); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn query(&self) -> Option<&str> { self.0.query() } /// Returns the IRI fragment if it exists. /// /// ``` /// use oxiri::Iri; /// /// let iri = Iri::parse("http://example.com/my/path?query=foo#frag")?; /// assert_eq!(iri.fragment(), Some("frag")); /// # Result::<(), oxiri::IriParseError>::Ok(()) /// ``` #[inline] pub fn fragment(&self) -> Option<&str> { self.0.fragment() } } impl, Rhs> PartialEq> for Iri { #[inline] fn eq(&self, other: &Iri) -> bool { self.0.eq(&other.0) } } impl, Rhs> PartialEq> for Iri { #[inline] fn eq(&self, other: &IriRef) -> bool { self.0.eq(other) } } impl, Rhs> PartialEq> for IriRef { #[inline] fn eq(&self, other: &Iri) -> bool { self.eq(&other.0) } } impl> PartialEq for Iri { #[inline] fn eq(&self, other: &str) -> bool { self.0.eq(other) } } impl<'a, T: PartialEq<&'a str>> PartialEq<&'a str> for Iri { #[inline] fn eq(&self, other: &&'a str) -> bool { self.0.eq(other) } } impl> PartialEq for Iri { #[inline] fn eq(&self, other: &String) -> bool { self.0.eq(other) } } impl<'a, T: PartialEq>> PartialEq> for Iri { #[inline] fn eq(&self, other: &Cow<'a, str>) -> bool { self.0.eq(other) } } impl> PartialEq> for str { #[inline] fn eq(&self, other: &Iri) -> bool { self.eq(&other.0) } } impl<'a, T: PartialEq<&'a str>> PartialEq> for &'a str { #[inline] fn eq(&self, other: &Iri) -> bool { self.eq(&other.0) } } impl> PartialEq> for String { #[inline] fn eq(&self, other: &Iri) -> bool { self.eq(&other.0) } } impl<'a, T: PartialEq>> PartialEq> for Cow<'a, str> { #[inline] fn eq(&self, other: &Iri) -> bool { self.eq(&other.0) } } impl Eq for Iri {} impl Hash for Iri { #[inline] fn hash(&self, state: &mut H) { self.0.hash(state) } } impl, Rhs> PartialOrd> for Iri { #[inline] fn partial_cmp(&self, other: &Iri) -> Option { self.0.partial_cmp(&other.0) } } impl, Rhs> PartialOrd> for Iri { #[inline] fn partial_cmp(&self, other: &IriRef) -> Option { self.0.partial_cmp(other) } } impl, Rhs> PartialOrd> for IriRef { #[inline] fn partial_cmp(&self, other: &Iri) -> Option { self.partial_cmp(&other.0) } } impl Ord for Iri { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } impl> Deref for Iri { type Target = str; #[inline] fn deref(&self) -> &str { self.0.deref() } } impl> AsRef for Iri { #[inline] fn as_ref(&self) -> &str { self.0.as_ref() } } impl> Borrow for Iri { #[inline] fn borrow(&self) -> &str { self.0.borrow() } } impl fmt::Debug for Iri { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl fmt::Display for Iri { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl FromStr for Iri { type Err = IriParseError; #[inline] fn from_str(iri: &str) -> Result { Self::parse(iri.to_owned()) } } impl<'a> From> for Iri { #[inline] fn from(iri: Iri<&'a str>) -> Self { Self(iri.0.into()) } } impl<'a> From>> for Iri { #[inline] fn from(iri: Iri>) -> Self { Self(iri.0.into()) } } impl From>> for Iri { #[inline] fn from(iri: Iri>) -> Self { Self(iri.0.into()) } } impl<'a> From> for Iri> { #[inline] fn from(iri: Iri<&'a str>) -> Self { Self(iri.0.into()) } } impl<'a> From> for Iri> { #[inline] fn from(iri: Iri) -> Self { Self(iri.0.into()) } } impl<'a> From<&'a Iri> for Iri<&'a str> { #[inline] fn from(iri: &'a Iri) -> Self { Self(iri.0.as_ref()) } } impl<'a> From<&'a Iri>> for Iri<&'a str> { #[inline] fn from(iri: &'a Iri>) -> Self { Self(iri.0.as_ref()) } } impl> From> for IriRef { fn from(iri: Iri) -> Self { iri.0 } } impl> TryFrom> for Iri { type Error = IriParseError; fn try_from(iri: IriRef) -> Result { if iri.is_absolute() { Ok(Self(iri)) } else { Err(IriParseError { kind: IriParseErrorKind::NoScheme, }) } } } #[cfg(feature = "serde")] impl Serialize for Iri { fn serialize(&self, serializer: S) -> Result { self.0.serialize(serializer) } } #[cfg(feature = "serde")] impl<'de, T: Deref + Deserialize<'de>> Deserialize<'de> for Iri { fn deserialize>(deserializer: D) -> Result { use serde::de::Error; IriRef::deserialize(deserializer)? .try_into() .map_err(D::Error::custom) } } /// An error raised during [`Iri`](struct.Iri.html) validation. #[derive(Debug)] pub struct IriParseError { kind: IriParseErrorKind, } impl fmt::Display for IriParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.kind { IriParseErrorKind::NoScheme => write!(f, "No scheme found in an absolute IRI"), IriParseErrorKind::InvalidHostCharacter(c) => { write!(f, "Invalid character '{}' in host", c) } IriParseErrorKind::InvalidHostIp(e) => write!(f, "Invalid host IP ({})", e), IriParseErrorKind::InvalidPortCharacter(c) => write!(f, "Invalid character '{}'", c), IriParseErrorKind::InvalidIriCodePoint(c) => { write!(f, "Invalid IRI code point '{}'", c) } IriParseErrorKind::InvalidPercentEncoding(cs) => write!( f, "Invalid IRI percent encoding '{}'", cs.iter().flatten().cloned().collect::() ), } } } impl Error for IriParseError { fn source(&self) -> Option<&(dyn Error + 'static)> { if let IriParseErrorKind::InvalidHostIp(e) = &self.kind { Some(e) } else { None } } } #[derive(Debug)] enum IriParseErrorKind { NoScheme, InvalidHostCharacter(char), InvalidHostIp(AddrParseError), InvalidPortCharacter(char), InvalidIriCodePoint(char), InvalidPercentEncoding([Option; 3]), } #[derive(Debug, Clone, Copy)] struct IriElementsPositions { scheme_end: usize, authority_end: usize, path_end: usize, query_end: usize, } trait OutputBuffer { fn push(&mut self, c: char); fn push_str(&mut self, s: &str); fn clear(&mut self); fn truncate(&mut self, new_len: usize); fn len(&self) -> usize; fn as_str(&self) -> &str; } #[derive(Default)] struct VoidOutputBuffer { len: usize, } impl OutputBuffer for VoidOutputBuffer { #[inline] fn push(&mut self, c: char) { self.len += c.len_utf8(); } #[inline] fn push_str(&mut self, s: &str) { self.len += s.len(); } #[inline] fn clear(&mut self) { self.len = 0; } #[inline] fn truncate(&mut self, new_len: usize) { self.len = new_len; } #[inline] fn len(&self) -> usize { self.len } #[inline] fn as_str(&self) -> &str { "" } } impl OutputBuffer for String { #[inline] fn push(&mut self, c: char) { self.push(c); } #[inline] fn push_str(&mut self, s: &str) { self.push_str(s); } #[inline] fn clear(&mut self) { self.clear(); } #[inline] fn truncate(&mut self, new_len: usize) { self.truncate(new_len); } #[inline] fn len(&self) -> usize { self.len() } #[inline] fn as_str(&self) -> &str { self.as_str() } } struct ParserInput<'a> { value: Chars<'a>, position: usize, } impl<'a> ParserInput<'a> { #[inline] fn next(&mut self) -> Option { if let Some(head) = self.value.next() { self.position += head.len_utf8(); Some(head) } else { None } } #[inline] fn front(&self) -> Option { self.value.clone().next() } #[inline] fn starts_with(&self, c: char) -> bool { self.value.as_str().starts_with(c) } } /// parser implementing https://url.spec.whatwg.org/#concept-basic-url-parser without the normalization or backward compatibility bits to comply with RFC 3987 /// /// A sub function takes care of each state struct IriParser<'a, O: OutputBuffer> { iri: &'a str, base: Option>, input: ParserInput<'a>, output: &'a mut O, output_positions: IriElementsPositions, input_scheme_end: usize, } impl<'a, O: OutputBuffer> IriParser<'a, O> { fn parse( iri: &'a str, base: Option>, output: &'a mut O, ) -> Result { let mut parser = Self { iri, base, input: ParserInput { value: iri.chars(), position: 0, }, output, output_positions: IriElementsPositions { scheme_end: 0, authority_end: 0, path_end: 0, query_end: 0, }, input_scheme_end: 0, }; parser.parse_scheme_start()?; Ok(parser.output_positions) } fn parse_scheme_start(&mut self) -> Result<(), IriParseError> { match self.input.front() { Some(':') => self.parse_error(IriParseErrorKind::NoScheme), Some(c) if c.is_ascii_alphabetic() => self.parse_scheme(), _ => self.parse_relative(), } } fn parse_scheme(&mut self) -> Result<(), IriParseError> { loop { let c = self.input.next(); match c { Some(c) if c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.' => { self.output.push(c) } Some(':') => { self.output.push(':'); self.output_positions.scheme_end = self.output.len(); self.input_scheme_end = self.input.position; return if self.input.starts_with('/') { self.input.next(); self.output.push('/'); self.parse_path_or_authority() } else { self.output_positions.authority_end = self.output.len(); self.parse_path() }; } _ => { self.input = ParserInput { value: self.iri.chars(), position: 0, }; // reset self.output.clear(); return self.parse_relative(); } } } } fn parse_path_or_authority(&mut self) -> Result<(), IriParseError> { if self.input.starts_with('/') { self.input.next(); self.output.push('/'); self.parse_authority() } else { self.output_positions.authority_end = self.output.len() - 1; self.parse_path() } } fn parse_relative(&mut self) -> Result<(), IriParseError> { if let Some(base) = self.base { match self.input.front() { None => { self.output.push_str(&base.iri[..base.positions.query_end]); self.output_positions.scheme_end = base.positions.scheme_end; self.output_positions.authority_end = base.positions.authority_end; self.output_positions.path_end = base.positions.path_end; self.output_positions.query_end = base.positions.query_end; Ok(()) } Some('/') => { self.input.next(); self.parse_relative_slash(&base) } Some('?') => { self.input.next(); self.output.push_str(&base.iri[..base.positions.path_end]); self.output.push('?'); self.output_positions.scheme_end = base.positions.scheme_end; self.output_positions.authority_end = base.positions.authority_end; self.output_positions.path_end = base.positions.path_end; self.parse_query() } Some('#') => { self.input.next(); self.output.push_str(&base.iri[..base.positions.query_end]); self.output_positions.scheme_end = base.positions.scheme_end; self.output_positions.authority_end = base.positions.authority_end; self.output_positions.path_end = base.positions.path_end; self.output_positions.query_end = base.positions.query_end; self.output.push('#'); self.parse_fragment() } _ => { self.output.push_str(&base.iri[..base.positions.path_end]); self.output_positions.scheme_end = base.positions.scheme_end; self.output_positions.authority_end = base.positions.authority_end; self.output_positions.path_end = base.positions.path_end; self.remove_last_segment(); if self.output.len() > base.positions.scheme_end { // We have some path or authority, we keep a base '/' self.output.push('/'); } self.parse_path() } } } else { self.output_positions.scheme_end = 0; self.input_scheme_end = 0; if self.input.starts_with('/') { self.input.next(); self.output.push('/'); self.parse_path_or_authority() } else { self.output_positions.authority_end = 0; self.parse_path() } } } fn parse_relative_slash(&mut self, base: &IriRef<&'a str>) -> Result<(), IriParseError> { if self.input.starts_with('/') { self.input.next(); self.output.push_str(&base.iri[..base.positions.scheme_end]); self.output_positions.scheme_end = base.positions.scheme_end; self.output.push('/'); self.output.push('/'); self.parse_authority() } else { self.output .push_str(&base.iri[..base.positions.authority_end]); self.output.push('/'); self.output_positions.scheme_end = base.positions.scheme_end; self.output_positions.authority_end = base.positions.authority_end; self.parse_path() } } fn parse_authority(&mut self) -> Result<(), IriParseError> { // @ are not allowed in IRI authorities so not need to take care of ambiguities loop { let c = self.input.next(); match c { Some('@') => { self.output.push('@'); return self.parse_host(); } None | Some('[') | Some('/') | Some('?') | Some('#') => { self.input = ParserInput { value: self.iri[self.input_scheme_end + 2..].chars(), position: self.input_scheme_end + 2, }; self.output.truncate(self.output_positions.scheme_end + 2); return self.parse_host(); } Some(c) => { self.read_url_codepoint_or_echar(c)?; } } } } fn parse_host(&mut self) -> Result<(), IriParseError> { if self.input.starts_with('[') { // IP v6 let start_position = self.input.position; while let Some(c) = self.input.next() { self.output.push(c); if c == ']' { let ip = &self.iri[start_position + 1..self.input.position - 1]; if let Err(error) = Ipv6Addr::from_str(ip) { return self.parse_error(IriParseErrorKind::InvalidHostIp(error)); } let c = self.input.next(); return match c { Some(':') => { self.output.push(':'); self.parse_port() } None | Some('/') | Some('?') | Some('#') => { self.output_positions.authority_end = self.output.len(); self.parse_path_start(c) } Some(c) => self.parse_error(IriParseErrorKind::InvalidHostCharacter(c)), }; } } self.parse_error(IriParseErrorKind::InvalidHostCharacter('[')) } else { // Other host loop { let c = self.input.next(); match c { Some(':') => { self.output.push(':'); return self.parse_port(); } None | Some('/') | Some('?') | Some('#') => { self.output_positions.authority_end = self.output.len(); return self.parse_path_start(c); } Some(c) => self.read_url_codepoint_or_echar(c)?, } } } } fn parse_port(&mut self) -> Result<(), IriParseError> { loop { let c = self.input.next(); match c { Some(c) if c.is_ascii_digit() => self.output.push(c), Some('/') | Some('?') | Some('#') | None => { self.output_positions.authority_end = self.output.len(); return self.parse_path_start(c); } Some(c) => return self.parse_error(IriParseErrorKind::InvalidPortCharacter(c)), } } } fn parse_path_start(&mut self, c: Option) -> Result<(), IriParseError> { match c { None => { self.output_positions.path_end = self.output.len(); self.output_positions.query_end = self.output.len(); Ok(()) } Some('?') => { self.output_positions.path_end = self.output.len(); self.output.push('?'); self.parse_query() } Some('#') => { self.output_positions.path_end = self.output.len(); self.output_positions.query_end = self.output.len(); self.output.push('#'); self.parse_fragment() } Some('/') => { self.output.push('/'); self.parse_path() } Some(c) => { self.read_url_codepoint_or_echar(c)?; self.parse_path() } } } fn parse_path(&mut self) -> Result<(), IriParseError> { loop { let c = self.input.next(); match c { None | Some('/') | Some('?') | Some('#') => { if self.output.as_str().ends_with("/..") { self.remove_last_segment(); self.remove_last_segment(); self.output.push('/'); } else if self.output.as_str().ends_with("/.") { self.remove_last_segment(); self.output.push('/'); } else if c == Some('/') { self.output.push('/'); } if c == Some('?') { self.output_positions.path_end = self.output.len(); self.output.push('?'); return self.parse_query(); } else if c == Some('#') { self.output_positions.path_end = self.output.len(); self.output_positions.query_end = self.output.len(); self.output.push('#'); return self.parse_fragment(); } else if c == None { self.output_positions.path_end = self.output.len(); self.output_positions.query_end = self.output.len(); return Ok(()); } } Some(c) => self.read_url_codepoint_or_echar(c)?, } } } fn parse_query(&mut self) -> Result<(), IriParseError> { while let Some(c) = self.input.next() { if c == '#' { self.output_positions.query_end = self.output.len(); self.output.push('#'); return self.parse_fragment(); } else { self.read_url_query_codepoint_or_echar(c)? } } self.output_positions.query_end = self.output.len(); Ok(()) } fn parse_fragment(&mut self) -> Result<(), IriParseError> { while let Some(c) = self.input.next() { self.read_url_codepoint_or_echar(c)? } Ok(()) } fn remove_last_segment(&mut self) { let last_slash_position = self.output.as_str()[self.output_positions.authority_end..] .rfind('/') .unwrap_or(0); self.output .truncate(last_slash_position + self.output_positions.authority_end) } #[inline] fn read_url_codepoint_or_echar(&mut self, c: char) -> Result<(), IriParseError> { if c == '%' { self.read_echar() } else if is_url_code_point(c) { self.output.push(c); Ok(()) } else { self.parse_error(IriParseErrorKind::InvalidIriCodePoint(c)) } } #[inline] fn read_url_query_codepoint_or_echar(&mut self, c: char) -> Result<(), IriParseError> { if c == '%' { self.read_echar() } else if is_url_query_code_point(c) { self.output.push(c); Ok(()) } else { self.parse_error(IriParseErrorKind::InvalidIriCodePoint(c)) } } #[inline] fn read_echar(&mut self) -> Result<(), IriParseError> { let c1 = self.input.next(); let c2 = self.input.next(); if c1.map_or(false, |c| c.is_ascii_hexdigit()) && c2.map_or(false, |c| c.is_ascii_hexdigit()) { self.output.push('%'); self.output.push(c1.unwrap()); self.output.push(c2.unwrap()); Ok(()) } else { self.parse_error(IriParseErrorKind::InvalidPercentEncoding([ Some('%'), c1, c2, ])) } } #[inline] fn parse_error(&self, kind: IriParseErrorKind) -> Result { Err(IriParseError { kind }) } } fn is_url_code_point(c: char) -> bool { matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' | '=' | '?' | '@' | '_' | '~' | '\u{A0}'..='\u{D7FF}' | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFEF}' | '\u{10000}'..='\u{1FFFD}' | '\u{20000}'..='\u{2FFFD}' | '\u{30000}'..='\u{3FFFD}' | '\u{40000}'..='\u{4FFFD}' | '\u{50000}'..='\u{5FFFD}' | '\u{60000}'..='\u{6FFFD}' | '\u{70000}'..='\u{7FFFD}' | '\u{80000}'..='\u{8FFFD}' | '\u{90000}'..='\u{9FFFD}' | '\u{A0000}'..='\u{AFFFD}' | '\u{B0000}'..='\u{BFFFD}' | '\u{C0000}'..='\u{CFFFD}' | '\u{D0000}'..='\u{DFFFD}' | '\u{E1000}'..='\u{EFFFD}' ) } fn is_url_query_code_point(c: char) -> bool { is_url_code_point(c) || matches!(c, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}') } oxiri-0.2.2/tests/000077500000000000000000000000001422011227600140045ustar00rootroot00000000000000oxiri-0.2.2/tests/lib.rs000066400000000000000000000566421422011227600151350ustar00rootroot00000000000000#![allow(clippy::eq_op)] use oxiri::{Iri, IriRef}; #[cfg(feature = "serde")] use serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[test] fn test_parsing() { let examples = [ "file://foo", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "http://example.com", "http://example.com/", "http://example.com/foo", "http://example.com/foo/bar", "http://example.com/foo/bar/", "http://example.com/foo/bar?q=1&r=2", "http://example.com/foo/bar/?q=1&r=2", "http://example.com#toto", "http://example.com/#toto", "http://example.com/foo#toto", "http://example.com/foo/bar#toto", "http://example.com/foo/bar/#toto", "http://example.com/foo/bar?q=1&r=2#toto", "http://example.com/foo/bar/?q=1&r=2#toto", "http://example.com/foo/bar/.././baz", "http://a.example/AZaz\u{00C0}\u{00D6}\u{00D8}\u{00F6}\u{00F8}\u{02FF}\u{0370}\u{037D}\u{037F}\u{1FFF}\u{200C}\u{200D}\u{2070}\u{218F}\u{2C00}\u{2FEF}\u{3001}\u{D7FF}\u{FA0E}\u{FDCF}\u{FDF0}\u{FFEF}\u{10000}\u{EFFFD}", "http://a.example/?AZaz\u{E000}\u{F8FF}\u{F0000}\u{FFFFD}\u{100000}\u{10FFFD}\u{00C0}\u{00D6}\u{00D8}\u{00F6}\u{00F8}\u{02FF}\u{0370}\u{037D}\u{037F}\u{1FFF}\u{200C}\u{200D}\u{2070}\u{218F}\u{2C00}\u{2FEF}\u{3001}\u{D7FF}\u{FA0E}\u{FDCF}\u{FDF0}\u{FFEF}\u{10000}\u{EFFFD}" ]; for e in examples.iter() { if let Err(error) = Iri::parse(*e) { panic!("{} on IRI {}", error, e); } } } #[test] fn test_relative_parsing() { // From https://sourceforge.net/projects/foursuite/ under Apache License let examples = [ "file:///foo/bar", "mailto:user@host?subject=blah", "dav:", // empty opaque part / rel-path allowed by RFC 2396bis "about:", // empty opaque part / rel-path allowed by RFC 2396bis // // the following test cases are from a Perl script by David A. Wheeler // at http://www.dwheeler.com/secure-programs/url.pl "http://www.yahoo.com", "http://www.yahoo.com/", "http://1.2.3.4/", "http://www.yahoo.com/stuff", "http://www.yahoo.com/stuff/", "http://www.yahoo.com/hello%20world/", "http://www.yahoo.com?name=obi", "http://www.yahoo.com?name=obi+wan&status=jedi", "http://www.yahoo.com?onery", "http://www.yahoo.com#bottom", "http://www.yahoo.com/yelp.html#bottom", "https://www.yahoo.com/", "ftp://www.yahoo.com/", "ftp://www.yahoo.com/hello", "demo.txt", "demo/hello.txt", "demo/hello.txt?query=hello#fragment", "/cgi-bin/query?query=hello#fragment", "/demo.txt", "/hello/demo.txt", "hello/demo.txt", "/", "", "#", "#here", // Wheeler"s script says these are invalid, but they aren"t "http://www.yahoo.com?name=%00%01", "http://www.yaho%6f.com", "http://www.yahoo.com/hello%00world/", "http://www.yahoo.com/hello+world/", "http://www.yahoo.com?name=obi&", "http://www.yahoo.com?name=obi&type=", "http://www.yahoo.com/yelp.html#", "//", // the following test cases are from a Haskell program by Graham Klyne // at http://www.ninebynine.org/Software/HaskellUtils/Network/URITest.hs "http://example.org/aaa/bbb#ccc", "mailto:local@domain.org", "mailto:local@domain.org#frag", "HTTP://EXAMPLE.ORG/AAA/BBB#CCC", "//example.org/aaa/bbb#ccc", "/aaa/bbb#ccc", "bbb#ccc", "#ccc", "#", "A'C", //-- escapes "http://example.org/aaa%2fbbb#ccc", "http://example.org/aaa%2Fbbb#ccc", "%2F", "?%2F", "#?%2F", "aaa%2Fbbb", //-- ports "http://example.org:80/aaa/bbb#ccc", "http://example.org:/aaa/bbb#ccc", "http://example.org./aaa/bbb#ccc", "http://example.123./aaa/bbb#ccc", //-- bare authority "http://example.org", //-- IPv6 literals (from RFC2732): "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", "http://[1080:0:0:0:8:800:200C:417A]/index.html", "http://[3ffe:2a00:100:7031::1]", "http://[1080::8:800:200C:417A]/foo", "http://[::192.9.5.5]/ipng", "http://[::FFFF:129.144.52.38]:80/index.html", "http://[2010:836B:4179::836B:4179]", "//[2010:836B:4179::836B:4179]", //-- Random other things that crop up "http://example/Andrȷ", "file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/", // iprivate characters are allowed in query "http://a/?\u{E000}", "?\u{E000}", ]; let base = Iri::parse("http://a/b/c/d;p?q").unwrap(); for e in examples.iter() { if let Err(error) = IriRef::parse(*e) { panic!("{} on relative IRI {}", error, e); } if let Err(error) = base.resolve(*e) { panic!("{} on relative IRI {}", error, e); } } } #[test] fn test_wrong_relative_parsing() { // From https://sourceforge.net/projects/foursuite/ under Apache License let examples = [ "beepbeep\x07\x07", "\n", // "::", // not OK, per Roy Fielding on the W3C uri list on 2004-04-01 // // the following test cases are from a Perl script by David A. Wheeler // at http://www.dwheeler.com/secure-programs/url.pl "http://www yahoo.com", "http://www.yahoo.com/hello world/", "http://www.yahoo.com/yelp.html#\"", // // the following test cases are from a Haskell program by Graham Klyne // at http://www.ninebynine.org/Software/HaskellUtils/Network/URITest.hs "[2010:836B:4179::836B:4179]", " ", "%", "A%Z", "%ZZ", "%AZ", "A C", // "A'C", "A`C", "AC", "A^C", "A\\C", "A{C", "A|C", "A}C", "A[C", "A]C", "A[**]C", "http://[xyz]/", "http://]/", "http://example.org/[2010:836B:4179::836B:4179]", "http://example.org/abc#[2010:836B:4179::836B:4179]", "http://example.org/xxx/[qwerty]#a[b]", // from a post to the W3C uri list on 2004-02-17 "http://w3c.org:80path1/path2", // relative IRIs do not accept colon in the first path segment ":a/b", // iprivate characters are not allowed in path not in fragment "http://example.com/\u{E000}", "\u{E000}", "http://example.com/#\u{E000}", "#\u{E000}", // bad characters "//\u{FFFF}", "?\u{FFFF}", "/\u{0000}", "?\u{0000}", "#\u{0000}", "/\u{E000}", "/\u{F8FF}", "/\u{F0000}", "/\u{FFFFD}", "/\u{100000}", "/\u{10FFFD}", "?\u{FDEF}", "?\u{FFFF}", "/\u{FDEF}", "/\u{FFFF}", "/u{1FFFF}", "/u{2FFFF}", "/u{3FFFF}", "/u{4FFFF}", "/u{5FFFF}", "/u{6FFFF}", "/u{7FFFF}", "/u{8FFFF}", "/u{9FFFF}", "/u{AFFFF}", "/u{BFFFF}", "/u{CFFFF}", "/u{DFFFF}", "/u{EFFFF}", "/u{FFFFF}", // bad host "http://[/", "http://[::1]a/", // fuzzing bugs "//͏@[]", ]; let base = Iri::parse("http://a/b/c/d;p?q").unwrap(); for e in examples.iter() { let result = base.resolve(*e); assert!(result.is_err(), "{} is wrongly considered valid", e); } } #[test] fn test_resolve_relative_iri() { // From https://sourceforge.net/projects/foursuite/ under Apache License let examples = [ // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html ("/.", "http://a/b/c/d;p?q", "http://a/"), ("/.foo", "http://a/b/c/d;p?q", "http://a/.foo"), (".foo", "http://a/b/c/d;p?q", "http://a/b/c/.foo"), // http://gbiv.com/protocols/uri/test/rel_examples1.html // examples from RFC 2396 ("g:h", "http://a/b/c/d;p?q", "g:h"), ("g", "http://a/b/c/d;p?q", "http://a/b/c/g"), ("./g", "http://a/b/c/d;p?q", "http://a/b/c/g"), ("g/", "http://a/b/c/d;p?q", "http://a/b/c/g/"), ("/g", "http://a/b/c/d;p?q", "http://a/g"), ("//g", "http://a/b/c/d;p?q", "http://g"), // changed with RFC 2396bis //("?y" , "http://a/b/c/d;p?q", "http://a/b/c/d;p?y"), ("?y", "http://a/b/c/d;p?q", "http://a/b/c/d;p?y"), ("g?y", "http://a/b/c/d;p?q", "http://a/b/c/g?y"), // changed with RFC 2396bis //("#s" , "http://a/b/c/d;p?q", CURRENT_DOC_URI + "#s"), ("#s", "http://a/b/c/d;p?q", "http://a/b/c/d;p?q#s"), ("g#s", "http://a/b/c/d;p?q", "http://a/b/c/g#s"), ("g?y#s", "http://a/b/c/d;p?q", "http://a/b/c/g?y#s"), (";x", "http://a/b/c/d;p?q", "http://a/b/c/;x"), ("g;x", "http://a/b/c/d;p?q", "http://a/b/c/g;x"), ("g;x?y#s", "http://a/b/c/d;p?q", "http://a/b/c/g;x?y#s"), // changed with RFC 2396bis //("" , "http://a/b/c/d;p?q", CURRENT_DOC_URI), ("", "http://a/b/c/d;p?q", "http://a/b/c/d;p?q"), (".", "http://a/b/c/d;p?q", "http://a/b/c/"), ("./", "http://a/b/c/d;p?q", "http://a/b/c/"), ("..", "http://a/b/c/d;p?q", "http://a/b/"), ("../", "http://a/b/c/d;p?q", "http://a/b/"), ("../g", "http://a/b/c/d;p?q", "http://a/b/g"), ("../..", "http://a/b/c/d;p?q", "http://a/"), ("../../", "http://a/b/c/d;p?q", "http://a/"), ("../../g", "http://a/b/c/d;p?q", "http://a/g"), ("../../../g", "http://a/b/c/d;p?q", "http://a/g"), ("../../../../g", "http://a/b/c/d;p?q", "http://a/g"), // changed with RFC 2396bis ("/./g", "http://a/b/c/d;p?q", "http://a/g"), // changed with RFC 2396bis ("/../g", "http://a/b/c/d;p?q", "http://a/g"), ("g.", "http://a/b/c/d;p?q", "http://a/b/c/g."), (".g", "http://a/b/c/d;p?q", "http://a/b/c/.g"), ("g..", "http://a/b/c/d;p?q", "http://a/b/c/g.."), ("..g", "http://a/b/c/d;p?q", "http://a/b/c/..g"), ("./../g", "http://a/b/c/d;p?q", "http://a/b/g"), ("./g/.", "http://a/b/c/d;p?q", "http://a/b/c/g/"), ("g/./h", "http://a/b/c/d;p?q", "http://a/b/c/g/h"), ("g/../h", "http://a/b/c/d;p?q", "http://a/b/c/h"), ("g;x=1/./y", "http://a/b/c/d;p?q", "http://a/b/c/g;x=1/y"), ("g;x=1/../y", "http://a/b/c/d;p?q", "http://a/b/c/y"), ("g?y/./x", "http://a/b/c/d;p?q", "http://a/b/c/g?y/./x"), ("g?y/../x", "http://a/b/c/d;p?q", "http://a/b/c/g?y/../x"), ("g#s/./x", "http://a/b/c/d;p?q", "http://a/b/c/g#s/./x"), ("g#s/../x", "http://a/b/c/d;p?q", "http://a/b/c/g#s/../x"), ("http:g", "http://a/b/c/d;p?q", "http:g"), ("http:", "http://a/b/c/d;p?q", "http:"), // not sure where this one originated ("/a/b/c/./../../g", "http://a/b/c/d;p?q", "http://a/a/g"), // http://gbiv.com/protocols/uri/test/rel_examples2.html // slashes in base URI"s query args ("g", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g"), ("./g", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g"), ("g/", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g/"), ("/g", "http://a/b/c/d;p?q=1/2", "http://a/g"), ("//g", "http://a/b/c/d;p?q=1/2", "http://g"), // changed in RFC 2396bis ("?y", "http://a/b/c/d;p?q=1/2", "http://a/b/c/d;p?y"), ("g?y", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g?y"), ("g?y/./x", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g?y/./x"), ( "g?y/../x", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g?y/../x", ), ("g#s", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g#s"), ("g#s/./x", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g#s/./x"), ( "g#s/../x", "http://a/b/c/d;p?q=1/2", "http://a/b/c/g#s/../x", ), ("./", "http://a/b/c/d;p?q=1/2", "http://a/b/c/"), ("../", "http://a/b/c/d;p?q=1/2", "http://a/b/"), ("../g", "http://a/b/c/d;p?q=1/2", "http://a/b/g"), ("../../", "http://a/b/c/d;p?q=1/2", "http://a/"), ("../../g", "http://a/b/c/d;p?q=1/2", "http://a/g"), // http://gbiv.com/protocols/uri/test/rel_examples3.html // slashes in path params // all of these changed in RFC 2396bis ("g", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g"), ("./g", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g"), ("g/", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g/"), ("g?y", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g?y"), (";x", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/;x"), ("g;x", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g;x"), ( "g;x=1/./y", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/g;x=1/y", ), ( "g;x=1/../y", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/y", ), ("./", "http://a/b/c/d;p=1/2?q", "http://a/b/c/d;p=1/"), ("../", "http://a/b/c/d;p=1/2?q", "http://a/b/c/"), ("../g", "http://a/b/c/d;p=1/2?q", "http://a/b/c/g"), ("../../", "http://a/b/c/d;p=1/2?q", "http://a/b/"), ("../../g", "http://a/b/c/d;p=1/2?q", "http://a/b/g"), // http://gbiv.com/protocols/uri/test/rel_examples4.html // double and triple slash, unknown scheme ("g:h", "fred:///s//a/b/c", "g:h"), ("g", "fred:///s//a/b/c", "fred:///s//a/b/g"), ("./g", "fred:///s//a/b/c", "fred:///s//a/b/g"), ("g/", "fred:///s//a/b/c", "fred:///s//a/b/g/"), ("/g", "fred:///s//a/b/c", "fred:///g"), // may change to fred:///s//a/g ("//g", "fred:///s//a/b/c", "fred://g"), // may change to fred:///s//g ("//g/x", "fred:///s//a/b/c", "fred://g/x"), // may change to fred:///s//g/x ("///g", "fred:///s//a/b/c", "fred:///g"), ("./", "fred:///s//a/b/c", "fred:///s//a/b/"), ("../", "fred:///s//a/b/c", "fred:///s//a/"), ("../g", "fred:///s//a/b/c", "fred:///s//a/g"), ("../../", "fred:///s//a/b/c", "fred:///s//"), // may change to fred:///s//a/../ ("../../g", "fred:///s//a/b/c", "fred:///s//g"), // may change to fred:///s//a/../g ("../../../g", "fred:///s//a/b/c", "fred:///s/g"), // may change to fred:///s//a/../../g ("../../../../g", "fred:///s//a/b/c", "fred:///g"), // may change to fred:///s//a/../../../g // http://gbiv.com/protocols/uri/test/rel_examples5.html // double and triple slash, well-known scheme ("g:h", "http:///s//a/b/c", "g:h"), ("g", "http:///s//a/b/c", "http:///s//a/b/g"), ("./g", "http:///s//a/b/c", "http:///s//a/b/g"), ("g/", "http:///s//a/b/c", "http:///s//a/b/g/"), ("/g", "http:///s//a/b/c", "http:///g"), // may change to http:///s//a/g ("//g", "http:///s//a/b/c", "http://g"), // may change to http:///s//g ("//g/x", "http:///s//a/b/c", "http://g/x"), // may change to http:///s//g/x ("///g", "http:///s//a/b/c", "http:///g"), ("./", "http:///s//a/b/c", "http:///s//a/b/"), ("../", "http:///s//a/b/c", "http:///s//a/"), ("../g", "http:///s//a/b/c", "http:///s//a/g"), ("../../", "http:///s//a/b/c", "http:///s//"), // may change to http:///s//a/../ ("../../g", "http:///s//a/b/c", "http:///s//g"), // may change to http:///s//a/../g ("../../../g", "http:///s//a/b/c", "http:///s/g"), // may change to http:///s//a/../../g ("../../../../g", "http:///s//a/b/c", "http:///g"), // may change to http:///s//a/../../../g // from Dan Connelly"s tests in http://www.w3.org/2000/10/swap/uripath.py ("bar:abc", "foo:xyz", "bar:abc"), ("../abc", "http://example/x/y/z", "http://example/x/abc"), ( "http://example/x/abc", "http://example2/x/y/z", "http://example/x/abc", ), ("../r", "http://ex/x/y/z", "http://ex/x/r"), ("q/r", "http://ex/x/y", "http://ex/x/q/r"), ("q/r#s", "http://ex/x/y", "http://ex/x/q/r#s"), ("q/r#s/t", "http://ex/x/y", "http://ex/x/q/r#s/t"), ("ftp://ex/x/q/r", "http://ex/x/y", "ftp://ex/x/q/r"), ("", "http://ex/x/y", "http://ex/x/y"), ("", "http://ex/x/y/", "http://ex/x/y/"), ("", "http://ex/x/y/pdq", "http://ex/x/y/pdq"), ("z/", "http://ex/x/y/", "http://ex/x/y/z/"), ( "#Animal", "file:/swap/test/animal.rdf", "file:/swap/test/animal.rdf#Animal", ), ("../abc", "file:/e/x/y/z", "file:/e/x/abc"), ( "/example/x/abc", "file:/example2/x/y/z", "file:/example/x/abc", ), ("../r", "file:/ex/x/y/z", "file:/ex/x/r"), ("/r", "file:/ex/x/y/z", "file:/r"), ("q/r", "file:/ex/x/y", "file:/ex/x/q/r"), ("q/r#s", "file:/ex/x/y", "file:/ex/x/q/r#s"), ("q/r#", "file:/ex/x/y", "file:/ex/x/q/r#"), ("q/r#s/t", "file:/ex/x/y", "file:/ex/x/q/r#s/t"), ("ftp://ex/x/q/r", "file:/ex/x/y", "ftp://ex/x/q/r"), ("", "file:/ex/x/y", "file:/ex/x/y"), ("", "file:/ex/x/y/", "file:/ex/x/y/"), ("", "file:/ex/x/y/pdq", "file:/ex/x/y/pdq"), ("z/", "file:/ex/x/y/", "file:/ex/x/y/z/"), ( "file://meetings.example.com/cal#m1", "file:/devel/WWW/2000/10/swap/test/reluri-1.n3", "file://meetings.example.com/cal#m1", ), ( "file://meetings.example.com/cal#m1", "file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3", "file://meetings.example.com/cal#m1", ), ("./#blort", "file:/some/dir/foo", "file:/some/dir/#blort"), ("./#", "file:/some/dir/foo", "file:/some/dir/#"), // Ryan Lee ("./", "http://example/x/abc.efg", "http://example/x/"), // Graham Klyne"s tests // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls // 01-31 are from Connelly"s cases // 32-49 ("./q:r", "http://ex/x/y", "http://ex/x/q:r"), ("./p=q:r", "http://ex/x/y", "http://ex/x/p=q:r"), ("?pp/rr", "http://ex/x/y?pp/qq", "http://ex/x/y?pp/rr"), ("y/z", "http://ex/x/y?pp/qq", "http://ex/x/y/z"), ("y?q", "http://ex/x/y?q", "http://ex/x/y?q"), ("/x/y?q", "http://ex?p", "http://ex/x/y?q"), /*("c/d", "foo:a/b", "foo:a/c/d"), ("/c/d", "foo:a/b", "foo:/c/d"), ("", "foo:a/b?c#d", "foo:a/b?c"), ("b/c", "foo:a", "foo:b/c"),*/ ("../b/c", "foo:/a/y/z", "foo:/a/b/c"), //("./b/c", "foo:a", "foo:b/c"), //("/./b/c", "foo:a", "foo:/b/c"), ("../../d", "foo://a//b/c", "foo://a/d"), //(".", "foo:a", "foo:"), //("..", "foo:a", "foo:"), // 50-57 (cf. TimBL comments -- // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) ("abc", "http://example/x/y%2Fz", "http://example/x/abc"), ( "../../x%2Fabc", "http://example/a/x/y/z", "http://example/a/x%2Fabc", ), ( "../x%2Fabc", "http://example/a/x/y%2Fz", "http://example/a/x%2Fabc", ), ("abc", "http://example/x%2Fy/z", "http://example/x%2Fy/abc"), ("q%3Ar", "http://ex/x/y", "http://ex/x/q%3Ar"), ( "/x%2Fabc", "http://example/x/y%2Fz", "http://example/x%2Fabc", ), ("/x%2Fabc", "http://example/x/y/z", "http://example/x%2Fabc"), ( "/x%2Fabc", "http://example/x/y%2Fz", "http://example/x%2Fabc", ), // 70-77 ( "http://example/a/b?c/../d", "foo:bar", "http://example/a/b?c/../d", ), ( "http://example/a/b#c/../d", "foo:bar", "http://example/a/b#c/../d", ), // 82-88 ("http:this", "http://example.org/base/uri", "http:this"), ("http:this", "http:base", "http:this"), ( "mini1.xml", "file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/", "file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml", ), // More bad test by Rio ("?bar", "file:foo", "file:foo?bar"), ("#bar", "file:foo", "file:foo#bar"), ("/lv2.h", "file:foo", "file:/lv2.h"), ("/lv2.h", "file:foo", "file:/lv2.h"), ("///lv2.h", "file:foo", "file:///lv2.h"), ("lv2.h", "file:foo", "file:lv2.h"), ("s", "http://example.com", "http://example.com/s"), ]; for (relative, base, output) in examples.iter() { let base = Iri::parse(*base).unwrap(); match base.resolve(*relative) { Ok(result) => assert_eq!( result.as_str(), *output, "Resolving of {} against {} is wrong. Found {} and expecting {}", relative, base, result, output ), Err(error) => panic!( "Resolving of {} against {} failed with error: {}", relative, base, error ), } } } #[test] fn test_eq() { let iri = Iri::parse("http://example.com").unwrap(); assert_eq!(iri, iri); assert_eq!(iri, "http://example.com"); assert_eq!("http://example.com", iri); assert_eq!(hash(iri), hash("http://example.com")); } fn hash(value: impl Hash) -> u64 { let mut hasher = DefaultHasher::new(); value.hash(&mut hasher); hasher.finish() } #[test] fn test_str() { let iri = Iri::parse("http://example.com").unwrap(); assert!(iri.starts_with("http://")); } #[cfg(feature = "serde")] #[test] fn test_iriref_serde_impl() { assert_tokens( &IriRef::parse("//example.com").unwrap(), &[Token::BorrowedStr("//example.com")], ); assert_tokens( &IriRef::parse("//example.com".to_string()).unwrap(), &[Token::String("//example.com")], ); assert_de_tokens( &IriRef::parse("//example.com".to_string()).unwrap(), &[Token::BorrowedStr("//example.com")], ); assert_de_tokens_error::>( &[Token::String(":")], "No scheme found in an absolute IRI", ); } #[cfg(feature = "serde")] #[test] fn test_iri_serde_impl() { assert_tokens( &Iri::parse("http://example.com").unwrap(), &[Token::BorrowedStr("http://example.com")], ); assert_tokens( &Iri::parse("http://example.com".to_string()).unwrap(), &[Token::String("http://example.com")], ); assert_de_tokens( &Iri::parse("http://example.com".to_string()).unwrap(), &[Token::BorrowedStr("http://example.com")], ); assert_de_tokens_error::>( &[Token::String(":")], "No scheme found in an absolute IRI", ); assert_de_tokens_error::>( &[Token::String("//example.com")], "No scheme found in an absolute IRI", ); }