mdurl

web demo github docs.rs crates.io coverage

URL parser and formatter that gracefully handles invalid input.

It is a rust port of mdurl.js library, created specifically for url rendering in markdown-it parser.

URL formatter

This function takes URL, decodes it, and fits it into N characters, replacing the rest with "…" symbol (that's called "url elision").

This is similar to what Chromium would show you in status bar when you hover your mouse over a link.

```rust use mdurl::formaturlforhumans as format; let url = "https://www.reddit.com/r/programming/comments/vxttiq/\ comment/ifyqsqt/?utmsource=reddit&utm_medium=web2x&context=3";

asserteq!(format(url, 20), "reddit.com/…/ifyqsq…"); asserteq!(format(url, 30), "www.reddit.com/r/…/ifyqsqt/?u…"); assert_eq!(format(url, 50), "www.reddit.com/r/programming/comments/…/ifyqsqt/?…"); ```

Check out this demo to play around with different URLs and lengths.

humanize-url crate tries to achieve similar goals, let me know if there are others.

URL parser

In order to achieve the task above, a new url parser had to be created, so here it is:

```rust let url = "https://www.reddit.com/r/programming/comments/vxttiq/\ comment/ifyqsqt/?utmsource=reddit&utmmedium=web2x&context=3"; let u = mdurl::parse_url(url);

asserteq!(u.hostname, Some("www.reddit.com".into())); asserteq!(u.pathname, Some("/r/programming/comments/vxttiq/comment/ifyqsqt/".into())); asserteq!(u.search, Some("?utmsource=reddit&utm_medium=web2x&context=3".into())); ```

This function uses a non-standard parsing algorithm derived from node.js legacy URL parser.

You should probably be using rust-url crate instead. Unfortunately, it isn't suitable for the task of pretty-printing urls because you can't customize parts of Url returned by that library (for example, rust-url will always encode non-ascii hostname with punycode, this implementation will not).