linkify-0.4.0/.gitignore010066400017500001750000000001261323457761700134110ustar0000000000000000# cargo target Cargo.lock # MacOS .DS_Store # IDEA .idea/ *.iml # VS Code .vscode/ linkify-0.4.0/CHANGELOG.md010066400017500001750000000035731352200367600132300ustar0000000000000000# 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.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 (minimal 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.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.4.0/Cargo.toml.orig010064400017500001750000000012231352200544300142640ustar0000000000000000[package] name = "linkify" version = "0.4.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 = ["/.travis.yml"] [dependencies] memchr = "2.0.1" [dev-dependencies] version-sync = "0.8" linkify-0.4.0/Cargo.toml0000644000000022130000000000000105350ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "linkify" version = "0.4.0" authors = ["Robin Stocker "] exclude = ["/.travis.yml"] 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" [dependencies.memchr] version = "2.0.1" [dev-dependencies.version-sync] version = "0.8" linkify-0.4.0/LICENSE-APACHE010066400017500001750000000251371307171277700133530ustar0000000000000000 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.4.0/LICENSE-MIT010066400017500001750000000020561307171273400130470ustar0000000000000000MIT 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.4.0/README.md010064400017500001750000000063341352147017200126700ustar0000000000000000Linkify ======= 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. [![Documentation](https://docs.rs/linkify/badge.svg)](https://docs.rs/linkify) [![Crate](https://img.shields.io/crates/v/linkify.svg)](https://crates.io/crates/linkify) [![Build Status](https://travis-ci.org/robinst/linkify.svg?branch=master)](https://travis-ci.org/robinst/linkify) [![codecov](https://codecov.io/gh/robinst/linkify/branch/master/graph/badge.svg)](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. ## 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()); ``` 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://tools.ietf.org/search/rfc3986 [RFC 3987]: https://tools.ietf.org/search/rfc3987 [RFC 5321]: https://tools.ietf.org/search/rfc5321 [RFC 6531]: https://tools.ietf.org/search/rfc6531 linkify-0.4.0/benches/url.rs010066400017500001750000000026541352177114500141770ustar0000000000000000#![feature(test)] extern crate test; use linkify::LinkFinder; use test::Bencher; #[bench] fn no_links(b: &mut Bencher) { 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); }); } #[bench] fn some_links(b: &mut Bencher) { 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); }); } #[bench] fn heaps_of_links(b: &mut Bencher) { 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); }); } linkify-0.4.0/src/email.rs010064400017500001750000000071411352177067700136470ustar0000000000000000use std::ops::Range; 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 { break; } } first } // See "Domain" in RFC 5321, plus extension of "sub-domain" in RFC 6531 fn find_end(&self, s: &str) -> Option { let mut first_in_sub_domain = true; let mut can_end_sub_domain = false; let mut first_dot = None; let mut end = None; for (i, c) in s.char_indices() { if first_in_sub_domain { if Self::sub_domain_allowed(c) { end = Some(i + c.len_utf8()); first_in_sub_domain = false; can_end_sub_domain = true; } else { break; } } else if c == '.' { if !can_end_sub_domain { break; } first_in_sub_domain = true; if first_dot.is_none() { first_dot = Some(i); } } else if c == '-' { can_end_sub_domain = false; } else if Self::sub_domain_allowed(c) { end = Some(i + c.len_utf8()); can_end_sub_domain = true; } else { break; } } if let Some(end) = end { if !self.domain_must_have_dot || first_dot.map(|d| d < end).unwrap_or(false) { 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}', } } // See "sub-domain" in RFC 5321. Extension in RFC 6531 is simplified, // this can also match invalid domains. fn sub_domain_allowed(c: char) -> bool { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => true, _ => c >= '\u{80}', } } } linkify-0.4.0/src/finder.rs010064400017500001750000000200541352177107200140130ustar0000000000000000use std::fmt; use std::iter::Peekable; use memchr::memchr; use memchr::memchr2; use crate::email::EmailScanner; use crate::scanner::Scanner; use crate::url::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, } /// Iterator for finding links. pub struct Links<'t> { text: &'t str, rewind: usize, trigger_finder: Box Option>, email_scanner: EmailScanner, url_scanner: UrlScanner, } /// 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, } } /// 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 } /// 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.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, email: bool, email_domain_must_have_dot: bool) -> Links<'t> { let url_scanner = UrlScanner {}; let email_scanner = EmailScanner { domain_must_have_dot: email_domain_must_have_dot, }; let trigger_finder: Box Option> = match (url, email) { (true, true) => Box::new(|s| memchr2(b':', b'@', s)), (true, false) => Box::new(|s| memchr(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, } } } 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.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.4.0/src/lib.rs010064400017500001750000000073171352200425100133060ustar0000000000000000//! 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()); //! ``` //! //! 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://tools.ietf.org/search/rfc3986 //! [RFC 3987]: https://tools.ietf.org/search/rfc3987 //! [RFC 5321]: https://tools.ietf.org/search/rfc5321 //! [RFC 6531]: https://tools.ietf.org/search/rfc6531 #![doc(html_root_url = "https://docs.rs/linkify/0.4.0")] #![deny(warnings)] #![deny(missing_docs)] #![deny(missing_debug_implementations)] 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}; linkify-0.4.0/src/scanner.rs010066400017500001750000000001671305665557600142170ustar0000000000000000use std::ops::Range; pub trait Scanner { fn scan(&self, s: &str, trigger_index: usize) -> Option>; } linkify-0.4.0/src/url.rs010064400017500001750000000112571352177067700133650ustar0000000000000000use std::ops::Range; use crate::scanner::Scanner; /// Scan for URLs starting from the trigger character ":", requires "://". /// /// Based on RFC 3986. pub struct UrlScanner {} impl Scanner for UrlScanner { fn scan(&self, s: &str, colon: usize) -> Option> { let after_slash_slash = colon + 3; // Need at least one character for scheme, and one after '//' if colon > 0 && after_slash_slash < s.len() && s[colon..].starts_with("://") { if let Some(start) = self.find_start(&s[0..colon]) { if let Some(end) = self.find_end(&s[after_slash_slash..]) { let range = Range { start, end: after_slash_slash + end, }; return Some(range); } } } None } } impl UrlScanner { // See "scheme" in RFC 3986 fn find_start(&self, s: &str) -> Option { let mut first = None; let mut digit = None; for (i, c) in s.char_indices().rev() { match c { 'a'..='z' | 'A'..='Z' => first = Some(i), '0'..='9' => digit = Some(i), // scheme special '+' | '-' | '.' => {} _ => { 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(digit) = digit { // Comparing the byte indices with `- 1` is ok as scheme must be ASCII if first > 0 && first - 1 == digit { return None; } } } first } fn find_end(&self, s: &str) -> 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 = None; 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 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 } '[' => { // Allowed in IPv6 address host square += 1; false } ']' => { // Allowed in IPv6 address host 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 } '\'' => { 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.4.0/tests/common/mod.rs010066400017500001750000000010511323457761700151760ustar0000000000000000use 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.4.0/tests/email.rs010064400017500001750000000065461352177114500142210ustar0000000000000000mod 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 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.ϸ", "|a@a.ϸ|"); } 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.4.0/tests/types.rs010064400017500001750000000010751352177114500142660ustar0000000000000000use 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.4.0/tests/url.rs010064400017500001750000000175771352177114500137420ustar0000000000000000mod common; use crate::common::assert_linked_with; use linkify::LinkFinder; #[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("http://"); assert_not_linked("http:// "); assert_not_linked("\"http://\""); assert_not_linked("\"http://...\", "); assert_linked("http://a.", "|http://a|."); } #[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 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 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}"); } #[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 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_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 single_quote() { 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 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 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

", "|http://example.org|

"); assert_linked("http://example.org

", "|http://example.org|

"); } #[test] fn css() { assert_linked("http://example.org\");", "|http://example.org|\");"); assert_linked("http://example.org');", "|http://example.org|');"); } #[test] fn slash() { assert_linked("http://example.org/", "|http://example.org/|"); assert_linked("http://example.org/a/", "|http://example.org/a/|"); assert_linked("http://example.org//", "|http://example.org//|"); } #[test] fn multiple() { assert_linked( "http://one.org/ http://two.org/", "|http://one.org/| |http://two.org/|", ); assert_linked( "http://one.org/ : http://two.org/", "|http://one.org/| : |http://two.org/|", ); assert_linked( "(http://one.org/)(http://two.org/)", "(|http://one.org/|)(|http://two.org/|)", ); } #[test] fn international() { assert_linked( "http://üñîçøðé.com/ä", "|http://üñîçøðé.com/ä|", ); assert_linked("http://example.org/\u{A1}", "|http://example.org/\u{A1}|"); assert_linked("http://example.org/\u{A2}", "|http://example.org/\u{A2}|"); assert_linked( "http://example.org/\u{1F600}", "|http://example.org/\u{1F600}|", ); assert_linked("http://example.org/\u{A2}/", "|http://example.org/\u{A2}/|"); assert_linked( "http://xn--c1h.example.com/", "|http://xn--c1h.example.com/|", ); } #[test] fn fuzz() { assert_not_linked("ab:/ϸ"); } fn assert_not_linked(s: &str) { assert_linked(s, s); } fn assert_linked(input: &str, expected: &str) { let finder = LinkFinder::new(); assert_linked_with(&finder, input, expected); } linkify-0.4.0/tests/version-numbers.rs010066400017500001750000000001431352200377100162470ustar0000000000000000#[test] fn test_html_root_url() { version_sync::assert_html_root_url_updated!("src/lib.rs"); } linkify-0.4.0/.cargo_vcs_info.json0000644000000001120000000000000125330ustar00{ "git": { "sha1": "a08b343bb524f267130d67ad3e1a752c34dd49ac" } }