linkify-0.9.0/.cargo_vcs_info.json 0000644 00000000136 00000000001 0012507 0 ustar {
"git": {
"sha1": "3be62ab5cb024d37455044cf9f1851f76fa72cae"
},
"path_in_vcs": ""
} linkify-0.9.0/.gitignore 0000644 0000000 0000000 00000000126 00726746425 0013316 0 ustar 0000000 0000000 # cargo
target
Cargo.lock
# MacOS
.DS_Store
# IDEA
.idea/
*.iml
# VS Code
.vscode/
linkify-0.9.0/CHANGELOG.md 0000644 0000000 0000000 00000010025 00726746425 0013136 0 ustar 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html),
with the exception that 0.x versions can break between minor versions.
## [0.9.0] - 2022-07-11
### Changed
- More strict parsing of hostname (authority) part of URLs. Applies to
emails, plain domains URLs (e.g. `example.com/foo`) and URLs with
schemes where a host is expected (e.g. `https`).
This fixes a few problems that have been reported over time, namely:
- `https://www.example..com` is no longer parsed as an URL (#41)
- `foo@v1.1.1` is no longer parsed as an email address (#29)
- `https://*.example.org` is no longer parsed as an URL (#38)
It's a tricky change and hopefully this solves some problems while
not introducing too many new ones. If anything unexpectedly changed
for you, please let us know!
## [0.8.1] - 2022-04-14
### Changed
- Skip parsing very short strings for URLs as a performance optimization
## [0.8.0] - 2021-11-26
### Added
- New option `url_must_have_scheme` on `LinkFinder` that can be set to
`false` to allow URLs without scheme/protocol such as `example.com`.
Note that there is no allowlist for top-level domains, if you want
that you will have to implement it yourself.
### Changed
- Bump MSRV (minimum supported Rust version) to 1.46
## [0.7.0] - 2021-05-18
### Changed
- URLs that have a quote character like `'` or `"` before them will stop
when that quote character is encountered, e.g. in
`"https://example.org/","`, the URL will not include any quotes. Before,
it would run until the end because the quotes after the slash were an
even number. (#20)
- Bump MSRV (minimum supported Rust version) to 1.41
## [0.6.0] - 2021-04-09
### Changed
- Stop URLs when encountering `|`. Consistent with RFC and will
hopefully not cause problems with real URLs.
## [0.5.0] - 2021-02-13
### Changed
- Treat `*` as a delimiter like `.` or `,`, which means they can be part
of an URL but not at the end.
## [0.4.0] - 2019-08-05
### Changed
- Stop URLs when encountering ". This is consistent with RFC 3986, and
it seems unlikely that a user would have an unescaped " in an URL
anyway, as browsers escape it when copying an URL with it.
- Stop URLs at \` characters too, same as < and >
- Bump MSRV (minimum supported Rust version) to 1.31 (2018 edition)
## [0.3.1] - 2018-02-04
### Changed
- Bump memchr dependency to 2 (for wasm support)
## [0.3.0] - 2018-01-25
### Added
- New API to iterate over both plain text and link spans using the
`spans` method. This is useful for iterating over all parts of the
input, not just the detected links. Thanks @srijs!
## [0.2.0] - 2017-09-18
### Changed
- Don't autolink if authority is only "end" characters, e.g. like
`http://.` or `http://"`
## [0.1.2] - 2017-06-09
### Fixed
- Fix `html_root_url` attribute
## [0.1.1] - 2017-06-08
### Added
- More docs
- Add `Debug` impls for `Links` and `LinkFinder`
## [0.1.0] - 2017-05-13
### Added
Initial release of linkify, a Rust library to find links such as URLs and email
addresses in plain text, handling surrounding punctuation correctly.
[0.9.0]: https://github.com/robinst/linkify/compare/0.8.1...0.9.0
[0.8.1]: https://github.com/robinst/linkify/compare/0.8.0...0.8.1
[0.8.0]: https://github.com/robinst/linkify/compare/0.7.0...0.8.0
[0.7.0]: https://github.com/robinst/linkify/compare/0.6.0...0.7.0
[0.6.0]: https://github.com/robinst/linkify/compare/0.5.0...0.6.0
[0.5.0]: https://github.com/robinst/linkify/compare/0.4.0...0.5.0
[0.4.0]: https://github.com/robinst/linkify/compare/0.3.1...0.4.0
[0.3.1]: https://github.com/robinst/linkify/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/robinst/linkify/compare/0.2.0...0.3.0
[0.2.0]: https://github.com/robinst/linkify/compare/0.1.2...0.2.0
[0.1.2]: https://github.com/robinst/linkify/compare/0.1.1...0.1.2
[0.1.1]: https://github.com/robinst/linkify/compare/0.1.0...0.1.1
[0.1.0]: https://github.com/robinst/linkify/commits/0.1.0
linkify-0.9.0/Cargo.toml 0000644 00000002364 00000000001 0010512 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "linkify"
version = "0.9.0"
authors = ["Robin Stocker "]
exclude = ["/.github"]
description = "Finds URLs and email addresses in plain text. Takes care to get the boundaries right with surrounding punctuation like parentheses."
homepage = "https://github.com/robinst/linkify"
documentation = "https://docs.rs/linkify"
readme = "README.md"
keywords = [
"web",
"text",
"url",
"links",
]
categories = ["text-processing"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/robinst/linkify"
[[bench]]
name = "bench"
harness = false
[dependencies.memchr]
version = "2.0.1"
[dev-dependencies.criterion]
version = "0.3"
[dev-dependencies.doc-comment]
version = "0.3.3"
[dev-dependencies.plotters-backend]
version = "= 0.3.2"
linkify-0.9.0/Cargo.toml.orig 0000644 0000000 0000000 00000001406 00726746425 0014217 0 ustar 0000000 0000000 [package]
name = "linkify"
version = "0.9.0" # remember to update html_root_url
authors = ["Robin Stocker "]
edition = "2018"
license = "MIT OR Apache-2.0"
readme = "README.md"
repository = "https://github.com/robinst/linkify"
homepage = "https://github.com/robinst/linkify"
documentation = "https://docs.rs/linkify"
description = "Finds URLs and email addresses in plain text. Takes care to get the boundaries right with surrounding punctuation like parentheses."
categories = ["text-processing"]
keywords = ["web", "text", "url", "links"]
exclude = ["/.github"]
[dependencies]
memchr = "2.0.1"
[dev-dependencies]
criterion = "0.3"
plotters-backend = "= 0.3.2" # 0.3.4 requires later Rust
doc-comment = "0.3.3"
[[bench]]
name = "bench"
harness = false
linkify-0.9.0/LICENSE-APACHE 0000644 0000000 0000000 00000025137 00726746425 0013263 0 ustar 0000000 0000000 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.
linkify-0.9.0/LICENSE-MIT 0000644 0000000 0000000 00000002056 00726746425 0012766 0 ustar 0000000 0000000 MIT License
Copyright (c) 2017 Robin Stocker
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.
linkify-0.9.0/README.md 0000644 0000000 0000000 00000010041 00726746425 0012602 0 ustar 0000000 0000000 Linkify
=======
Linkify is a Rust library to find links such as URLs and email addresses in
plain text. It's smart about where a link ends, such as with trailing
punctuation.
[](https://docs.rs/linkify)
[](https://crates.io/crates/linkify)
[](https://github.com/robinst/linkify/actions?query=workflow%3Aci)
[](https://codecov.io/gh/robinst/linkify)
## Introduction
Your reaction might be: "Do I need a library for this? Why not a regex?".
Let's look at a few cases:
* In `http://example.com/.` the link should not include the trailing dot
* `http://example.com/,` should not include the trailing comma
* `(http://example.com/)` should not include the parens
Seems simple enough. But then we also have these cases:
* `https://en.wikipedia.org/wiki/Link_(The_Legend_of_Zelda)` should include the trailing paren
* `http://üñîçøðé.com/ä` should also work for Unicode (including Emoji and Punycode)
* `` should not include angle brackets
This library behaves as you'd expect in the above cases and many more.
It uses a simple scan with linear runtime.
In addition to URLs, it can also find email addresses.
## Demo 🧑🔬
Try it out online on the demo playground (Rust compiled to WebAssembly):
https://robinst.github.io/linkify/
If you want to use it on the command line, try [lychee](https://github.com/lycheeverse/lychee).
It uses linkify to extract all links and checks if they're valid, but it can also just print them like this:
```shell
$ echo 'Test https://example.org (and https://example.com)' | lychee --dump -
https://example.org/
https://example.com/
```
## Usage
Basic usage:
```rust
extern crate linkify;
use linkify::{LinkFinder, LinkKind};
let input = "Have you seen http://example.com?";
let finder = LinkFinder::new();
let links: Vec<_> = finder.links(input).collect();
assert_eq!(1, links.len());
let link = &links[0];
assert_eq!("http://example.com", link.as_str());
assert_eq!(14, link.start());
assert_eq!(32, link.end());
assert_eq!(&LinkKind::Url, link.kind());
```
Option to allow URLs without schemes:
```rust
use linkify::LinkFinder;
let input = "Look, no scheme: example.org/foo";
let mut finder = LinkFinder::new();
// true by default
finder.url_must_have_scheme(false);
let links: Vec<_> = finder.links(input).collect();
assert_eq!(links[0].as_str(), "example.org/foo");
```
Restrict the kinds of links:
```rust
use linkify::{LinkFinder, LinkKind};
let input = "http://example.com and foo@example.com";
let mut finder = LinkFinder::new();
finder.kinds(&[LinkKind::Email]);
let links: Vec<_> = finder.links(input).collect();
assert_eq!(1, links.len());
let link = &links[0];
assert_eq!("foo@example.com", link.as_str());
assert_eq!(&LinkKind::Email, link.kind());
```
See full documentation on [docs.rs](https://docs.rs/linkify).
## Conformance
This crates makes an effort to respect the various standards, namely:
* [RFC 3986] and [RFC 3987] for URLs
* [RFC 5321] and [RFC 6531] for email addresses (except IP addresses and quoting)
At the same time, it does not guarantee that the returned links are valid.
If in doubt, it rather returns a link than skipping it.
If you need to validate URLs, e.g. for checking TLDs, use another library on
the returned links.
## Contributing
Pull requests, issues and comments welcome! Make sure to add tests for
new features and bug fixes.
## License
Linkify is distributed under the terms of both the MIT license and the
Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE) and
[LICENSE-MIT](LICENSE-MIT) for details. Opening a pull requests is
assumed to signal agreement with these licensing terms.
[RFC 3986]: https://datatracker.ietf.org/doc/html/rfc3986
[RFC 3987]: https://datatracker.ietf.org/doc/html/rfc3987
[RFC 5321]: https://datatracker.ietf.org/doc/html/rfc5321
[RFC 6531]: https://datatracker.ietf.org/doc/html/rfc6531
linkify-0.9.0/benches/bench.rs 0000644 0000000 0000000 00000004545 00726746425 0014373 0 ustar 0000000 0000000 use criterion::{criterion_group, criterion_main, Criterion};
use linkify::LinkFinder;
fn no_links(c: &mut Criterion) {
c.bench_function("no_links", |b| {
let link_finder = LinkFinder::new();
b.iter(|| {
let links = link_finder.links(
"This is a text with no links in it. But: it has a colon.\
Lorem ipsum dolor sit amet, consectetur adipiscing elit.\
Curabitur luctus tincidunt diam.",
);
assert_eq!(links.count(), 0);
});
});
}
fn some_links(c: &mut Criterion) {
c.bench_function("some_links", |b| {
let link_finder = LinkFinder::new();
b.iter(|| {
let links = link_finder.links(
"This is a text with links in it. Here's one: http://www.example.com/. \
How about another one? (Maybe like this http://example.com/foo_(bar)) \
a+b://example.com/foo+bar+baz",
);
assert_eq!(links.count(), 3);
});
});
}
fn heaps_of_links(c: &mut Criterion) {
c.bench_function("heaps_of_links", |b| {
let link_finder = LinkFinder::new();
b.iter(|| {
let links = link_finder.links(
"http://www.example.com/a, http://www.example.com/b, http://www.example.com/c \
http://www.example.com/a: http://www.example.com/b: http://www.example.com/c \
http://www.example.com/a http://www.example.com/b http://www.example.com/c \
http://www.example.com/a< http://www.example.com/b< http://www.example.com/c<",
);
assert_eq!(links.count(), 12);
});
});
}
fn some_links_without_scheme(c: &mut Criterion) {
c.bench_function("some_links_without_scheme", |b| {
let mut link_finder = LinkFinder::new();
link_finder.url_must_have_scheme(false);
b.iter(|| {
let links = link_finder.links(
"This is a text with links in it. Here's one: http://www.example.com/. \
How about another one? (Maybe like this http://example.com/foo_(bar)). \
example.com/one/two/three/four",
);
assert_eq!(links.count(), 3);
});
});
}
criterion_group!(
benches,
no_links,
some_links,
heaps_of_links,
some_links_without_scheme
);
criterion_main!(benches);
linkify-0.9.0/src/domains.rs 0000644 0000000 0000000 00000014132 00726746425 0014117 0 ustar 0000000 0000000 //! Domain name related scanning, used by both email and URL scanners.
//!
//! This is called domains for familiarity but it's about the authority part of URLs as defined in
//! https://datatracker.ietf.org/doc/html/rfc3986#section-3.2
//!
//! ```text
//! authority = [ userinfo "@" ] host [ ":" port ]
//!
//!
//! userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
//!
//! host = IP-literal / IPv4address / reg-name
//!
//! IP-literal = "[" ( IPv6address / IPvFuture ) "]"
//!
//! IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
//!
//! reg-name = *( unreserved / pct-encoded / sub-delims )
//!
//!
//! unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
//!
//! sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
//!
//! pct-encoded = "%" HEXDIG HEXDIG
//! ```
use std::char;
pub(crate) fn find_authority_end(
s: &str,
mut userinfo_allowed: bool,
require_host: bool,
port_allowed: bool,
) -> (Option, Option) {
let mut end = Some(0);
let mut maybe_last_dot = None;
let mut last_dot = None;
let mut dot_allowed = false;
let mut hyphen_allowed = false;
let mut all_numeric = true;
let mut maybe_host = true;
let mut host_ended = false;
for (i, c) in s.char_indices() {
let can_be_last = match c {
// ALPHA
'a'..='z' | 'A'..='Z' | '\u{80}'..=char::MAX => {
// Can start or end a domain label, but not numeric
dot_allowed = true;
hyphen_allowed = true;
last_dot = maybe_last_dot;
all_numeric = false;
if host_ended {
maybe_host = false;
}
!require_host || !host_ended
}
// DIGIT
'0'..='9' => {
// Same as above, except numeric
dot_allowed = true;
hyphen_allowed = true;
last_dot = maybe_last_dot;
if host_ended {
maybe_host = false;
}
!require_host || !host_ended
}
// unreserved
'-' => {
// Hyphen can't be at start of a label, e.g. `-b` in `a.-b.com`
if !hyphen_allowed {
maybe_host = false;
}
// Hyphen can't be at end of a label, e.g. `b-` in `a.b-.com`
dot_allowed = false;
all_numeric = false;
!require_host
}
'.' => {
if !dot_allowed {
// Label can't be empty, e.g. `.example.com` or `a..com`
host_ended = true;
}
dot_allowed = false;
hyphen_allowed = false;
maybe_last_dot = Some(i);
false
}
'_' | '~' => {
// Hostnames can't contain these and we don't want to treat them as delimiters.
maybe_host = false;
false
}
// sub-delims
'!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' => {
// Can't be in hostnames, but we treat them as delimiters
host_ended = true;
if !userinfo_allowed && require_host {
// We don't have to look further
break;
}
false
}
':' => {
// Could be in userinfo, or we're getting a port now.
if !userinfo_allowed && !port_allowed {
break;
}
// Don't advance the last dot when we get to port numbers
maybe_last_dot = last_dot;
false
}
'@' => {
if !userinfo_allowed {
// We already had userinfo, can't have another `@` in a valid authority.
return (None, None);
}
// Sike! Everything before this has been userinfo, so let's reset our
// opinions about all the host bits.
userinfo_allowed = false;
maybe_last_dot = None;
last_dot = None;
dot_allowed = false;
hyphen_allowed = false;
all_numeric = true;
maybe_host = true;
host_ended = false;
false
}
'/' => {
if !require_host {
// For schemes where we allow anything, we want to stop at delimiter characters
// except if we get a slash closing the URL, which happened here.
end = Some(i);
}
break;
}
_ => {
// Anything else, this might be the end of the authority (can be empty).
// Now let the rest of the code handle checking whether the end of the URL is
// valid.
break;
}
};
if can_be_last {
end = Some(i + c.len_utf8());
}
}
if require_host {
if maybe_host {
// Can't have just a number without dots as the authority
if all_numeric && last_dot.is_none() && end != Some(0) {
return (None, None);
}
// If we have something that is not just numeric (not an IP address),
// check that the TLD looks reasonable. This is to avoid linking things like
// `abc@v1.1`.
if !all_numeric {
if let Some(last_dot) = last_dot {
if !valid_tld(&s[last_dot + 1..]) {
return (None, None);
}
}
}
return (end, last_dot);
} else {
return (None, None);
}
} else {
return (end, last_dot);
}
}
fn valid_tld(tld: &str) -> bool {
tld.chars()
.take_while(|c| c.is_ascii_alphabetic())
.take(2)
.count()
>= 2
}
linkify-0.9.0/src/email.rs 0000644 0000000 0000000 00000004767 00726746425 0013571 0 ustar 0000000 0000000 use std::ops::Range;
use crate::domains::find_authority_end;
use crate::scanner::Scanner;
/// Scan for email address starting from the trigger character "@".
///
/// Based on RFC 6531, but also accepts invalid IDNs. Doesn't try to handle IP addresses in domain part or
/// quoting in local part.
pub struct EmailScanner {
pub domain_must_have_dot: bool,
}
impl Scanner for EmailScanner {
fn scan(&self, s: &str, at: usize) -> Option> {
if let Some(start) = self.find_start(&s[0..at]) {
let after = at + 1;
if let Some(end) = self.find_end(&s[after..]) {
let range = Range {
start,
end: after + end,
};
return Some(range);
}
}
None
}
}
impl EmailScanner {
// See "Local-part" in RFC 5321, plus extensions in RFC 6531
fn find_start(&self, s: &str) -> Option {
let mut first = None;
let mut atom_boundary = true;
for (i, c) in s.char_indices().rev() {
if Self::local_atom_allowed(c) {
first = Some(i);
atom_boundary = false;
} else if c == '.' {
if atom_boundary {
break;
}
atom_boundary = true;
} else if c == '@' {
// In `@me@a.com`, we don't want to extract `me@a.com`.
return None;
} else {
break;
}
}
first
}
// See "Domain" in RFC 5321, plus extension of "sub-domain" in RFC 6531
fn find_end(&self, s: &str) -> Option {
if let (Some(end), last_dot) = find_authority_end(s, false, true, false) {
if !self.domain_must_have_dot || last_dot.is_some() {
Some(end)
} else {
None
}
} else {
None
}
}
// See "Atom" in RFC 5321, "atext" in RFC 5322
fn local_atom_allowed(c: char) -> bool {
match c {
'a'..='z'
| 'A'..='Z'
| '0'..='9'
| '!'
| '#'
| '$'
| '%'
| '&'
| '\''
| '*'
| '+'
| '-'
| '/'
| '='
| '?'
| '^'
| '_'
| '`'
| '{'
| '|'
| '}'
| '~' => true,
_ => c >= '\u{80}',
}
}
}
linkify-0.9.0/src/finder.rs 0000644 0000000 0000000 00000022434 00726746425 0013740 0 ustar 0000000 0000000 use std::fmt;
use std::iter::Peekable;
use memchr::{memchr, memchr2, memchr3};
use crate::email::EmailScanner;
use crate::scanner::Scanner;
use crate::url::{DomainScanner, UrlScanner};
/// A link found in the input text.
#[derive(Debug)]
pub struct Link<'t> {
text: &'t str,
start: usize,
end: usize,
kind: LinkKind,
}
impl<'t> Link<'t> {
/// The start index of the link within the input text.
#[inline]
pub fn start(&self) -> usize {
self.start
}
/// The end index of the link.
#[inline]
pub fn end(&self) -> usize {
self.end
}
/// Get the link text as a `str`.
#[inline]
pub fn as_str(&self) -> &'t str {
&self.text[self.start..self.end]
}
/// The type of the link.
#[inline]
pub fn kind(&self) -> &LinkKind {
&self.kind
}
}
/// The type of link that was found.
#[derive(Debug, Eq, PartialEq)]
pub enum LinkKind {
/// URL links like "http://example.org".
Url,
/// E-mail links like "foo@example.org"
Email,
/// Users should not exhaustively match this enum, because more link types
/// may be added in the future.
#[doc(hidden)]
__Nonexhaustive,
}
/// Span within the input text.
///
/// A span represents a substring of the input text,
/// which can either be a link, or plain text.
#[derive(Debug)]
pub struct Span<'t> {
text: &'t str,
start: usize,
end: usize,
kind: Option,
}
impl<'t> Span<'t> {
/// The start index of the span within the input text.
#[inline]
pub fn start(&self) -> usize {
self.start
}
/// The end index of the span.
#[inline]
pub fn end(&self) -> usize {
self.end
}
/// Get the span text as a `str`.
#[inline]
pub fn as_str(&self) -> &'t str {
&self.text[self.start..self.end]
}
/// The type of link included in the span, if any.
///
/// Returns `None` if the span represents plain text.
#[inline]
pub fn kind(&self) -> Option<&LinkKind> {
self.kind.as_ref()
}
}
/// A configured link finder.
#[derive(Debug)]
pub struct LinkFinder {
email: bool,
email_domain_must_have_dot: bool,
url: bool,
url_must_have_scheme: bool,
}
/// Iterator for finding links.
pub struct Links<'t> {
text: &'t str,
rewind: usize,
trigger_finder: Box Option>,
email_scanner: EmailScanner,
url_scanner: UrlScanner,
domain_scanner: DomainScanner,
}
/// Iterator over spans.
pub struct Spans<'t> {
text: &'t str,
position: usize,
links: Peekable>,
}
impl LinkFinder {
/// Create a new link finder with the default options for finding all kinds
/// of links.
///
/// If you only want to find a certain kind of links, use the `kinds` method.
pub fn new() -> LinkFinder {
LinkFinder {
email: true,
email_domain_must_have_dot: true,
url: true,
url_must_have_scheme: true,
}
}
/// Require the domain parts of email addresses to have at least one dot.
/// Use `false` to also find addresses such as `root@localhost`.
pub fn email_domain_must_have_dot(&mut self, value: bool) -> &mut LinkFinder {
self.email_domain_must_have_dot = value;
self
}
/// Set whether URLs must have a scheme, defaults to `true`.
///
/// By default only URLs having a scheme defined are found.
/// By setting this to `false` you make the scheme of URLs optional, to also find URLs like
/// `example.org`. For some URLs the used scheme is important, and making the scheme optional
/// may lead to finding a lot of false positive URLs.
pub fn url_must_have_scheme(&mut self, url_must_have_scheme: bool) -> &mut LinkFinder {
self.url_must_have_scheme = url_must_have_scheme;
self
}
/// Restrict the kinds of links that should be found to the specified ones.
pub fn kinds(&mut self, kinds: &[LinkKind]) -> &mut LinkFinder {
self.email = false;
self.url = false;
for kind in kinds {
match *kind {
LinkKind::Email => self.email = true,
LinkKind::Url => self.url = true,
_ => {}
}
}
self
}
/// Find links in the specified input text.
///
/// Returns an `Iterator` which only scans when `next` is called (lazy).
pub fn links<'t>(&self, text: &'t str) -> Links<'t> {
Links::new(
text,
self.url,
self.url_must_have_scheme,
self.email,
self.email_domain_must_have_dot,
)
}
/// Iterate over spans in the specified input text.
///
/// A span represents a substring of the input text,
/// which can either be a link, or plain text.
///
/// Returns an `Iterator` which only scans when `next` is called (lazy).
///
/// The spans that are returned by the `Iterator` are consecutive,
/// and when combined represent the input text in its entirety.
pub fn spans<'t>(&self, text: &'t str) -> Spans<'t> {
Spans {
text,
position: 0,
links: self.links(text).peekable(),
}
}
}
impl Default for LinkFinder {
fn default() -> Self {
LinkFinder::new()
}
}
impl<'t> Links<'t> {
fn new(
text: &'t str,
url: bool,
url_must_have_scheme: bool,
email: bool,
email_domain_must_have_dot: bool,
) -> Links<'t> {
let url_scanner = UrlScanner;
let domain_scanner = DomainScanner;
let email_scanner = EmailScanner {
domain_must_have_dot: email_domain_must_have_dot,
};
// With optional schemes URLs don't have unique `:`, then search for `.` as well
let trigger_finder: Box Option> = match (url, email) {
(true, true) if url_must_have_scheme => Box::new(|s| memchr2(b':', b'@', s)),
(true, true) => Box::new(|s| memchr3(b':', b'@', b'.', s)),
(true, false) if url_must_have_scheme => Box::new(|s| memchr(b':', s)),
(true, false) => Box::new(|s| memchr2(b':', b'.', s)),
(false, true) => Box::new(|s| memchr(b'@', s)),
(false, false) => Box::new(|_| None),
};
Links {
text,
rewind: 0,
trigger_finder,
email_scanner,
url_scanner,
domain_scanner,
}
}
}
impl<'t> Iterator for Links<'t> {
type Item = Link<'t>;
fn next(&mut self) -> Option> {
let slice = &self.text[self.rewind..];
let mut find_from = 0;
while let Some(i) = (self.trigger_finder)(slice[find_from..].as_bytes()) {
let trigger = slice.as_bytes()[find_from + i];
let (scanner, kind): (&dyn Scanner, LinkKind) = match trigger {
b':' => (&self.url_scanner, LinkKind::Url),
b'.' => (&self.domain_scanner, LinkKind::Url),
b'@' => (&self.email_scanner, LinkKind::Email),
_ => unreachable!(),
};
if let Some(range) = scanner.scan(slice, find_from + i) {
let start = self.rewind + range.start;
let end = self.rewind + range.end;
self.rewind = end;
let link = Link {
text: &self.text,
start,
end,
kind,
};
return Some(link);
} else {
// The scanner didn't find anything. But there could be more
// trigger characters later, so continue the search.
find_from += i + 1;
}
}
None
}
}
impl<'t> fmt::Debug for Links<'t> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Links").field("text", &self.text).finish()
}
}
impl<'t> Iterator for Spans<'t> {
type Item = Span<'t>;
fn next(&mut self) -> Option> {
match self.links.peek() {
Some(ref link) => {
if self.position < link.start {
let span = Span {
text: &self.text,
start: self.position,
end: link.start,
kind: None,
};
self.position = link.start;
return Some(span);
}
}
None => {
if self.position < self.text.len() {
let span = Span {
text: &self.text,
start: self.position,
end: self.text.len(),
kind: None,
};
self.position = self.text.len();
return Some(span);
}
}
};
self.links.next().map(|link| {
self.position = link.end;
Span {
text: &self.text,
start: link.start,
end: link.end,
kind: Some(link.kind),
}
})
}
}
impl<'t> fmt::Debug for Spans<'t> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Spans").field("text", &self.text).finish()
}
}
linkify-0.9.0/src/lib.rs 0000644 0000000 0000000 00000010247 00726746425 0013236 0 ustar 0000000 0000000 //! Linkify finds links such as URLs and email addresses in plain text.
//! It's smart about where a link ends, such as with trailing punctuation.
//!
//! Your reaction might be: "Do I need a library for this? Why not a regex?".
//! Let's look at a few cases:
//!
//! * In `http://example.com/.` the link should not include the trailing dot
//! * `http://example.com/,` should not include the trailing comma
//! * `(http://example.com/)` should not include the parens
//!
//! Seems simple enough. But then we also have these cases:
//!
//! * `https://en.wikipedia.org/wiki/Link_(The_Legend_of_Zelda)` should include the trailing paren
//! * `http://üñîçøðé.com/ä` should also work for Unicode (including Emoji and Punycode)
//! * `` should not include angle brackets
//!
//! This library behaves as you'd expect in the above cases and many more.
//! It uses a simple scan with linear runtime.
//!
//! In addition to URLs, it can also find emails.
//!
//! ### Usage
//!
//! Basic usage:
//!
//! ```
//! use linkify::{LinkFinder, LinkKind};
//!
//! let input = "Have you seen http://example.com?";
//! let finder = LinkFinder::new();
//! let links: Vec<_> = finder.links(input).collect();
//!
//! assert_eq!(1, links.len());
//! let link = &links[0];
//!
//! assert_eq!("http://example.com", link.as_str());
//! assert_eq!(14, link.start());
//! assert_eq!(32, link.end());
//! assert_eq!(&LinkKind::Url, link.kind());
//! ```
//!
//! Option to allow URLs without schemes:
//!
//! ```
//! use linkify::LinkFinder;
//!
//! let input = "Look, no scheme: example.org/foo";
//! let mut finder = LinkFinder::new();
//!
//! // true by default
//! finder.url_must_have_scheme(false);
//!
//! let links: Vec<_> = finder.links(input).collect();
//! assert_eq!(links[0].as_str(), "example.org/foo");
//! ```
//!
//! Restrict the kinds of links:
//!
//! ```
//! use linkify::{LinkFinder, LinkKind};
//!
//! let input = "http://example.com and foo@example.com";
//! let mut finder = LinkFinder::new();
//! finder.kinds(&[LinkKind::Email]);
//! let links: Vec<_> = finder.links(input).collect();
//!
//! assert_eq!(1, links.len());
//! let link = &links[0];
//! assert_eq!("foo@example.com", link.as_str());
//! assert_eq!(&LinkKind::Email, link.kind());
//! ```
//!
//! Split the text into consecutive spans (mixed links and plain text).
//!
//! ```
//! use linkify::{LinkFinder, LinkKind};
//!
//! let input = "Have you seen http://example.com?";
//! let finder = LinkFinder::new();
//! let spans: Vec<_> = finder.spans(input).collect();
//!
//! assert_eq!(3, spans.len());
//!
//! assert_eq!("Have you seen ", spans[0].as_str());
//! assert_eq!(0, spans[0].start());
//! assert_eq!(14, spans[0].end());
//! assert_eq!(None, spans[0].kind());
//!
//! assert_eq!("http://example.com", spans[1].as_str());
//! assert_eq!(14, spans[1].start());
//! assert_eq!(32, spans[1].end());
//! assert_eq!(Some(&LinkKind::Url), spans[1].kind());
//!
//! assert_eq!("?", spans[2].as_str());
//! assert_eq!(32, spans[2].start());
//! assert_eq!(33, spans[2].end());
//! assert_eq!(None, spans[2].kind());
//! ```
//!
//! ### Conformance
//!
//! This crates makes an effort to respect the various standards, namely:
//!
//! * [RFC 3986] and [RFC 3987] for URLs
//! * [RFC 5321] and [RFC 6531] for emails (except IP addresses and quoting)
//!
//! At the same time, it does not guarantee that the returned links are valid.
//! If in doubt, it rather returns a link than skipping it.
//!
//! If you need to validate URLs, e.g. for checking TLDs, use another library on
//! the returned links.
//!
//! [RFC 3986]: https://datatracker.ietf.org/doc/html/rfc3986
//! [RFC 3987]: https://datatracker.ietf.org/doc/html/rfc3987
//! [RFC 5321]: https://datatracker.ietf.org/doc/html/rfc5321
//! [RFC 6531]: https://datatracker.ietf.org/doc/html/rfc6531
#![doc(html_root_url = "https://docs.rs/linkify/0.9.0")]
#![deny(warnings)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
mod domains;
mod email;
mod finder;
mod scanner;
mod url;
pub use crate::finder::Link;
pub use crate::finder::LinkFinder;
pub use crate::finder::LinkKind;
pub use crate::finder::Links;
pub use crate::finder::{Span, Spans};
#[cfg(doctest)]
doc_comment::doctest!("../README.md");
linkify-0.9.0/src/scanner.rs 0000644 0000000 0000000 00000000167 00726746425 0014121 0 ustar 0000000 0000000 use std::ops::Range;
pub trait Scanner {
fn scan(&self, s: &str, trigger_index: usize) -> Option>;
}
linkify-0.9.0/src/url.rs 0000644 0000000 0000000 00000023101 00726746425 0013263 0 ustar 0000000 0000000 use std::char;
use std::ops::Range;
use crate::domains::find_authority_end;
use crate::scanner::Scanner;
/// Minimum valid URL length
///
/// The shortest valid URL (without a scheme) might be g.cn (Google China),
/// which consists of four characters.
/// We set this as a lower threshold for parsing URLs from plaintext
/// to avoid false-positives and as a slight performance optimization.
/// This threshold might be adjusted in the future.
const MIN_URL_LENGTH: usize = 4;
const QUOTES: &[char] = &['\'', '\"'];
/// Scan for URLs starting from the trigger character ":" (requires "://").
///
/// Based on RFC 3986.
pub struct UrlScanner;
/// Scan for plain domains (without scheme) such as `test.com` or `test.com/hi-there`.
pub struct DomainScanner;
impl Scanner for UrlScanner {
/// Scan for an URL at the given separator index in the string.
///
/// Returns `None` if none was found.
fn scan(&self, s: &str, separator: usize) -> Option> {
// There must be something before separator for scheme
if separator == 0 {
return None;
}
if !s[separator..].starts_with("://") {
// We only support schemes with authority, not things like `myscheme:mything`.
return None;
}
let after_separator = separator + "://".len();
// Need at least one character after '//'
if after_separator >= s.len() {
return None;
}
if let (Some(start), quote) = find_scheme_start(&s[0..separator]) {
let scheme = &s[start..separator];
let s = &s[after_separator..];
let require_host = scheme_requires_host(scheme);
if let (Some(after_authority), _) = find_authority_end(s, true, require_host, true) {
if let Some(end) = find_url_end(&s[after_authority..], quote) {
if after_authority == 0 && end == 0 {
return None;
}
let range = Range {
start,
end: after_separator + after_authority + end,
};
return Some(range);
}
}
}
None
}
}
impl Scanner for DomainScanner {
fn scan(&self, s: &str, separator: usize) -> Option> {
// There must be something before separator for domain, and a minimum number of characters
if separator == 0 || s.len() < MIN_URL_LENGTH {
return None;
}
if let (Some(start), quote) = find_domain_start(&s[0..separator]) {
let s = &s[start..];
if let (Some(domain_end), Some(_)) = find_authority_end(s, false, true, true) {
if let Some(end) = find_url_end(&s[domain_end..], quote) {
let range = Range {
start,
end: start + domain_end + end,
};
return Some(range);
}
}
}
None
}
}
/// Find start of scheme, e.g. from `https://`, start at `s` and end at `h`.
fn find_scheme_start(s: &str) -> (Option, Option) {
let mut first = None;
let mut special = None;
let mut quote = None;
for (i, c) in s.char_indices().rev() {
match c {
'a'..='z' | 'A'..='Z' => first = Some(i),
'0'..='9' => special = Some(i),
'+' | '-' | '.' => {}
'@' => return (None, None),
c if QUOTES.contains(&c) => {
// Check if there's a quote before the scheme,
// and stop once we encounter one of those quotes.
// https://github.com/robinst/linkify/issues/20
quote = Some(c);
break;
}
_ => break,
}
}
// We don't want to extract "abc://foo" out of "1abc://foo".
// ".abc://foo" and others are ok though, as they feel more like separators.
if let Some(first) = first {
if let Some(special) = special {
// Comparing the byte indices with `- 1` is ok as scheme must be ASCII
if first > 0 && first - 1 == special {
return (None, quote);
}
}
}
(first, quote)
}
/// Whether a scheme requires that authority looks like a host name (domain or IP address) or not
/// (can contain reg-name with arbitrary allowed characters).
///
/// We could make this configurable, but let's keep it simple until someone asks (hi!).
fn scheme_requires_host(scheme: &str) -> bool {
match scheme {
"https" | "http" | "file" | "ftp" | "ssh" => true,
_ => false,
}
}
/// Find the start of a plain domain URL (no scheme), e.g. from `blog.`, start at `g` and end at `b`.
/// The rules are:
/// - Domain is labels separated by `.`. Because we're starting at the first `.`, we only need to
/// handle one label.
/// - Label can not start or end with `-`
/// - Label can contain letters, digits, `-` or Unicode
fn find_domain_start(s: &str) -> (Option, Option) {
let mut first = None;
let mut quote = None;
for (i, c) in s.char_indices().rev() {
match c {
'a'..='z' | 'A'..='Z' | '0'..='9' | '\u{80}'..=char::MAX => first = Some(i),
// If we had something valid like `https://www.` we'd have found it with the ":"
// scanner already. We don't want to allow `.../www.example.com` just by itself.
// We *could* allow `//www.example.com` (scheme-relative URLs) in the future.
'/' => return (None, None),
// Similar to above, if this was an email we'd have found it already.
'@' => return (None, None),
// If this was a valid domain, we'd have extracted it already from the previous "."
'.' => return (None, None),
'-' => {
if first == None {
// Domain label can't end with `-`
return (None, None);
} else {
first = Some(i);
}
}
c if QUOTES.contains(&c) => {
// Check if there's a quote before, and stop once we encounter one of those quotes,
// e.g. with `"www.example.com"`
quote = Some(c);
break;
}
_ => break,
}
}
if let Some(first) = first {
if s[first..].starts_with('-') {
// Domain label can't start with `-`
return (None, None);
}
}
(first, quote)
}
/// Find the end of a URL. At this point we already scanned past a valid authority. So e.g. in
/// `https://example.com/foo` we're starting at `/` and want to end at `o`.
fn find_url_end(s: &str, quote: Option) -> Option {
let mut round = 0;
let mut square = 0;
let mut curly = 0;
let mut single_quote = false;
let mut previous_can_be_last = true;
let mut end = Some(0);
if !s[0..].starts_with("/") {
return Some(0);
}
for (i, c) in s.char_indices() {
let can_be_last = match c {
'\u{00}'..='\u{1F}' | ' ' | '|' | '\"' | '<' | '>' | '`' | '\u{7F}'..='\u{9F}' => {
// These can never be part of an URL, so stop now. See RFC 3986 and RFC 3987.
// Some characters are not in the above list, even they are not in "unreserved"
// or "reserved":
// '\\', '^', '{', '}'
// The reason for this is that other link detectors also allow them. Also see
// below, we require the braces to be balanced.
break;
}
'?' | '!' | '.' | ',' | ':' | ';' | '*' => {
// These may be part of an URL but not at the end. It's not that the spec
// doesn't allow them, but they are frequently used in plain text as delimiters
// where they're not meant to be part of the URL.
false
}
'/' => {
// This may be part of an URL and at the end, but not if the previous character
// can't be the end of an URL
previous_can_be_last
}
'(' => {
round += 1;
false
}
')' => {
round -= 1;
if round < 0 {
// More closing than opening brackets, stop now
break;
}
true
}
'[' => {
square += 1;
false
}
']' => {
square -= 1;
if square < 0 {
// More closing than opening brackets, stop now
break;
}
true
}
'{' => {
curly += 1;
false
}
'}' => {
curly -= 1;
if curly < 0 {
// More closing than opening brackets, stop now
break;
}
true
}
_ if Some(c) == quote => {
// Found matching quote from beginning of URL, stop now
break;
}
'\'' => {
single_quote = !single_quote;
// A single quote can only be the end of an URL if there's an even number
!single_quote
}
_ => true,
};
if can_be_last {
end = Some(i + c.len_utf8());
}
previous_can_be_last = can_be_last;
}
end
}
linkify-0.9.0/tests/common/mod.rs 0000644 0000000 0000000 00000001051 00726746425 0015103 0 ustar 0000000 0000000 use linkify::LinkFinder;
pub fn assert_linked_with(finder: &LinkFinder, input: &str, expected: &str) {
let actual = show_links(input, finder);
assert_eq!(actual, expected);
}
pub fn show_links(input: &str, finder: &LinkFinder) -> String {
let mut result = String::new();
for span in finder.spans(input) {
if span.kind().is_some() {
result.push('|');
result.push_str(span.as_str());
result.push('|');
} else {
result.push_str(span.as_str());
}
}
result
}
linkify-0.9.0/tests/domains.rs 0000644 0000000 0000000 00000011017 00726746425 0014471 0 ustar 0000000 0000000 mod common;
use crate::common::assert_linked_with;
use linkify::LinkFinder;
#[test]
fn domain_valid() {
assert_linked("9292.nl", "|9292.nl|");
assert_linked("a12.b-c.com", "|a12.b-c.com|");
}
#[test]
fn domain_invalid_tld() {
assert_not_linked("v1.2.3");
assert_not_linked("https://12-7.0.0.1/");
}
#[test]
fn domain_with_userinfo() {
assert_linked(
"https://user:pass@example.com/",
"|https://user:pass@example.com/|",
);
assert_linked(
"https://user:-.!$@example.com/",
"|https://user:-.!$@example.com/|",
);
assert_linked(
"https://user:!$&\'()*+,;=@example.com/",
"|https://user:!$&\'()*+,;=@example.com/|",
);
// Can't have another @
assert_not_linked("https://user:pass@ex@mple.com/");
}
#[test]
fn domain_with_port() {
assert_linked("https://localhost:8080!", "|https://localhost:8080|!");
assert_linked("https://localhost:8080/", "|https://localhost:8080/|");
}
#[test]
fn domain_with_userinfo_and_port() {
assert_linked(
"https://user:pass@example.com:8080/hi",
"|https://user:pass@example.com:8080/hi|",
);
}
#[test]
fn domain_ipv4() {
assert_linked("https://127.0.0.1/", "|https://127.0.0.1/|");
}
#[test]
fn domain_trailing_dot() {
// assert_linked("https://example.com./test", "|https://example.com./test|");
assert_linked(
"https://example.com.:8080/test",
"|https://example.com.:8080/test|",
);
}
#[test]
fn domain_delimited() {
// Delimiter at end of domain should *not* be included
assert_linked("https://example.org'", "|https://example.org|'");
// Unless it's a userinfo of course (sike!)
assert_linked(
"https://example.org'a@example.com",
"|https://example.org'a@example.com|",
);
}
#[test]
fn domain_delimited_multiple() {
assert_linked(
"https://a.com'https://b.com",
"https://a.com'|https://b.com|",
);
}
#[test]
fn domain_dots() {
assert_linked("https://example.com...", "|https://example.com|...")
}
#[test]
fn domain_labels_cant_be_empty() {
assert_not_linked("www.example..com");
assert_not_linked("https://.www.example.com");
}
#[test]
fn domain_labels_cant_start_with_hyphen() {
assert_not_linked("-a.com");
assert_not_linked("https://a.-b.com");
}
#[test]
fn domain_labels_cant_end_with_hyphen() {
assert_not_linked("a-.com");
assert_not_linked("a.b-.com");
assert_not_linked("https://a.b-.com");
// Could also argue that it should not be linked at all
assert_linked("https://example.com-/", "|https://example.com|-/");
assert_linked("https://example.org-", "|https://example.org|-");
}
#[test]
fn domain_cant_contain_at() {
// Looks like an email but was recognized as a schemeless link before.
assert_not_linked("example.com@about");
// As part of path it's ok.
assert_linked("example.com/@about", "|example.com/@about|");
assert_linked("https://example.com/@about", "|https://example.com/@about|");
}
#[test]
fn domain_cant_end_numeric() {
assert_not_linked("info@v1.1.1");
}
#[test]
fn no_authority_part() {
assert_linked("file:///", "|file:///|");
assert_linked("file:///home/foo", "|file:///home/foo|");
assert_linked("file://localhost/home/foo", "|file://localhost/home/foo|");
}
#[test]
fn authority_thats_not_domain() {
// Not valid according to DNS but we should allow it for other schemes (or all, not sure).
assert_linked("facetime://+19995551234", "|facetime://+19995551234|");
}
#[test]
fn authority_without_slash_should_stop_at_delimiters() {
// What's going on here? For schemes where we don't enforce domainyness,
// we want to stop at delimiter characters. Note that `!` is valid in authorities.
assert_linked("test://123'456!!!", "|test://123'456|!!!");
assert_linked("test://123'456...", "|test://123'456|...");
// ... unless there is a "/" terminating the authority.
assert_linked("test://123'456!!!/", "|test://123'456!!!/|");
assert_linked("test://123'456.../", "|test://123'456.../|");
}
#[test]
fn without_scheme_should_stop() {
// assert_linked("ab/example.com", "ab/|example.com|");
// This is not a valid scheme. Even the schemeless parser should not accept it, nor extract
// only example.com out of it.
assert_not_linked("1abc://example.com");
}
fn assert_linked(input: &str, expected: &str) {
let mut finder = LinkFinder::new();
finder.url_must_have_scheme(false);
assert_linked_with(&finder, input, expected);
}
fn assert_not_linked(s: &str) {
assert_linked(s, s);
}
linkify-0.9.0/tests/email.rs 0000644 0000000 0000000 00000006747 00726746425 0014144 0 ustar 0000000 0000000 mod common;
use crate::common::assert_linked_with;
use linkify::LinkFinder;
use linkify::LinkKind;
#[test]
fn no_links() {
assert_not_linked("");
assert_not_linked("foo");
assert_not_linked("@");
assert_not_linked("a@");
assert_not_linked("@a");
assert_not_linked("@@@");
}
#[test]
fn simple() {
assert_linked("foo@example.com", "|foo@example.com|");
assert_linked("foo.bar@example.com", "|foo.bar@example.com|");
}
#[test]
fn allowed_text() {
// I know, I know...
assert_linked(
"#!$%&'*+-/=?^_`{}|~@example.org",
"|#!$%&'*+-/=?^_`{}|~@example.org|",
);
}
#[test]
fn space_separation() {
assert_linked("foo a@b.com", "foo |a@b.com|");
assert_linked("a@b.com foo", "|a@b.com| foo");
assert_linked("\na@b.com", "\n|a@b.com|");
assert_linked("a@b.com\n", "|a@b.com|\n");
}
#[test]
fn special_separation() {
assert_linked("(a@example.com)", "(|a@example.com|)");
assert_linked("\"a@example.com\"", "\"|a@example.com|\"");
assert_linked("\"a@example.com\"", "\"|a@example.com|\"");
assert_linked(",a@example.com,", ",|a@example.com|,");
assert_linked(":a@example.com:", ":|a@example.com|:");
assert_linked(";a@example.com;", ";|a@example.com|;");
}
#[test]
fn dots() {
assert_not_linked(".@example.com");
assert_not_linked("foo.@example.com");
assert_linked(".foo@example.com", ".|foo@example.com|");
assert_linked(".foo@example.com", ".|foo@example.com|");
assert_linked("a..b@example.com", "a..|b@example.com|");
assert_linked("a@example.com.", "|a@example.com|.");
}
#[test]
fn domain_without_dot() {
assert_not_linked("a@b");
assert_not_linked("a@b.");
assert_linked("a@b.com.", "|a@b.com|.");
}
#[test]
fn dashes() {
assert_linked("a@example.com-", "|a@example.com|-");
assert_linked("a@foo-bar.com", "|a@foo-bar.com|");
assert_not_linked("a@-foo.com");
assert_not_linked("a@b-.");
}
#[test]
fn domain_must_have_dot_false() {
let mut finder = LinkFinder::new();
finder.kinds(&[LinkKind::Email]);
finder.email_domain_must_have_dot(false);
assert_linked_with(&finder, "a@b", "|a@b|");
assert_linked_with(&finder, "a@b.", "|a@b|.");
assert_linked_with(&finder, "a@b.", "|a@b|.");
}
#[test]
fn multiple() {
assert_linked(
"a@example.com b@example.com",
"|a@example.com| |b@example.com|",
);
assert_linked(
"a@example.com @ b@example.com",
"|a@example.com| @ |b@example.com|",
);
}
#[test]
fn multiple_delimited_hard() {
assert_linked(
"a@xy.com;b@xy.com,c@xy.com",
"|a@xy.com|;|b@xy.com|,|c@xy.com|",
);
}
#[test]
fn international() {
assert_linked("üñîçøðé@example.com", "|üñîçøðé@example.com|");
assert_linked("üñîçøðé@üñîçøðé.com", "|üñîçøðé@üñîçøðé.com|");
}
#[test]
fn trigger_overlap() {
let finder = LinkFinder::new();
// 'w' is a trigger character for WWW links. Make sure we can rewind enough.
assert_linked_with(&finder, "www@example.com", "|www@example.com|");
}
#[test]
fn fuzz() {
assert_linked("a@a.xyϸ", "|a@a.xyϸ|");
}
fn assert_not_linked(s: &str) {
let mut finder = LinkFinder::new();
finder.kinds(&[LinkKind::Email]);
let result = finder.links(s);
assert_eq!(result.count(), 0, "expected no links in {:?}", s);
}
fn assert_linked(input: &str, expected: &str) {
let mut finder = LinkFinder::new();
finder.kinds(&[LinkKind::Email]);
assert_linked_with(&finder, input, expected);
}
linkify-0.9.0/tests/types.rs 0000644 0000000 0000000 00000001075 00726746425 0014206 0 ustar 0000000 0000000 use linkify::Link;
use linkify::LinkFinder;
use linkify::LinkKind;
#[test]
fn send_and_sync() {
check_send::();
check_sync::();
check_send::>();
check_sync::>();
}
#[test]
fn equality() {
let finder = LinkFinder::new();
let first = finder.links("http://example.org").next();
assert!(first.is_some());
let link = first.unwrap();
// Check that link has Debug
println!("{:?}", link);
assert_eq!(link.kind(), &LinkKind::Url);
}
fn check_send() {}
fn check_sync() {}
linkify-0.9.0/tests/url.rs 0000644 0000000 0000000 00000044314 00726746425 0013647 0 ustar 0000000 0000000 mod common;
use crate::common::assert_linked_with;
use linkify::{LinkFinder, LinkKind};
#[test]
fn no_links() {
assert_not_linked("");
assert_not_linked("foo");
assert_not_linked(":");
assert_not_linked("://");
assert_not_linked(":::");
}
#[test]
fn schemes() {
assert_not_linked("://foo");
assert_not_linked("1://foo");
assert_not_linked("123://foo");
assert_not_linked("+://foo");
assert_not_linked("-://foo");
assert_not_linked(".://foo");
assert_not_linked("1abc://foo");
assert_linked("a://foo", "|a://foo|");
assert_linked("a123://foo", "|a123://foo|");
assert_linked("a123b://foo", "|a123b://foo|");
assert_linked("a+b://foo", "|a+b://foo|");
assert_linked("a-b://foo", "|a-b://foo|");
assert_linked("a.b://foo", "|a.b://foo|");
assert_linked("ABC://foo", "|ABC://foo|");
assert_linked(".http://example.org/", ".|http://example.org/|");
assert_linked("1.http://example.org/", "1.|http://example.org/|");
}
#[test]
fn authority() {
assert_not_linked("ab://");
assert_not_linked("file://");
assert_not_linked("file:// ");
assert_not_linked("\"file://\"");
assert_not_linked("\"file://...\", ");
assert_linked("http://a.", "|http://a|.");
}
#[test]
fn local_links() {
assert_linked("http://127.0.0.1", "|http://127.0.0.1|");
assert_linked("http://127.0.0.1/", "|http://127.0.0.1/|");
}
#[test]
fn single_links() {
assert_linked("ab://c", "|ab://c|");
assert_linked("http://example.org/", "|http://example.org/|");
assert_linked("http://example.org/123", "|http://example.org/123|");
assert_linked(
"http://example.org/?foo=test&bar=123",
"|http://example.org/?foo=test&bar=123|",
);
assert_linked(
"http://example.org/?foo=%20",
"|http://example.org/?foo=%20|",
);
assert_linked("http://example.org/%3C", "|http://example.org/%3C|");
}
#[test]
fn single_links_without_protocol() {
assert_urls_without_protocol("example.org/", "|example.org/|");
assert_urls_without_protocol("example.org/123", "|example.org/123|");
assert_urls_without_protocol(
"example.org/?foo=test&bar=123",
"|example.org/?foo=test&bar=123|",
);
assert_urls_without_protocol("example.org/?foo=%20", "|example.org/?foo=%20|");
assert_urls_without_protocol("example.org/%3C", "|example.org/%3C|");
}
#[test]
fn space_characters_stop_url() {
assert_linked("foo http://example.org/", "foo |http://example.org/|");
assert_linked("http://example.org/ bar", "|http://example.org/| bar");
assert_linked("http://example.org/\tbar", "|http://example.org/|\tbar");
assert_linked("http://example.org/\nbar", "|http://example.org/|\nbar");
assert_linked(
"http://example.org/\u{0B}bar",
"|http://example.org/|\u{0B}bar",
);
assert_linked(
"http://example.org/\u{0C}bar",
"|http://example.org/|\u{0C}bar",
);
assert_linked("http://example.org/\rbar", "|http://example.org/|\rbar");
}
#[test]
fn space_characters_stop_url_without_protocol() {
assert_urls_without_protocol("foo example.org/", "foo |example.org/|");
assert_urls_without_protocol("example.org/ bar", "|example.org/| bar");
assert_urls_without_protocol("example.org/\tbar", "|example.org/|\tbar");
assert_urls_without_protocol("example.org/\nbar", "|example.org/|\nbar");
assert_urls_without_protocol("example.org/\u{0B}bar", "|example.org/|\u{0B}bar");
assert_urls_without_protocol("example.org/\u{0C}bar", "|example.org/|\u{0C}bar");
assert_urls_without_protocol("example.org/\rbar", "|example.org/|\rbar");
}
#[test]
fn illegal_characters_stop_url() {
assert_linked("http://example.org/<", "|http://example.org/|<");
assert_linked("http://example.org/>", "|http://example.org/|>");
assert_linked("http://example.org/<>", "|http://example.org/|<>");
assert_linked("http://example.org/\u{00}", "|http://example.org/|\u{00}");
assert_linked("http://example.org/\u{0E}", "|http://example.org/|\u{0E}");
assert_linked("http://example.org/\u{7F}", "|http://example.org/|\u{7F}");
assert_linked("http://example.org/\u{9F}", "|http://example.org/|\u{9F}");
assert_linked("http://example.org/foo|bar", "|http://example.org/foo||bar");
}
#[test]
fn illegal_characters_stop_url_without_protocol() {
assert_urls_without_protocol("example.org/<", "|example.org/|<");
assert_urls_without_protocol("example.org/>", "|example.org/|>");
assert_urls_without_protocol("example.org/<>", "|example.org/|<>");
assert_urls_without_protocol("example.org/\u{00}", "|example.org/|\u{00}");
assert_urls_without_protocol("example.org/\u{0E}", "|example.org/|\u{0E}");
assert_urls_without_protocol("example.org/\u{7F}", "|example.org/|\u{7F}");
assert_urls_without_protocol("example.org/\u{9F}", "|example.org/|\u{9F}");
}
#[test]
fn delimiter_at_end() {
assert_linked("http://example.org/.", "|http://example.org/|.");
assert_linked("http://example.org/..", "|http://example.org/|..");
assert_linked("http://example.org/,", "|http://example.org/|,");
assert_linked("http://example.org/:", "|http://example.org/|:");
assert_linked("http://example.org/?", "|http://example.org/|?");
assert_linked("http://example.org/!", "|http://example.org/|!");
assert_linked("http://example.org/;", "|http://example.org/|;");
}
#[test]
fn delimiter_at_end_no_protocol() {
assert_urls_without_protocol("example.org/.", "|example.org/|.");
assert_urls_without_protocol("example.org/..", "|example.org/|..");
assert_urls_without_protocol("example.org/,", "|example.org/|,");
assert_urls_without_protocol("example.org/:", "|example.org/|:");
assert_urls_without_protocol("example.org/?", "|example.org/|?");
assert_urls_without_protocol("example.org/!", "|example.org/|!");
assert_urls_without_protocol("example.org/;", "|example.org/|;");
}
#[test]
fn matching_punctuation() {
assert_linked("http://example.org/a(b)", "|http://example.org/a(b)|");
assert_linked("http://example.org/a[b]", "|http://example.org/a[b]|");
assert_linked("http://example.org/a{b}", "|http://example.org/a{b}|");
assert_linked("http://example.org/a'b'", "|http://example.org/a'b'|");
assert_linked("(http://example.org/)", "(|http://example.org/|)");
assert_linked("[http://example.org/]", "[|http://example.org/|]");
assert_linked("{http://example.org/}", "{|http://example.org/|}");
assert_linked("\"http://example.org/\"", "\"|http://example.org/|\"");
assert_linked("'http://example.org/'", "'|http://example.org/|'");
}
#[test]
fn matching_punctuation_without_protocol() {
assert_urls_without_protocol("example.org/a(b)", "|example.org/a(b)|");
assert_urls_without_protocol("example.org/a[b]", "|example.org/a[b]|");
assert_urls_without_protocol("example.org/a{b}", "|example.org/a{b}|");
assert_urls_without_protocol("example.org/a'b'", "|example.org/a'b'|");
assert_urls_without_protocol("(example.org/)", "(|example.org/|)");
assert_urls_without_protocol("[example.org/]", "[|example.org/|]");
assert_urls_without_protocol("{example.org/}", "{|example.org/|}");
assert_urls_without_protocol("\"example.org/\"", "\"|example.org/|\"");
assert_urls_without_protocol("'example.org/'", "'|example.org/|'");
}
#[test]
fn matching_punctuation_tricky() {
assert_linked("((http://example.org/))", "((|http://example.org/|))");
assert_linked(
"((http://example.org/a(b)))",
"((|http://example.org/a(b)|))",
);
assert_linked("[(http://example.org/)]", "[(|http://example.org/|)]");
assert_linked("(http://example.org/).", "(|http://example.org/|).");
assert_linked("(http://example.org/.)", "(|http://example.org/|.)");
assert_linked("http://example.org/>", "|http://example.org/|>");
// not sure about these
assert_linked("http://example.org/(", "|http://example.org/|(");
assert_linked("http://example.org/(.", "|http://example.org/|(.");
assert_linked("http://example.org/]()", "|http://example.org/|]()");
}
#[test]
fn matching_punctuation_tricky_without_protocol() {
assert_urls_without_protocol("((example.org/))", "((|example.org/|))");
assert_urls_without_protocol("((example.org/a(b)))", "((|example.org/a(b)|))");
assert_urls_without_protocol("[(example.org/)]", "[(|example.org/|)]");
assert_urls_without_protocol("(example.org/).", "(|example.org/|).");
assert_urls_without_protocol("(example.org/.)", "(|example.org/|.)");
assert_urls_without_protocol("example.org/>", "|example.org/|>");
// not sure about these
assert_urls_without_protocol("example.org/(", "|example.org/|(");
assert_urls_without_protocol("example.org/(.", "|example.org/|(.");
assert_urls_without_protocol("example.org/]()", "|example.org/|]()");
}
#[test]
fn single_quote() {
assert_linked("'https://example.org'", "'|https://example.org|'");
assert_linked("\"https://example.org\"", "\"|https://example.org|\"");
assert_linked("''https://example.org''", "''|https://example.org|''");
assert_linked("'https://example.org''", "'|https://example.org|''");
assert_linked("'https://example.org", "'|https://example.org|");
assert_linked(
"http://example.org/\'_(foo)",
"|http://example.org/\'_(foo)|",
);
assert_linked(
"http://example.org/\'_(foo)\'",
"|http://example.org/\'_(foo)\'|",
);
assert_linked("http://example.org/\'\'", "|http://example.org/\'\'|");
assert_linked("http://example.org/\'\'\'", "|http://example.org/\'\'|\'");
assert_linked("http://example.org/\'.", "|http://example.org/|\'.");
assert_linked("http://example.org/\'a", "|http://example.org/\'a|");
assert_linked("http://example.org/it's", "|http://example.org/it's|");
}
#[test]
fn single_quote_without_protocol() {
assert_urls_without_protocol("example.org/\'_(foo)", "|example.org/\'_(foo)|");
assert_urls_without_protocol("example.org/\'_(foo)\'", "|example.org/\'_(foo)\'|");
assert_urls_without_protocol("example.org/\'\'", "|example.org/\'\'|");
assert_urls_without_protocol("example.org/\'\'\'", "|example.org/\'\'|\'");
assert_urls_without_protocol("example.org/\'.", "|example.org/|\'.");
assert_urls_without_protocol("example.org/\'a", "|example.org/\'a|");
assert_urls_without_protocol("example.org/it's", "|example.org/it's|");
}
#[test]
fn double_quote() {
// " not allowed in URLs
assert_linked("http://example.org/\"a", "|http://example.org/|\"a");
assert_linked("http://example.org/\"a\"", "|http://example.org/|\"a\"");
}
#[test]
fn grave_quote() {
// ` not allowed in URLs
assert_linked("http://example.org/`a", "|http://example.org/|`a");
assert_linked("http://example.org/`a`", "|http://example.org/|`a`");
}
#[test]
fn asterisk() {
assert_linked("https://example.org*", "|https://example.org|*");
assert_linked("https://example.org/*", "|https://example.org/|*");
assert_linked("https://example.org/**", "|https://example.org/|**");
assert_linked("https://example.org/*/a", "|https://example.org/*/a|");
}
#[test]
fn grave_quote_without_protocol() {
// ` not allowed in URLs
assert_urls_without_protocol("example.org/`a", "|example.org/|`a");
assert_urls_without_protocol("example.org/`a`", "|example.org/|`a`");
}
#[test]
fn html() {
assert_linked("http://example.org\">", "|http://example.org|\">");
assert_linked("http://example.org'>", "|http://example.org|'>");
assert_linked("http://example.org\"/>", "|http://example.org|\"/>");
assert_linked("http://example.org'/>", "|http://example.org|'/>");
assert_linked("http://example.org