diff options
Diffstat (limited to '')
26 files changed, 8089 insertions, 0 deletions
diff --git a/vendor/minifier/.cargo-checksum.json b/vendor/minifier/.cargo-checksum.json new file mode 100644 index 000000000..4760bcb0d --- /dev/null +++ b/vendor/minifier/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"adb64b1e8820e83bebfc867d6e5846154743bc324754d50a2bb13742f682f1b9","Cargo.toml":"d5c1e43fffcf2a4a384ea0adfacac7c08b41bd3b05937e7e2ad1aeb0ea2aad62","LICENSE":"d64fe3199be0c90d1f88b363e6b567d5812f64c01accc8957e71381598a3d670","README.md":"7ce7cc43ebca972096db97b9f8bd211e5ac0c688f01b1732d5e2243e8c32d02d","src/css/mod.rs":"afbab7f8a657871fb567b25c5c87cb3e1c9e88d486335e154873b8c818370506","src/css/tests.rs":"056d1d3d927be4c7cece4033b48b28fe3a142939ac2f71cb10ca93f2a28a4477","src/css/token.rs":"b9fff49884a74423e11a913f49dd923b2f8c28e5a29894b08c9d1b2fbc06b85f","src/html.rs":"7b78e2c7d1b0d85065de7e6ab7e0407a74590e23ad1d20fe106c2361f5b09447","src/js/mod.rs":"b63e9cac9cc2cf7063f1eb598892fde3aa55081d0bf926df85c008e35d8e5a30","src/js/token.rs":"81918762068fba64a53dc0328222e74e8c922e657be46bb431ae4a3ac0e9fce9","src/js/tools.rs":"50e9581d6cfa2aebf2928f3df63bbb8a72149c7a40a687f248c108cf154a74ab","src/js/utils.rs":"54d97e766cb38ca1ac7c661a376f8e01c735486f2b78ae149794bb735e8f787b","src/json/json_minifier.rs":"83b5868bff0692aa655973596ad6ff34d215001be47c5c9adad8049faeec87bb","src/json/mod.rs":"e4ff2108ba01d5e937e22108c467c1c191ffc55fffedebd9c86d2a9789abb5e4","src/json/read/byte_to_char.rs":"633cdff14eb99fe7e2ba72594444b2c681a7ec13f557fecfc791b11ce8b9f130","src/json/read/internal_buffer.rs":"459e17fcc86039dd5000dbf9e8c834bfaa02cba2a2afbd19c067c9d621ba7d0b","src/json/read/internal_reader.rs":"37d9f8a31fd6477bbed676ce923a85568e9a96ef5d46db02e92e65ba13c65dea","src/json/read/json_read.rs":"dbc2c729c0c07109860e5a7c69f4fea2c4721fc17f764622392c54bd2afb1b55","src/json/string.rs":"9b9b3a40bfdb6fcbe2f3215a0506b8edfab577dd79e4a404c492fbc486896567","src/lib.rs":"ec53713f3903f80439c83a835d46b562c3cae119f2354d7a5558c0603c86c1a7","src/main.rs":"10c62d1d5544896506962d569d1507d3396bf894f501c26586a561b904956c47","tests/files/main.js":"18f43c7672eb75f532bc7f99dd2b6d644b3a11e19662774e93405928fde4d4d4","tests/files/minified_main.js":"0952e8cff3fae6c91b13a15f2923d922ccd9bce339419cc4bd52b5314180dabb","tests/files/test.json":"e07a148ef24385057cb7420209a630758c6ce80970bd54c8ffee5be207205608","tests/js_minify.rs":"66de1b596668a5f8d11e0b65d42ace3da6bc0b2b997b2d9e2fc09a488624c5af"},"package":"ac96d1e7a65f206443f95afff6de8f1690c77c97d6fc9c9bb2d2cd0662e9ff9f"}
\ No newline at end of file diff --git a/vendor/minifier/Cargo.lock b/vendor/minifier/Cargo.lock new file mode 100644 index 000000000..9f5453ee1 --- /dev/null +++ b/vendor/minifier/Cargo.lock @@ -0,0 +1,42 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "memchr" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" + +[[package]] +name = "minifier" +version = "0.2.1" +dependencies = [ + "regex", +] + +[[package]] +name = "regex" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" diff --git a/vendor/minifier/Cargo.toml b/vendor/minifier/Cargo.toml new file mode 100644 index 000000000..be981e4d0 --- /dev/null +++ b/vendor/minifier/Cargo.toml @@ -0,0 +1,60 @@ +# 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 = "2021" +name = "minifier" +version = "0.2.1" +authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] +description = "Minifier tool/lib for JS/CSS/JSON files" +documentation = "https://docs.rs/minifier-rs" +readme = "README.md" +keywords = [ + "minify", + "minifier", + "JS", + "HTML", + "CSS", +] +license = "MIT" +repository = "https://github.com/GuillaumeGomez/minifier-rs" +resolver = "2" + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +strip = true + +[profile.release.package."*"] +opt-level = 3 +codegen-units = 1 + +[lib] +name = "minifier" + +[[bin]] +name = "minifier" +doc = false + +[dependencies.regex] +version = "1.5.5" +optional = true + +[features] +html = ["regex"] + +[badges.appveyor] +repository = "GuillaumeGomez/minifier-rs" +service = "github" + +[badges.travis-ci] +repository = "GuillaumeGomez/minifier-rs" diff --git a/vendor/minifier/LICENSE b/vendor/minifier/LICENSE new file mode 100644 index 000000000..8bd1bcc08 --- /dev/null +++ b/vendor/minifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Guillaume Gomez + +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. diff --git a/vendor/minifier/README.md b/vendor/minifier/README.md new file mode 100644 index 000000000..e9aa5bba6 --- /dev/null +++ b/vendor/minifier/README.md @@ -0,0 +1,30 @@ +# minifier-rs + +Minifier tool/lib for JS/CSS/JSON files. + +This crate provides both a library and binary, depending on your needs. + +## Usage + +To use the binary, just run like this: + +``` +> cargo run test.js +``` + +To use the library, add it into your `Cargo.toml` file like this: + +```toml +[dependencies] +minifier = "^0.0.1" +``` + +Then import it into your code like this: + +```rust +extern crate minifier; +``` + +## WARNING!! + +Please be aware that this is still at a very early stage of development so you shouldn't rely on it too much! diff --git a/vendor/minifier/src/css/mod.rs b/vendor/minifier/src/css/mod.rs new file mode 100644 index 000000000..224ad8126 --- /dev/null +++ b/vendor/minifier/src/css/mod.rs @@ -0,0 +1,40 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::{fmt, io}; + +mod token; + +/// Minifies a given CSS source code. +/// +/// # Example +/// +/// ```rust +/// use minifier::css::minify; +/// +/// let css = r#" +/// .foo > p { +/// color: red; +/// }"#.into(); +/// let css_minified = minify(css).expect("minification failed"); +/// assert_eq!(&css_minified.to_string(), ".foo>p{color:red;}"); +/// ``` +pub fn minify<'a>(content: &'a str) -> Result<Minified<'a>, &'static str> { + token::tokenize(content).map(Minified) +} + +pub struct Minified<'a>(token::Tokens<'a>); + +impl<'a> Minified<'a> { + pub fn write<W: io::Write>(self, w: W) -> io::Result<()> { + self.0.write(w) + } +} + +impl<'a> fmt::Display for Minified<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(test)] +mod tests; diff --git a/vendor/minifier/src/css/tests.rs b/vendor/minifier/src/css/tests.rs new file mode 100644 index 000000000..dd696afde --- /dev/null +++ b/vendor/minifier/src/css/tests.rs @@ -0,0 +1,286 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::css::minify; + +/*enum Element { + /// Rule starting with `@`: + /// + /// * charset + /// * font-face + /// * import + /// * keyframes + /// * media + AtRule(AtRule<'a>), + /// Any "normal" CSS rule block. + /// + /// Contains the selector(s) and its content. + ElementRule(Vec<&'a str>, Vec<Property<'a>>), +} + +fn get_property<'a>(source: &'a str, iterator: &mut Peekable<CharIndices>, + start_pos: &mut usize) -> Option<Property<'a>> { + let mut end_pos = None; + // First we get the property name. + while let Some((pos, c)) = iterator.next() { + if let Ok(c) = ReservedChar::try_from(c) { + if c.is_useless() { + continue + } else if c == ReservedChar::OpenCurlyBrace { + return None + } else if c == ReservedChar::Colon { + end_pos = Some(pos); + break + } else { // Invalid character. + return None; + } + } else if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' { + // everything's fine for now... + } else { + return None; // invalid character + } + } + if end_pos.is_none() || end_pos == Some(*start_pos + 1) { + return None; + } + while let Some((pos, c)) = iterator.next() { + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::DoubleQuote || c == ReservedChar::Quote { + get_string(source, iterator, &mut 0, c) + } else if c == ReservedChar::SemiColon { + // we reached the end! + let end_pos = end_pos.unwrap(); + *start_pos = pos; + return Property { + name: &source[start_pos..end_pos], + value: &source[end_pos..pos], + } + } + } + } + None +} + +enum Selector<'a> { + Tag(&'a str), + /// '.' + Class(&'a str), + /// '#' + Id(&'a str), + /// '<', '>', '(', ')', '+', ' ', '[', ']' + Operator(char), +} + +struct ElementRule<'a> { + selectors: Vec<Selector<'a>>, + properties: Vec<Property<'a>>, +} + +fn get_element_rule<'a>(source: &'a str, iterator: &mut Peekable<CharIndices>, + c: char) -> Option<Token<'a>> { + let mut selectors = Vec::with_capacity(2); + + while let Some(s) = get_next_selector(source, iterator, c) { + if !selectors.is_empty() || !s.empty_operator() { + } + selectors.push(s); + } +} + +fn get_media_query<'a>(source: &'a str, iterator: &mut Peekable<CharIndices>, + start_pos: &mut usize) -> Option<Token<'a>> { + while let Some((pos, c)) = iterator.next() { + if c == '{' { + ; + } + } + None // An error occurred, sad life... +} + + +fn get_properties<'a>(source: &'a str, iterator: &mut Peekable<CharIndices>, + start_pos: &mut usize) -> Vec<Property> { + let mut ret = Vec::with_capacity(2); + while let Some(property) = get_property(source, iterator, start_pos) { + ret.push(property); + } + ret +} + +pub struct Property<'a> { + name: &'a str, + value: &'a str, +} + +pub enum AtRule<'a> { + /// Contains the charset. Supposed to be the first rule in the style sheet and be present + /// only once. + Charset(&'a str), + /// font-face rule. + FontFace(Vec<Property<'a>>), + /// Contains the import. + Import(&'a str), + /// Contains the rule and the block. + Keyframes(&'a str, Tokens<'a>), + /// Contains the rules and the block. + Media(Vec<&'a str>, Tokens<'a>), +} + +impl fmt::Display for AtRule { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "@{}", &match *self { + AtRule::Charset(c) => format!("charset {};", c), + AtRule::FontFace(t) => format!("font-face {{{}}};", t), + AtRule::Import(i) => format!("import {};", i), + AtRule::Keyframes(r, t) => format!("keyframes {} {{{}}}", r, t), + AtRule::Media(r, t) => format!("media {} {{{}}}", r.join(" ").collect::<String>(), t), + }) + } +}*/ + +#[test] +fn check_minification() { + let s = r#" +/** Baguette! */ +.b > p + div:hover { + background: #fff; +} + +a[target = "_blank"] { + /* I like weird tests. */ + border: 1px solid yellow ; +} +"#; + let expected = r#"/*! Baguette! */ +.b>p+div:hover{background:#fff;}a[target="_blank"]{border:1px solid yellow;}"#; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_minification2() { + let s = r#" +h2, h3:not(.impl):not(.method):not(.type) { + background-color: #0a042f !important; +} + +:target { background: #494a3d; } + +.table-display tr td:first-child { + float: right; +} + +/* just some + * long + * + * very + * long + * comment :) + */ +@media (max-width: 700px) { + .theme-picker { + left: 10px; + top: 54px; + z-index: 1; + background-color: rgba(0, 0 , 0 , 0); + font: 15px "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace; + } +}"#; + let expected = "h2,h3:not(.impl):not(.method):not(.type){background-color:#0a042f !important;}\ + :target{background:#494a3d;}.table-display tr td:first-child{float:right;}\ + @media (max-width:700px){.theme-picker{left:10px;top:54px;z-index:1;\ + background-color:rgba(0,0,0,0);font:15px \"SFMono-Regular\",Consolas,\ + \"Liberation Mono\",Menlo,Courier,monospace;}}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_calc() { + let s = ".foo { width: calc(100% - 34px); }"; + let expected = ".foo{width:calc(100% - 34px);}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_spaces() { + let s = ".line-numbers .line-highlighted { color: #0a042f !important; }"; + let expected = ".line-numbers .line-highlighted{color:#0a042f !important;}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_space_after_paren() { + let s = ".docblock:not(.type-decl) a:not(.srclink) {}"; + let expected = ".docblock:not(.type-decl) a:not(.srclink){}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_space_after_and() { + let s = "@media only screen and (max-width : 600px) {}"; + let expected = "@media only screen and (max-width:600px){}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_space_after_or_not() { + let s = "@supports not ((text-align-last: justify) or (-moz-text-align-last: justify)) {}"; + let expected = "@supports not ((text-align-last:justify) or (-moz-text-align-last:justify)){}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_space_after_brackets() { + let s = "#main[data-behavior = \"1\"] {}"; + let expected = "#main[data-behavior=\"1\"]{}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); + + let s = "#main[data-behavior = \"1\"] .aclass"; + let expected = "#main[data-behavior=\"1\"] .aclass"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); + + let s = "#main[data-behavior = \"1\"] ul.aclass"; + let expected = "#main[data-behavior=\"1\"] ul.aclass"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_whitespaces_in_calc() { + let s = ".foo { width: calc(130px + 10%); }"; + let expected = ".foo{width:calc(130px + 10%);}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); + + let s = ".foo { width: calc(130px + (45% - 10% + (12 * 2px))); }"; + let expected = ".foo{width:calc(130px + (45% - 10% + (12 * 2px)));}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_weird_comments() { + let s = ".test1 { + font-weight: 30em; +}/**/ +.test2 { + font-weight: 30em; +}/**/ +.test3 { + font-weight: 30em; +}/**/"; + let expected = ".test1{font-weight:30em;}.test2{font-weight:30em;}.test3{font-weight:30em;}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn check_slash_slash() { + let s = "body { + background-image: url(data:image/webp;base64,c//S4KP//ZZ/19Uj/UA==); +}"; + let expected = "body{background-image:url(data:image/webp;base64,c//S4KP//ZZ/19Uj/UA==);}"; + assert_eq!(minify(s).expect("minify failed").to_string(), expected); +} + +#[test] +fn issue_80() { + assert_eq!( + minify("@import 'i';t{x: #fff;}").unwrap().to_string(), + "@import 'i';t{x:#fff;}", + ); +} diff --git a/vendor/minifier/src/css/token.rs b/vendor/minifier/src/css/token.rs new file mode 100644 index 000000000..d2d738840 --- /dev/null +++ b/vendor/minifier/src/css/token.rs @@ -0,0 +1,875 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::convert::TryFrom; +use std::fmt; +use std::iter::Peekable; +use std::str::CharIndices; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum ReservedChar { + Comma, + SuperiorThan, + OpenParenthese, + CloseParenthese, + OpenCurlyBrace, + CloseCurlyBrace, + OpenBracket, + CloseBracket, + Colon, + SemiColon, + Slash, + Plus, + EqualSign, + Space, + Tab, + Backline, + Star, + Quote, + DoubleQuote, + Pipe, + Tilde, + Dollar, + Circumflex, +} + +impl fmt::Display for ReservedChar { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + ReservedChar::Comma => ',', + ReservedChar::OpenParenthese => '(', + ReservedChar::CloseParenthese => ')', + ReservedChar::OpenCurlyBrace => '{', + ReservedChar::CloseCurlyBrace => '}', + ReservedChar::OpenBracket => '[', + ReservedChar::CloseBracket => ']', + ReservedChar::Colon => ':', + ReservedChar::SemiColon => ';', + ReservedChar::Slash => '/', + ReservedChar::Star => '*', + ReservedChar::Plus => '+', + ReservedChar::EqualSign => '=', + ReservedChar::Space => ' ', + ReservedChar::Tab => '\t', + ReservedChar::Backline => '\n', + ReservedChar::SuperiorThan => '>', + ReservedChar::Quote => '\'', + ReservedChar::DoubleQuote => '"', + ReservedChar::Pipe => '|', + ReservedChar::Tilde => '~', + ReservedChar::Dollar => '$', + ReservedChar::Circumflex => '^', + } + ) + } +} + +impl TryFrom<char> for ReservedChar { + type Error = &'static str; + + fn try_from(value: char) -> Result<ReservedChar, Self::Error> { + match value { + '\'' => Ok(ReservedChar::Quote), + '"' => Ok(ReservedChar::DoubleQuote), + ',' => Ok(ReservedChar::Comma), + '(' => Ok(ReservedChar::OpenParenthese), + ')' => Ok(ReservedChar::CloseParenthese), + '{' => Ok(ReservedChar::OpenCurlyBrace), + '}' => Ok(ReservedChar::CloseCurlyBrace), + '[' => Ok(ReservedChar::OpenBracket), + ']' => Ok(ReservedChar::CloseBracket), + ':' => Ok(ReservedChar::Colon), + ';' => Ok(ReservedChar::SemiColon), + '/' => Ok(ReservedChar::Slash), + '*' => Ok(ReservedChar::Star), + '+' => Ok(ReservedChar::Plus), + '=' => Ok(ReservedChar::EqualSign), + ' ' => Ok(ReservedChar::Space), + '\t' => Ok(ReservedChar::Tab), + '\n' | '\r' => Ok(ReservedChar::Backline), + '>' => Ok(ReservedChar::SuperiorThan), + '|' => Ok(ReservedChar::Pipe), + '~' => Ok(ReservedChar::Tilde), + '$' => Ok(ReservedChar::Dollar), + '^' => Ok(ReservedChar::Circumflex), + _ => Err("Unknown reserved char"), + } + } +} + +impl ReservedChar { + fn is_useless(&self) -> bool { + *self == ReservedChar::Space + || *self == ReservedChar::Tab + || *self == ReservedChar::Backline + } + + fn is_operator(&self) -> bool { + Operator::try_from(*self).is_ok() + } +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Operator { + Plus, + Multiply, + Minus, + Modulo, + Divide, +} + +impl fmt::Display for Operator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + Operator::Plus => '+', + Operator::Multiply => '*', + Operator::Minus => '-', + Operator::Modulo => '%', + Operator::Divide => '/', + } + ) + } +} + +impl TryFrom<char> for Operator { + type Error = &'static str; + + fn try_from(value: char) -> Result<Operator, Self::Error> { + match value { + '+' => Ok(Operator::Plus), + '*' => Ok(Operator::Multiply), + '-' => Ok(Operator::Minus), + '%' => Ok(Operator::Modulo), + '/' => Ok(Operator::Divide), + _ => Err("Unknown operator"), + } + } +} + +impl TryFrom<ReservedChar> for Operator { + type Error = &'static str; + + fn try_from(value: ReservedChar) -> Result<Operator, Self::Error> { + match value { + ReservedChar::Slash => Ok(Operator::Divide), + ReservedChar::Star => Ok(Operator::Multiply), + ReservedChar::Plus => Ok(Operator::Plus), + _ => Err("Unknown operator"), + } + } +} + +#[derive(Eq, PartialEq, Clone, Debug)] +pub enum SelectorElement<'a> { + PseudoClass(&'a str), + Class(&'a str), + Id(&'a str), + Tag(&'a str), + Media(&'a str), +} + +impl<'a> TryFrom<&'a str> for SelectorElement<'a> { + type Error = &'static str; + + fn try_from(value: &'a str) -> Result<SelectorElement<'_>, Self::Error> { + if let Some(value) = value.strip_prefix('.') { + if value.is_empty() { + Err("cannot determine selector") + } else { + Ok(SelectorElement::Class(value)) + } + } else if let Some(value) = value.strip_prefix('#') { + if value.is_empty() { + Err("cannot determine selector") + } else { + Ok(SelectorElement::Id(value)) + } + } else if let Some(value) = value.strip_prefix('@') { + if value.is_empty() { + Err("cannot determine selector") + } else { + Ok(SelectorElement::Media(value)) + } + } else if let Some(value) = value.strip_prefix(':') { + if value.is_empty() { + Err("cannot determine selector") + } else { + Ok(SelectorElement::PseudoClass(value)) + } + } else if value.chars().next().unwrap_or(' ').is_alphabetic() { + Ok(SelectorElement::Tag(value)) + } else { + Err("unknown selector") + } + } +} + +impl<'a> fmt::Display for SelectorElement<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + SelectorElement::Class(c) => write!(f, ".{}", c), + SelectorElement::Id(i) => write!(f, "#{}", i), + SelectorElement::Tag(t) => write!(f, "{}", t), + SelectorElement::Media(m) => write!(f, "@{} ", m), + SelectorElement::PseudoClass(pc) => write!(f, ":{}", pc), + } + } +} + +#[derive(Eq, PartialEq, Clone, Debug, Copy)] +pub enum SelectorOperator { + /// `~=` + OneAttributeEquals, + /// `|=` + EqualsOrStartsWithFollowedByDash, + /// `$=` + EndsWith, + /// `^=` + FirstStartsWith, + /// `*=` + Contains, +} + +impl fmt::Display for SelectorOperator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + SelectorOperator::OneAttributeEquals => write!(f, "~="), + SelectorOperator::EqualsOrStartsWithFollowedByDash => write!(f, "|="), + SelectorOperator::EndsWith => write!(f, "$="), + SelectorOperator::FirstStartsWith => write!(f, "^="), + SelectorOperator::Contains => write!(f, "*="), + } + } +} + +#[derive(Eq, PartialEq, Clone, Debug)] +pub enum Token<'a> { + /// Comment. + Comment(&'a str), + /// Comment starting with `/**`. + License(&'a str), + Char(ReservedChar), + Other(&'a str), + SelectorElement(SelectorElement<'a>), + String(&'a str), + SelectorOperator(SelectorOperator), + Operator(Operator), +} + +impl<'a> fmt::Display for Token<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + // Token::AtRule(at_rule) => write!(f, "{}", at_rule, content), + // Token::ElementRule(selectors) => write!(f, "{}", x), + Token::Comment(c) => write!(f, "{}", c), + Token::License(l) => writeln!(f, "/*!{}*/", l), + Token::Char(c) => write!(f, "{}", c), + Token::Other(s) => write!(f, "{}", s), + Token::SelectorElement(ref se) => write!(f, "{}", se), + Token::String(s) => write!(f, "{}", s), + Token::SelectorOperator(so) => write!(f, "{}", so), + Token::Operator(op) => write!(f, "{}", op), + } + } +} + +impl<'a> Token<'a> { + fn is_comment(&self) -> bool { + matches!(*self, Token::Comment(_)) + } + + fn is_char(&self) -> bool { + matches!(*self, Token::Char(_)) + } + + fn get_char(&self) -> Option<ReservedChar> { + match *self { + Token::Char(c) => Some(c), + _ => None, + } + } + + fn is_useless(&self) -> bool { + match *self { + Token::Char(c) => c.is_useless(), + _ => false, + } + } + + fn is_a_media(&self) -> bool { + matches!(*self, Token::SelectorElement(SelectorElement::Media(_))) + } + + fn is_a_license(&self) -> bool { + matches!(*self, Token::License(_)) + } + + fn is_operator(&self) -> bool { + match *self { + Token::Operator(_) => true, + Token::Char(c) => c.is_operator(), + _ => false, + } + } +} + +impl<'a> PartialEq<ReservedChar> for Token<'a> { + fn eq(&self, other: &ReservedChar) -> bool { + match *self { + Token::Char(c) => c == *other, + _ => false, + } + } +} + +fn get_comment<'a>( + source: &'a str, + iterator: &mut Peekable<CharIndices<'_>>, + start_pos: &mut usize, +) -> Option<Token<'a>> { + let mut prev = ReservedChar::Quote; + *start_pos += 1; + let builder = if let Some((_, c)) = iterator.next() { + if c == '!' || (c == '*' && iterator.peek().map(|(_, c)| c) != Some(&'/')) { + *start_pos += 1; + Token::License + } else { + if let Ok(c) = ReservedChar::try_from(c) { + prev = c; + } + Token::Comment + } + } else { + Token::Comment + }; + + for (pos, c) in iterator { + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::Slash && prev == ReservedChar::Star { + let ret = Some(builder(&source[*start_pos..pos - 1])); + *start_pos = pos; + return ret; + } + prev = c; + } else { + prev = ReservedChar::Space; + } + } + None +} + +fn get_string<'a>( + source: &'a str, + iterator: &mut Peekable<CharIndices<'_>>, + start_pos: &mut usize, + start: ReservedChar, +) -> Option<Token<'a>> { + while let Some((pos, c)) = iterator.next() { + if c == '\\' { + // we skip next character + iterator.next(); + continue; + } + if let Ok(c) = ReservedChar::try_from(c) { + if c == start { + let ret = Some(Token::String(&source[*start_pos..pos + 1])); + *start_pos = pos; + return ret; + } + } + } + None +} + +fn fill_other<'a>( + source: &'a str, + v: &mut Vec<Token<'a>>, + start: usize, + pos: usize, + is_in_block: isize, + is_in_media: bool, + is_in_attribute_selector: bool, +) { + if start < pos { + if !is_in_attribute_selector + && ((is_in_block == 0 && !is_in_media) || (is_in_media && is_in_block == 1)) + { + let mut is_pseudo_class = false; + let mut add = 0; + if let Some(&Token::Char(ReservedChar::Colon)) = v.last() { + is_pseudo_class = true; + add = 1; + } + if let Ok(s) = SelectorElement::try_from(&source[start - add..pos]) { + if is_pseudo_class { + v.pop(); + } + v.push(Token::SelectorElement(s)); + } else { + let s = &source[start..pos]; + if !s.starts_with(':') + && !s.starts_with('.') + && !s.starts_with('#') + && !s.starts_with('@') + { + v.push(Token::Other(s)); + } + } + } else { + v.push(Token::Other(&source[start..pos])); + } + } +} + +#[allow(clippy::comparison_chain)] +pub(super) fn tokenize<'a>(source: &'a str) -> Result<Tokens<'a>, &'static str> { + let mut v = Vec::with_capacity(1000); + let mut iterator = source.char_indices().peekable(); + let mut start = 0; + let mut is_in_block: isize = 0; + let mut is_in_media = false; + let mut is_in_attribute_selector = false; + + loop { + let (mut pos, c) = match iterator.next() { + Some(x) => x, + None => { + fill_other( + source, + &mut v, + start, + source.len(), + is_in_block, + is_in_media, + is_in_attribute_selector, + ); + break; + } + }; + if let Ok(c) = ReservedChar::try_from(c) { + fill_other( + source, + &mut v, + start, + pos, + is_in_block, + is_in_media, + is_in_attribute_selector, + ); + is_in_media = is_in_media + || v.last() + .unwrap_or(&Token::Char(ReservedChar::Space)) + .is_a_media(); + match c { + ReservedChar::Quote | ReservedChar::DoubleQuote => { + if let Some(s) = get_string(source, &mut iterator, &mut pos, c) { + v.push(s); + } + } + ReservedChar::Star + if *v.last().unwrap_or(&Token::Char(ReservedChar::Space)) + == ReservedChar::Slash => + { + v.pop(); + if let Some(s) = get_comment(source, &mut iterator, &mut pos) { + v.push(s); + } + } + ReservedChar::OpenBracket => { + if is_in_attribute_selector { + return Err("Already in attribute selector"); + } + is_in_attribute_selector = true; + v.push(Token::Char(c)); + } + ReservedChar::CloseBracket => { + if !is_in_attribute_selector { + return Err("Unexpected ']'"); + } + is_in_attribute_selector = false; + v.push(Token::Char(c)); + } + ReservedChar::OpenCurlyBrace => { + is_in_block += 1; + v.push(Token::Char(c)); + } + ReservedChar::CloseCurlyBrace => { + is_in_block -= 1; + if is_in_block < 0 { + return Err("Too much '}'"); + } else if is_in_block == 0 { + is_in_media = false; + } + v.push(Token::Char(c)); + } + ReservedChar::SemiColon if is_in_block == 0 => { + is_in_media = false; + v.push(Token::Char(c)); + } + ReservedChar::EqualSign => { + match match v + .last() + .unwrap_or(&Token::Char(ReservedChar::Space)) + .get_char() + .unwrap_or(ReservedChar::Space) + { + ReservedChar::Tilde => Some(SelectorOperator::OneAttributeEquals), + ReservedChar::Pipe => { + Some(SelectorOperator::EqualsOrStartsWithFollowedByDash) + } + ReservedChar::Dollar => Some(SelectorOperator::EndsWith), + ReservedChar::Circumflex => Some(SelectorOperator::FirstStartsWith), + ReservedChar::Star => Some(SelectorOperator::Contains), + _ => None, + } { + Some(r) => { + v.pop(); + v.push(Token::SelectorOperator(r)); + } + None => v.push(Token::Char(c)), + } + } + c if !c.is_useless() => { + v.push(Token::Char(c)); + } + c => { + if !v + .last() + .unwrap_or(&Token::Char(ReservedChar::Space)) + .is_useless() + && (!v + .last() + .unwrap_or(&Token::Char(ReservedChar::OpenCurlyBrace)) + .is_char() + || v.last() + .unwrap_or(&Token::Char(ReservedChar::OpenCurlyBrace)) + .is_operator() + || v.last() + .unwrap_or(&Token::Char(ReservedChar::OpenCurlyBrace)) + .get_char() + == Some(ReservedChar::CloseParenthese) + || v.last() + .unwrap_or(&Token::Char(ReservedChar::OpenCurlyBrace)) + .get_char() + == Some(ReservedChar::CloseBracket)) + { + v.push(Token::Char(ReservedChar::Space)); + } else if let Ok(op) = Operator::try_from(c) { + v.push(Token::Operator(op)); + } + } + } + start = pos + 1; + } + } + Ok(Tokens(clean_tokens(v))) +} + +fn clean_tokens(mut v: Vec<Token<'_>>) -> Vec<Token<'_>> { + let mut i = 0; + let mut is_in_calc = false; + let mut paren = 0; + + while i < v.len() { + if v[i] == Token::Other("calc") { + is_in_calc = true; + } else if is_in_calc { + if v[i] == Token::Char(ReservedChar::CloseParenthese) { + paren -= 1; + is_in_calc = paren != 0; + } else if v[i] == Token::Char(ReservedChar::OpenParenthese) { + paren += 1; + } + } + + if v[i].is_useless() { + if i > 0 && v[i - 1] == Token::Char(ReservedChar::CloseBracket) { + if i + 1 < v.len() + && (v[i + 1].is_useless() + || v[i + 1] == Token::Char(ReservedChar::OpenCurlyBrace)) + { + v.remove(i); + continue; + } + } else if i > 0 + && (v[i - 1] == Token::Other("and") + || v[i - 1] == Token::Other("or") + || v[i - 1] == Token::Other("not")) + { + // retain the space after "and", "or" or "not" + } else if (is_in_calc && v[i - 1].is_useless()) + || !is_in_calc + && ((i > 0 + && ((v[i - 1].is_char() + && v[i - 1] != Token::Char(ReservedChar::CloseParenthese)) + || v[i - 1].is_a_media() + || v[i - 1].is_a_license())) + || (i < v.len() - 1 && v[i + 1].is_char())) + { + v.remove(i); + continue; + } + } else if v[i].is_comment() { + v.remove(i); + continue; + } + i += 1; + } + v +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub(super) struct Tokens<'a>(Vec<Token<'a>>); + +impl<'a> Tokens<'a> { + pub(super) fn write<W: std::io::Write>(self, mut w: W) -> std::io::Result<()> { + for token in self.0.iter() { + write!(w, "{}", token)?; + } + Ok(()) + } +} + +impl<'a> fmt::Display for Tokens<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for token in self.0.iter() { + write!(f, "{}", token)?; + } + Ok(()) + } +} + +#[test] +fn css_basic() { + let s = r#" +/*! just some license */ +.foo > #bar p:hover { + color: blue; + background: "blue"; +} + +/* a comment! */ +@media screen and (max-width: 640px) { + .block:hover { + display: block; + } +}"#; + let expected = vec![ + Token::License(" just some license "), + Token::SelectorElement(SelectorElement::Class("foo")), + Token::Char(ReservedChar::SuperiorThan), + Token::SelectorElement(SelectorElement::Id("bar")), + Token::Char(ReservedChar::Space), + Token::SelectorElement(SelectorElement::Tag("p")), + Token::SelectorElement(SelectorElement::PseudoClass("hover")), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("color"), + Token::Char(ReservedChar::Colon), + Token::Other("blue"), + Token::Char(ReservedChar::SemiColon), + Token::Other("background"), + Token::Char(ReservedChar::Colon), + Token::String("\"blue\""), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Media("media")), + Token::Other("screen"), + Token::Char(ReservedChar::Space), + Token::Other("and"), + Token::Char(ReservedChar::Space), + Token::Char(ReservedChar::OpenParenthese), + Token::Other("max-width"), + Token::Char(ReservedChar::Colon), + Token::Other("640px"), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::SelectorElement(SelectorElement::Class("block")), + Token::SelectorElement(SelectorElement::PseudoClass("hover")), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("display"), + Token::Char(ReservedChar::Colon), + Token::Other("block"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::Char(ReservedChar::CloseCurlyBrace), + ]; + assert_eq!(tokenize(s), Ok(Tokens(expected))); +} + +#[test] +fn elem_selector() { + let s = r#" +/** just some license */ +a[href*="example"] { + background: yellow; +} +a[href$=".org"] { + font-style: italic; +} +span[lang|="zh"] { + color: red; +} +a[href^="/"] { + background-color: gold; +} +div[value~="test"] { + border-width: 1px; +} +span[lang="pt"] { + font-size: 12em; /* I love big fonts */ +} +"#; + let expected = vec![ + Token::License(" just some license "), + Token::SelectorElement(SelectorElement::Tag("a")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("href"), + Token::SelectorOperator(SelectorOperator::Contains), + Token::String("\"example\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("background"), + Token::Char(ReservedChar::Colon), + Token::Other("yellow"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("a")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("href"), + Token::SelectorOperator(SelectorOperator::EndsWith), + Token::String("\".org\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("font-style"), + Token::Char(ReservedChar::Colon), + Token::Other("italic"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("span")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("lang"), + Token::SelectorOperator(SelectorOperator::EqualsOrStartsWithFollowedByDash), + Token::String("\"zh\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("color"), + Token::Char(ReservedChar::Colon), + Token::Other("red"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("a")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("href"), + Token::SelectorOperator(SelectorOperator::FirstStartsWith), + Token::String("\"/\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("background-color"), + Token::Char(ReservedChar::Colon), + Token::Other("gold"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("div")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("value"), + Token::SelectorOperator(SelectorOperator::OneAttributeEquals), + Token::String("\"test\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("border-width"), + Token::Char(ReservedChar::Colon), + Token::Other("1px"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("span")), + Token::Char(ReservedChar::OpenBracket), + Token::Other("lang"), + Token::Char(ReservedChar::EqualSign), + Token::String("\"pt\""), + Token::Char(ReservedChar::CloseBracket), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("font-size"), + Token::Char(ReservedChar::Colon), + Token::Other("12em"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + ]; + assert_eq!(tokenize(s), Ok(Tokens(expected))); +} + +#[test] +fn check_media() { + let s = "@media (max-width: 700px) { color: red; }"; + + let expected = vec![ + Token::SelectorElement(SelectorElement::Media("media")), + Token::Char(ReservedChar::OpenParenthese), + Token::Other("max-width"), + Token::Char(ReservedChar::Colon), + Token::Other("700px"), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("color")), + Token::Char(ReservedChar::Colon), + Token::Other("red"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + ]; + + assert_eq!(tokenize(s), Ok(Tokens(expected))); +} + +#[test] +fn check_supports() { + let s = "@supports not (display: grid) { div { float: right; } }"; + + let expected = vec![ + Token::SelectorElement(SelectorElement::Media("supports")), + Token::Other("not"), + Token::Char(ReservedChar::Space), + Token::Char(ReservedChar::OpenParenthese), + Token::Other("display"), + Token::Char(ReservedChar::Colon), + Token::Other("grid"), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::SelectorElement(SelectorElement::Tag("div")), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("float"), + Token::Char(ReservedChar::Colon), + Token::Other("right"), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + Token::Char(ReservedChar::CloseCurlyBrace), + ]; + + assert_eq!(tokenize(s), Ok(Tokens(expected))); +} + +#[test] +fn check_calc() { + let s = ".foo { width: calc(100% - 34px); }"; + + let expected = vec![ + Token::SelectorElement(SelectorElement::Class("foo")), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Other("width"), + Token::Char(ReservedChar::Colon), + Token::Other("calc"), + Token::Char(ReservedChar::OpenParenthese), + Token::Other("100%"), + Token::Char(ReservedChar::Space), + Token::Other("-"), + Token::Char(ReservedChar::Space), + Token::Other("34px"), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::SemiColon), + Token::Char(ReservedChar::CloseCurlyBrace), + ]; + assert_eq!(tokenize(s), Ok(Tokens(expected))); +} diff --git a/vendor/minifier/src/html.rs b/vendor/minifier/src/html.rs new file mode 100644 index 000000000..b6fa99362 --- /dev/null +++ b/vendor/minifier/src/html.rs @@ -0,0 +1,233 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use regex::{Captures, Regex}; + +fn condense_whitespace(source: &str) -> String { + let lower_source = source.to_lowercase(); + if lower_source.find("<textarea").is_none() && lower_source.find("<pre").is_none() { + // maybe should be better not to recreate Regex every time? + let re = Regex::new(r">\s+<").unwrap(); + let source = re.replace_all(source, "> <").into_owned(); + let re = Regex::new(r"\s{2,}|[\r\n]").unwrap(); + re.replace_all(&source, " ").into_owned() + } else { + source.trim().to_owned() + } +} + +fn condense(source: &str) -> String { + let re = Regex::new(r"<(style|script)[\w|\s].*?>").unwrap(); + let type_reg = Regex::new(r#"\s*?type="[\w|\s].*?""#).unwrap(); + re.replace_all(source, |caps: &Captures| { + type_reg.replace_all(&caps[0], "").into_owned() + }) + .into_owned() +} + +fn clean_unneeded_tags(source: &str) -> String { + let useless_tags = [ + "</area>", + "</base>", + "<body>", + "</body>", + "</br>", + "</col>", + "</colgroup>", + "</dd>", + "</dt>", + "<head>", + "</head>", + "</hr>", + "<html>", + "</html>", + "</img>", + "</input>", + "</li>", + "</link>", + "</meta>", + "</option>", + "</param>", + "<tbody>", + "</tbody>", + "</td>", + "</tfoot>", + "</th>", + "</thead>", + "</tr>", + "</basefont>", + "</isindex>", + "</param>", + ]; + let mut res = source.to_owned(); + for useless_tag in &useless_tags { + res = res.replace(useless_tag, ""); + } + res +} + +fn remove_comments(source: &str) -> String { + // "build" and "endbuild" should be matched case insensitively. + let re = Regex::new("<!--(.|\n)*?-->").unwrap(); + re.replace_all(source, |caps: &Captures| { + if caps[0].replace("<!--", " ").trim().starts_with("[") { + caps[0].to_owned() + } else { + " ".to_owned() + } + }) + .into_owned() +} + +fn unquote_attributes(source: &str) -> String { + // Some attributes like width, height, etc... don't need quotes. + let any_tag = Regex::new(r"<\w.*?>").unwrap(); + let extra_spaces = Regex::new(r" \s+|\s +").unwrap(); + let between_words = Regex::new(r"\w\s+\w").unwrap(); + let spaces_before_close = Regex::new(r##""\s+>"##).unwrap(); + let spaces_before_close2 = Regex::new(r"'\s+>").unwrap(); + let extra_spaces2 = Regex::new(r##""\s\s+\w+="|'\s\s+\w+='|"\s\s+\w+=|'\s\s+\w+="##).unwrap(); + let extra_spaces3 = Regex::new(r"\d\s+>").unwrap(); + let quotes_in_tag = Regex::new(r##"([a-zA-Z]+)="([a-zA-Z0-9-_\.]+)""##).unwrap(); + + any_tag + .replace_all(source, |caps: &Captures| { + let cap = format!("{}", &caps[0]); + if cap.starts_with("<!") || cap.find("</").is_some() { + cap + } else { + let tag = spaces_before_close.replace_all(&cap, "\">").into_owned(); + let mut tag = spaces_before_close2.replace_all(&tag, "'>").into_owned(); + let tag_c = tag.clone(); + + let space1_matches: Vec<_> = between_words.find_iter(&tag_c).collect(); + let space6_matches: Vec<_> = extra_spaces3.find_iter(&tag_c).collect(); + let mut pos = 0; + loop { + let replacement = match (space1_matches.get(pos), space6_matches.get(pos)) { + (Some(a), Some(b)) => format!("{}{}", a.as_str(), b.as_str()), + (None, Some(b)) => format!("{}", b.as_str()), + (Some(a), None) => format!("{}", a.as_str()), + _ => break, + }; + pos += 1; + tag = tag.replace( + &replacement, + &extra_spaces.replace_all(&replacement, " ").into_owned(), + ); + } + let mut output = tag.clone(); + for caps in extra_spaces2.find_iter(&tag) { + let c = caps.as_str().chars().next().unwrap_or('\0'); + output = output.replace( + caps.as_str(), + &format!( + "{} {}", + if c == '\0' { + String::new() + } else { + format!("{}", c) + }, + caps.as_str()[1..].trim_start() + ), + ); + } + tag = quotes_in_tag + .replace_all(&output, |caps: &Captures| match &caps[1] { + "width" | "height" => format!("{}={}", &caps[1], &caps[2]), + x => format!("{}=\"{}\"", x, &caps[2]), + }) + .into_owned(); + if cap != tag { + tag + } else { + cap + } + } + }) + .trim() + .to_owned() +} + +/// Returns a minified version of the provided HTML source. +pub fn minify(source: &str) -> String { + let source = remove_comments(source); + let source = condense(&source); + let source = clean_unneeded_tags(&source); + let source = condense_whitespace(&source); + unquote_attributes(&source).trim().to_owned() +} + +#[test] +fn html_minify_test() { + let source = r##"<head> + <title>Some huge title</title> + <link rel="stylesheet" type="text/css" href="something.css" > + <style type="text/css"> + .some_class { + color: red; + } + </style> +</head> +<body> + <header> + <div> + <i> <b><a href="www.somewhere.com" class="some_class">Narnia</a> </b> </i> + <h1 style="width:100%;text-align:center;" >Big header</h1> + </div> + <!-- commeeeeeeeents !!! --> + </header> + <div id="some_id"> + <!-- another comment + on +multi +lines --> + <div id="another_id" class="another_class" width="100"> + <h2>A little sub title</h2> + <ul> + <li>A list!</li> + <li>Who doesn't like lists?</li> + <li height="12" class="fooool">Well, who cares...</li> + </ul> + </div> + </div> + <script type="text/javascript" > + console.log("foo"); + </script> + <style type="text/css" src="../foo.css"> + <script src="../foo.js"> +</body> +"##; + + let expected_result = "<title>Some huge title</title> <link rel=\"stylesheet\" \ + type=\"text/css\" href=\"something.css\"> <style> .some_class \ + { color: red; } </style> <header> <div> <i> <b><a \ + href=\"www.somewhere.com\" class=\"some_class\">Narnia</a> </b> </i> \ + <h1 style=\"width:100%;text-align:center;\">Big header</h1> </div> \ + </header> <div id=\"some_id\"> <div id=\"another_id\" \ + class=\"another_class\" width=100> <h2>A little sub \ + title</h2> <ul> <li>A list! <li>Who doesn't like lists? \ + <li height=12 class=\"fooool\">Well, who cares... </ul> </div> \ + </div> <script > console.log(\"foo\"); </script> <style \ + src=\"../foo.css\"> <script src=\"../foo.js\">"; + assert_eq!(minify(source), expected_result); +} + +#[test] +fn html_keep_important_comments() { + let source = r#" +<div> + <!-- normal comment --> + <div>content</div> + <!--[if lte IE 8]> + <div class="warning">This old browser is unsupported and will most likely display funky things. + </div> + <![endif]--> +</div> +"#; + + let expected_result = + "<div> <div>content</div> <!--[if lte IE 8]> <div class=\"warning\">This \ + old browser is unsupported and will most likely display funky things. \ + </div> <![endif]--> </div>"; + assert_eq!(minify(source), expected_result); +} diff --git a/vendor/minifier/src/js/mod.rs b/vendor/minifier/src/js/mod.rs new file mode 100644 index 000000000..4e0226bd9 --- /dev/null +++ b/vendor/minifier/src/js/mod.rs @@ -0,0 +1,17 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +mod token; +mod tools; +mod utils; + +pub use self::token::{tokenize, Condition, Keyword, Operation, ReservedChar, Token, Tokens}; +pub use self::tools::{ + aggregate_strings, aggregate_strings_into_array, aggregate_strings_into_array_filter, + aggregate_strings_into_array_with_separation, + aggregate_strings_into_array_with_separation_filter, aggregate_strings_with_separation, minify, + simple_minify, +}; +pub use self::utils::{ + clean_token, clean_token_except, clean_tokens, clean_tokens_except, + get_variable_name_and_value_positions, replace_token_with, replace_tokens_with, +}; diff --git a/vendor/minifier/src/js/token.rs b/vendor/minifier/src/js/token.rs new file mode 100644 index 000000000..251394cf6 --- /dev/null +++ b/vendor/minifier/src/js/token.rs @@ -0,0 +1,1431 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::convert::TryFrom; +use std::fmt; +use std::str::{CharIndices, FromStr}; + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] +pub enum ReservedChar { + Comma, + OpenParenthese, + CloseParenthese, + OpenCurlyBrace, + CloseCurlyBrace, + OpenBracket, + CloseBracket, + Colon, + SemiColon, + Dot, + Quote, + DoubleQuote, + ExclamationMark, + QuestionMark, + Slash, + Modulo, + Star, + Minus, + Plus, + EqualSign, + Backslash, + Space, + Tab, + Backline, + LessThan, + SuperiorThan, + Pipe, + Ampersand, + BackTick, +} + +impl ReservedChar { + pub fn is_white_character(&self) -> bool { + *self == ReservedChar::Space + || *self == ReservedChar::Tab + || *self == ReservedChar::Backline + } +} + +impl fmt::Display for ReservedChar { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + ReservedChar::Comma => ',', + ReservedChar::OpenParenthese => '(', + ReservedChar::CloseParenthese => ')', + ReservedChar::OpenCurlyBrace => '{', + ReservedChar::CloseCurlyBrace => '}', + ReservedChar::OpenBracket => '[', + ReservedChar::CloseBracket => ']', + ReservedChar::Colon => ':', + ReservedChar::SemiColon => ';', + ReservedChar::Dot => '.', + ReservedChar::Quote => '\'', + ReservedChar::DoubleQuote => '"', + ReservedChar::ExclamationMark => '!', + ReservedChar::QuestionMark => '?', + ReservedChar::Slash => '/', + ReservedChar::Modulo => '%', + ReservedChar::Star => '*', + ReservedChar::Minus => '-', + ReservedChar::Plus => '+', + ReservedChar::EqualSign => '=', + ReservedChar::Backslash => '\\', + ReservedChar::Space => ' ', + ReservedChar::Tab => '\t', + ReservedChar::Backline => '\n', + ReservedChar::LessThan => '<', + ReservedChar::SuperiorThan => '>', + ReservedChar::Pipe => '|', + ReservedChar::Ampersand => '&', + ReservedChar::BackTick => '`', + } + ) + } +} + +impl TryFrom<char> for ReservedChar { + type Error = &'static str; + + fn try_from(value: char) -> Result<ReservedChar, Self::Error> { + match value { + ',' => Ok(ReservedChar::Comma), + '(' => Ok(ReservedChar::OpenParenthese), + ')' => Ok(ReservedChar::CloseParenthese), + '{' => Ok(ReservedChar::OpenCurlyBrace), + '}' => Ok(ReservedChar::CloseCurlyBrace), + '[' => Ok(ReservedChar::OpenBracket), + ']' => Ok(ReservedChar::CloseBracket), + ':' => Ok(ReservedChar::Colon), + ';' => Ok(ReservedChar::SemiColon), + '.' => Ok(ReservedChar::Dot), + '\'' => Ok(ReservedChar::Quote), + '"' => Ok(ReservedChar::DoubleQuote), + '!' => Ok(ReservedChar::ExclamationMark), + '?' => Ok(ReservedChar::QuestionMark), + '/' => Ok(ReservedChar::Slash), + '%' => Ok(ReservedChar::Modulo), + '*' => Ok(ReservedChar::Star), + '-' => Ok(ReservedChar::Minus), + '+' => Ok(ReservedChar::Plus), + '=' => Ok(ReservedChar::EqualSign), + '\\' => Ok(ReservedChar::Backslash), + ' ' => Ok(ReservedChar::Space), + '\t' => Ok(ReservedChar::Tab), + '\n' | '\r' => Ok(ReservedChar::Backline), + '<' => Ok(ReservedChar::LessThan), + '>' => Ok(ReservedChar::SuperiorThan), + '|' => Ok(ReservedChar::Pipe), + '&' => Ok(ReservedChar::Ampersand), + '`' => Ok(ReservedChar::BackTick), + _ => Err("Unknown reserved char"), + } + } +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)] +pub enum Keyword { + Break, + Case, + Catch, + Const, + Continue, + Default, + Do, + Else, + False, + Finally, + Function, + For, + If, + In, + InstanceOf, + Let, + New, + Null, + Private, + Protected, + Public, + Return, + Switch, + This, + Throw, + True, + Try, + Typeof, + Static, + Var, + While, +} + +impl Keyword { + fn requires_before(&self) -> bool { + matches!(*self, Keyword::In | Keyword::InstanceOf) + } +} + +impl fmt::Display for Keyword { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + Keyword::Break => "break", + Keyword::Case => "case", + Keyword::Catch => "catch", + Keyword::Const => "const", + Keyword::Continue => "continue", + Keyword::Default => "default", + Keyword::Do => "do", + Keyword::Else => "else", + Keyword::False => "false", + Keyword::Finally => "finally", + Keyword::Function => "function", + Keyword::For => "for", + Keyword::If => "if", + Keyword::In => "in", + Keyword::InstanceOf => "instanceof", + Keyword::Let => "let", + Keyword::New => "new", + Keyword::Null => "null", + Keyword::Private => "private", + Keyword::Protected => "protected", + Keyword::Public => "public", + Keyword::Return => "return", + Keyword::Switch => "switch", + Keyword::This => "this", + Keyword::Throw => "throw", + Keyword::True => "true", + Keyword::Try => "try", + Keyword::Typeof => "typeof", + Keyword::Static => "static", + Keyword::Var => "var", + Keyword::While => "while", + } + ) + } +} + +impl<'a> TryFrom<&'a str> for Keyword { + type Error = &'static str; + + fn try_from(value: &str) -> Result<Keyword, Self::Error> { + match value { + "break" => Ok(Keyword::Break), + "case" => Ok(Keyword::Case), + "catch" => Ok(Keyword::Catch), + "const" => Ok(Keyword::Const), + "continue" => Ok(Keyword::Continue), + "default" => Ok(Keyword::Default), + "do" => Ok(Keyword::Do), + "else" => Ok(Keyword::Else), + "false" => Ok(Keyword::False), + "finally" => Ok(Keyword::Finally), + "function" => Ok(Keyword::Function), + "for" => Ok(Keyword::For), + "if" => Ok(Keyword::If), + "in" => Ok(Keyword::In), + "instanceof" => Ok(Keyword::InstanceOf), + "let" => Ok(Keyword::Let), + "new" => Ok(Keyword::New), + "null" => Ok(Keyword::Null), + "private" => Ok(Keyword::Private), + "protected" => Ok(Keyword::Protected), + "public" => Ok(Keyword::Public), + "return" => Ok(Keyword::Return), + "switch" => Ok(Keyword::Switch), + "this" => Ok(Keyword::This), + "throw" => Ok(Keyword::Throw), + "true" => Ok(Keyword::True), + "try" => Ok(Keyword::Try), + "typeof" => Ok(Keyword::Typeof), + "static" => Ok(Keyword::Static), + "var" => Ok(Keyword::Var), + "while" => Ok(Keyword::While), + _ => Err("Unkown keyword"), + } + } +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] +pub enum Condition { + And, + Or, + DifferentThan, + SuperDifferentThan, + EqualTo, + SuperEqualTo, + SuperiorThan, + SuperiorOrEqualTo, + InferiorThan, + InferiorOrEqualTo, +} + +impl fmt::Display for Condition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + Condition::And => "&&", + Condition::Or => "||", + Condition::DifferentThan => "!=", + Condition::SuperDifferentThan => "!==", + Condition::EqualTo => "==", + Condition::SuperEqualTo => "===", + Condition::SuperiorThan => ">", + Condition::SuperiorOrEqualTo => ">=", + Condition::InferiorThan => "<", + Condition::InferiorOrEqualTo => "<=", + } + ) + } +} + +impl TryFrom<ReservedChar> for Condition { + type Error = &'static str; + + fn try_from(value: ReservedChar) -> Result<Condition, Self::Error> { + Ok(match value { + ReservedChar::SuperiorThan => Condition::SuperiorThan, + ReservedChar::LessThan => Condition::InferiorThan, + _ => return Err("Unkown condition"), + }) + } +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] +pub enum Operation { + Addition, + AdditionEqual, + Subtract, + SubtractEqual, + Multiply, + MultiplyEqual, + Divide, + DivideEqual, + Modulo, + ModuloEqual, + Equal, +} + +impl Operation { + pub fn is_assign(&self) -> bool { + matches!( + *self, + Operation::AdditionEqual + | Operation::SubtractEqual + | Operation::MultiplyEqual + | Operation::DivideEqual + | Operation::ModuloEqual + | Operation::Equal + ) + } +} + +impl fmt::Display for Operation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match *self { + Operation::Addition => "+", + Operation::AdditionEqual => "+=", + Operation::Subtract => "-", + Operation::SubtractEqual => "-=", + Operation::Multiply => "*", + Operation::MultiplyEqual => "*=", + Operation::Divide => "/", + Operation::DivideEqual => "/=", + Operation::Modulo => "%", + Operation::ModuloEqual => "%=", + Operation::Equal => "=", + } + ) + } +} + +impl TryFrom<ReservedChar> for Operation { + type Error = &'static str; + + fn try_from(value: ReservedChar) -> Result<Operation, Self::Error> { + Ok(match value { + ReservedChar::Plus => Operation::Addition, + ReservedChar::Minus => Operation::Subtract, + ReservedChar::Slash => Operation::Divide, + ReservedChar::Star => Operation::Multiply, + ReservedChar::Modulo => Operation::Modulo, + ReservedChar::EqualSign => Operation::Equal, + _ => return Err("Unkown operation"), + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Hash)] +pub enum Token<'a> { + Keyword(Keyword), + Char(ReservedChar), + String(&'a str), + Comment(&'a str), + License(&'a str), + Other(&'a str), + Regex { + regex: &'a str, + is_global: bool, + is_interactive: bool, + }, + Condition(Condition), + Operation(Operation), + CreatedVarDecl(String), + CreatedVar(String), + Number(usize), + FloatingNumber(&'a str), +} + +impl<'a> fmt::Display for Token<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Token::Keyword(x) => write!(f, "{}", x), + Token::Char(x) => write!(f, "{}", x), + Token::String(x) | Token::Comment(x) | Token::Other(x) => write!(f, "{}", x), + Token::License(x) => write!(f, "/*!{}*/", x), + Token::Regex { + regex, + is_global, + is_interactive, + } => { + let x = write!(f, "/{}/", regex); + if is_global { + write!(f, "g")?; + } + if is_interactive { + write!(f, "i")?; + } + x + } + Token::Condition(x) => write!(f, "{}", x), + Token::Operation(x) => write!(f, "{}", x), + Token::CreatedVarDecl(ref x) => write!(f, "{}", x), + Token::CreatedVar(ref x) => write!(f, "{}", x), + Token::Number(x) => write!(f, "{}", x), + Token::FloatingNumber(ref x) => write!(f, "{}", x), + } + } +} + +impl<'a> Token<'a> { + pub fn is_comment(&self) -> bool { + matches!(*self, Token::Comment(_)) + } + + pub fn is_license(&self) -> bool { + matches!(*self, Token::License(_)) + } + + pub fn is_reserved_char(&self) -> bool { + matches!(*self, Token::Char(_)) + } + + pub fn get_char(&self) -> Option<ReservedChar> { + match *self { + Token::Char(c) => Some(c), + _ => None, + } + } + + pub fn eq_char(&self, rc: ReservedChar) -> bool { + match *self { + Token::Char(c) => c == rc, + _ => false, + } + } + + pub fn eq_operation(&self, ope: Operation) -> bool { + match *self { + Token::Operation(o) => o == ope, + _ => false, + } + } + + pub fn is_operation(&self) -> bool { + matches!(*self, Token::Operation(_)) + } + + pub fn eq_condition(&self, cond: Condition) -> bool { + match *self { + Token::Condition(c) => c == cond, + _ => false, + } + } + + pub fn is_condition(&self) -> bool { + matches!(*self, Token::Condition(_)) + } + + pub fn is_other(&self) -> bool { + matches!(*self, Token::Other(_)) + } + + pub fn get_other(&self) -> Option<&str> { + match *self { + Token::Other(s) => Some(s), + _ => None, + } + } + + pub fn is_white_character(&self) -> bool { + match *self { + Token::Char(c) => c.is_white_character(), + _ => false, + } + } + + pub fn is_keyword(&self) -> bool { + matches!(*self, Token::Keyword(_)) + } + + pub fn get_keyword(&self) -> Option<Keyword> { + match *self { + Token::Keyword(k) => Some(k), + _ => None, + } + } + + pub fn is_string(&self) -> bool { + matches!(*self, Token::String(_)) + } + + pub fn get_string(&self) -> Option<&str> { + match *self { + Token::String(s) => Some(s), + _ => None, + } + } + + pub fn is_regex(&self) -> bool { + matches!(*self, Token::Regex { .. }) + } + + pub fn is_created_var_decl(&self) -> bool { + matches!(*self, Token::CreatedVarDecl(_)) + } + + pub fn is_created_var(&self) -> bool { + matches!(*self, Token::CreatedVar(_)) + } + + pub fn is_number(&self) -> bool { + matches!(*self, Token::Number(_)) + } + + pub fn is_floating_number(&self) -> bool { + matches!(*self, Token::FloatingNumber(_)) + } + + fn get_required(&self) -> Option<char> { + match *self { + Token::Keyword(_) + | Token::Other(_) + | Token::CreatedVarDecl(_) + | Token::Number(_) + | Token::FloatingNumber(_) => Some(' '), + _ => None, + } + } + + fn requires_before(&self) -> bool { + match *self { + Token::Keyword(k) => k.requires_before(), + _ => false, + } + } +} + +fn get_line_comment<'a>( + source: &'a str, + iterator: &mut MyPeekable<'_>, + start_pos: &mut usize, +) -> Option<Token<'a>> { + *start_pos += 1; + for (pos, c) in iterator { + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::Backline { + let ret = Some(Token::Comment(&source[*start_pos..pos])); + *start_pos = pos; + return ret; + } + } + } + None +} + +fn get_regex<'a>( + source: &'a str, + iterator: &mut MyPeekable<'_>, + start_pos: &mut usize, + v: &[Token<'_>], +) -> Option<Token<'a>> { + let mut back = v.len(); + while back > 0 { + back -= 1; + if v[back].is_white_character() || v[back].is_comment() || v[back].is_license() { + continue; + } + match &v[back] { + Token::Char(ReservedChar::SemiColon) + | Token::Char(ReservedChar::Colon) + | Token::Char(ReservedChar::Comma) + | Token::Char(ReservedChar::OpenBracket) + | Token::Char(ReservedChar::OpenParenthese) + | Token::Char(ReservedChar::ExclamationMark) + | Token::Char(ReservedChar::OpenCurlyBrace) + | Token::Char(ReservedChar::QuestionMark) + | Token::Char(ReservedChar::Backline) + | Token::Char(ReservedChar::Pipe) + | Token::Char(ReservedChar::Ampersand) => break, + t if t.is_operation() || t.is_condition() => break, + _ => return None, + } + } + iterator.start_save(); + while let Some((pos, c)) = iterator.next() { + if c == '\\' { + // we skip next character + iterator.next(); + continue; + } + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::Slash { + let mut is_global = false; + let mut is_interactive = false; + let mut add = 0; + loop { + match iterator.peek() { + Some((_, 'i')) => is_interactive = true, + Some((_, 'g')) => is_global = true, + _ => break, + }; + iterator.next(); + add += 1; + } + let ret = Some(Token::Regex { + regex: &source[*start_pos + 1..pos], + is_interactive, + is_global, + }); + *start_pos = pos + add; + iterator.drop_save(); + return ret; + } else if c == ReservedChar::Backline { + break; + } + } + } + iterator.stop_save(); + None +} + +fn get_comment<'a>( + source: &'a str, + iterator: &mut MyPeekable<'_>, + start_pos: &mut usize, +) -> Token<'a> { + let mut prev = ReservedChar::Quote; + *start_pos += 1; + let builder = if let Some((_, c)) = iterator.next() { + if c == '!' { + *start_pos += 1; + Token::License + } else { + if let Ok(c) = ReservedChar::try_from(c) { + prev = c; + } + Token::Comment + } + } else { + Token::Comment + }; + + let mut current_pos = *start_pos; + for (pos, c) in iterator { + current_pos = pos; + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::Slash && prev == ReservedChar::Star { + current_pos -= 2; + break; + } + prev = c; + } else { + prev = ReservedChar::Space; + } + } + // Unclosed comment so returning it anyway... + let ret = builder(&source[*start_pos..=current_pos]); + *start_pos = current_pos + 2; + ret +} + +fn get_string<'a>( + source: &'a str, + iterator: &mut MyPeekable<'_>, + start_pos: &mut usize, + start: ReservedChar, +) -> Option<Token<'a>> { + while let Some((pos, c)) = iterator.next() { + if c == '\\' { + // we skip next character + iterator.next(); + continue; + } + if let Ok(c) = ReservedChar::try_from(c) { + if c == start { + let ret = Some(Token::String(&source[*start_pos..pos + 1])); + *start_pos = pos; + return ret; + } + } + } + None +} + +fn get_backtick_string<'a>( + source: &'a str, + iterator: &mut MyPeekable<'_>, + start_pos: &mut usize, +) -> Option<Token<'a>> { + while let Some((pos, c)) = iterator.next() { + if c == '\\' { + // we skip next character + iterator.next(); + continue; + } + if c == '$' && iterator.peek().map(|(_, c)| c == '{').unwrap_or(false) { + let mut count = 0; + + loop { + if let Some((mut pos, c)) = iterator.next() { + if c == '\\' { + // we skip next character + iterator.next(); + continue; + } else if c == '"' || c == '\'' { + // We don't care about the result + get_string( + source, + iterator, + &mut pos, + ReservedChar::try_from(c) + .expect("ReservedChar::try_from unexpectedly failed..."), + ); + } else if c == '`' { + get_backtick_string(source, iterator, &mut pos); + } else if c == '{' { + count += 1; + } else if c == '}' { + count -= 1; + if count == 0 { + break; + } + } + } else { + return None; + } + } + } else if c == '`' { + let ret = Some(Token::String(&source[*start_pos..pos + 1])); + *start_pos = pos; + return ret; + } + } + None +} + +fn first_useful<'a>(v: &'a [Token<'a>]) -> Option<&'a Token<'a>> { + for x in v.iter().rev() { + if x.is_white_character() { + continue; + } + return Some(x); + } + None +} + +fn fill_other<'a>(source: &'a str, v: &mut Vec<Token<'a>>, start: usize, pos: usize) { + if start < pos { + if let Ok(w) = Keyword::try_from(&source[start..pos]) { + v.push(Token::Keyword(w)); + } else if let Ok(n) = usize::from_str(&source[start..pos]) { + v.push(Token::Number(n)) + } else if f64::from_str(&source[start..pos]).is_ok() { + v.push(Token::FloatingNumber(&source[start..pos])) + } else { + v.push(Token::Other(&source[start..pos])); + } + } +} + +fn handle_equal_sign(v: &mut Vec<Token<'_>>, c: ReservedChar) -> bool { + if c != ReservedChar::EqualSign { + return false; + } + match v.last().unwrap_or(&Token::Other("")) { + Token::Operation(Operation::Equal) => { + v.pop(); + v.push(Token::Condition(Condition::EqualTo)); + } + Token::Condition(Condition::EqualTo) => { + v.pop(); + v.push(Token::Condition(Condition::SuperEqualTo)); + } + Token::Char(ReservedChar::ExclamationMark) => { + v.pop(); + v.push(Token::Condition(Condition::DifferentThan)); + } + Token::Condition(Condition::DifferentThan) => { + v.pop(); + v.push(Token::Condition(Condition::SuperDifferentThan)); + } + Token::Operation(Operation::Divide) => { + v.pop(); + v.push(Token::Operation(Operation::DivideEqual)); + } + Token::Operation(Operation::Multiply) => { + v.pop(); + v.push(Token::Operation(Operation::MultiplyEqual)); + } + Token::Operation(Operation::Addition) => { + v.pop(); + v.push(Token::Operation(Operation::AdditionEqual)); + } + Token::Operation(Operation::Subtract) => { + v.pop(); + v.push(Token::Operation(Operation::SubtractEqual)); + } + Token::Operation(Operation::Modulo) => { + v.pop(); + v.push(Token::Operation(Operation::ModuloEqual)); + } + Token::Condition(Condition::SuperiorThan) => { + v.pop(); + v.push(Token::Condition(Condition::SuperiorOrEqualTo)); + } + Token::Condition(Condition::InferiorThan) => { + v.pop(); + v.push(Token::Condition(Condition::InferiorOrEqualTo)); + } + _ => { + return false; + } + } + true +} + +fn check_if_number<'a>( + iterator: &mut MyPeekable<'_>, + start: usize, + pos: usize, + source: &'a str, +) -> bool { + if source[start..pos].find('.').is_some() { + return false; + } else if u64::from_str(&source[start..pos]).is_ok() { + return true; + } else if let Some((_, x)) = iterator.peek() { + return x as u8 >= b'0' && x as u8 <= b'9'; + } + false +} + +struct MyPeekable<'a> { + inner: CharIndices<'a>, + saved: Vec<(usize, char)>, + peeked: Option<(usize, char)>, + is_saving: bool, +} + +impl<'a> MyPeekable<'a> { + fn new(indices: CharIndices<'a>) -> MyPeekable<'a> { + MyPeekable { + inner: indices, + saved: Vec::with_capacity(500), + peeked: None, + is_saving: false, + } + } + + fn start_save(&mut self) { + self.is_saving = true; + if let Some(p) = self.peeked { + self.saved.push(p); + } + } + + fn drop_save(&mut self) { + self.is_saving = false; + self.saved.clear(); + } + + fn stop_save(&mut self) { + self.is_saving = false; + if let Some(p) = self.peeked { + self.saved.push(p); + } + self.peeked = None; + } + + /// Returns None if saving. + fn peek(&mut self) -> Option<(usize, char)> { + if self.peeked.is_none() { + self.peeked = self.inner.next(); + if self.is_saving { + if let Some(p) = self.peeked { + self.saved.push(p); + } + } + } + self.peeked + } +} + +impl<'a> Iterator for MyPeekable<'a> { + type Item = (usize, char); + + fn next(&mut self) -> Option<Self::Item> { + if self.peeked.is_some() { + self.peeked.take() + } else { + if !self.is_saving && !self.saved.is_empty() { + return Some(self.saved.remove(0)); + } + match self.inner.next() { + Some(r) if self.is_saving => { + self.saved.push(r); + Some(r) + } + r => r, + } + } + } +} + +pub fn tokenize(source: &str) -> Tokens<'_> { + let mut v = Vec::with_capacity(1000); + let mut start = 0; + let mut iterator = MyPeekable::new(source.char_indices()); + + loop { + let (mut pos, c) = match iterator.next() { + Some(x) => x, + None => { + fill_other(source, &mut v, start, source.len()); + break; + } + }; + if let Ok(c) = ReservedChar::try_from(c) { + if c == ReservedChar::Dot && check_if_number(&mut iterator, start, pos, source) { + let mut cont = true; + if let Some(x) = iterator.peek() { + if !"0123456789,; \t\n<>/*&|{}[]-+=~%^:!".contains(x.1) { + fill_other(source, &mut v, start, pos); + start = pos; + cont = false; + } + } + if cont { + continue; + } + } + fill_other(source, &mut v, start, pos); + match c { + ReservedChar::Quote | ReservedChar::DoubleQuote => { + if let Some(s) = get_string(source, &mut iterator, &mut pos, c) { + v.push(s); + } + } + ReservedChar::BackTick => { + if let Some(s) = get_backtick_string(source, &mut iterator, &mut pos) { + v.push(s); + } + } + ReservedChar::Slash + if v.last() + .unwrap_or(&Token::Other("")) + .eq_operation(Operation::Divide) => + { + v.pop(); + if let Some(s) = get_line_comment(source, &mut iterator, &mut pos) { + v.push(s); + } + } + ReservedChar::Slash + if iterator.peek().is_some() + && iterator.peek().unwrap().1 != '/' + && iterator.peek().unwrap().1 != '*' + && !first_useful(&v).unwrap_or(&Token::String("")).is_other() => + { + if let Some(r) = get_regex(source, &mut iterator, &mut pos, &v) { + v.push(r); + } else { + v.push(Token::Operation(Operation::Divide)); + } + } + ReservedChar::Star + if v.last() + .unwrap_or(&Token::Other("")) + .eq_operation(Operation::Divide) => + { + v.pop(); + v.push(get_comment(source, &mut iterator, &mut pos)); + } + ReservedChar::Pipe + if v.last() + .unwrap_or(&Token::Other("")) + .eq_char(ReservedChar::Pipe) => + { + v.pop(); + v.push(Token::Condition(Condition::Or)); + } + ReservedChar::Ampersand + if v.last() + .unwrap_or(&Token::Other("")) + .eq_char(ReservedChar::Ampersand) => + { + v.pop(); + v.push(Token::Condition(Condition::And)); + } + _ if handle_equal_sign(&mut v, c) => {} + _ => { + if let Ok(o) = Operation::try_from(c) { + v.push(Token::Operation(o)); + } else if let Ok(o) = Condition::try_from(c) { + v.push(Token::Condition(o)); + } else { + v.push(Token::Char(c)); + } + } + } + start = pos + 1; + } + } + Tokens(v) +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Tokens<'a>(pub Vec<Token<'a>>); + +macro_rules! tokens_writer { + ($self:ident, $w:ident) => { + let tokens = &$self.0; + for i in 0..tokens.len() { + if i > 0 + && tokens[i].requires_before() + && !tokens[i - 1].is_keyword() + && !tokens[i - 1].is_other() + && !tokens[i - 1].is_reserved_char() + && !tokens[i - 1].is_string() + { + write!($w, " ")?; + } + write!($w, "{}", tokens[i])?; + if let Some(c) = match tokens[i] { + Token::Keyword(_) | Token::Other(_) if i + 1 < tokens.len() => { + tokens[i + 1].get_required() + } + _ => None, + } { + write!($w, "{}", c)?; + } + } + }; +} + +impl<'a> Tokens<'a> { + pub(super) fn write<W: std::io::Write>(self, mut w: W) -> std::io::Result<()> { + tokens_writer!(self, w); + Ok(()) + } +} + +impl<'a> fmt::Display for Tokens<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + tokens_writer!(self, f); + Ok(()) + } +} + +impl<'a> Tokens<'a> { + #[must_use] + pub fn apply<F>(self, func: F) -> Tokens<'a> + where + F: Fn(Tokens<'a>) -> Tokens<'a>, + { + func(self) + } +} + +pub struct IntoIterTokens<'a> { + inner: Tokens<'a>, +} + +impl<'a> IntoIterator for Tokens<'a> { + type Item = (Token<'a>, Option<&'a Token<'a>>); + type IntoIter = IntoIterTokens<'a>; + + fn into_iter(mut self) -> Self::IntoIter { + self.0.reverse(); + IntoIterTokens { inner: self } + } +} + +impl<'a> Iterator for IntoIterTokens<'a> { + type Item = (Token<'a>, Option<&'a Token<'a>>); + + fn next(&mut self) -> Option<Self::Item> { + if self.inner.0.is_empty() { + None + } else { + let ret = self.inner.0.pop().expect("pop() failed"); + // FIXME once generic traits' types are stabilized, use a second + // lifetime instead of transmute! + Some((ret, unsafe { std::mem::transmute(self.inner.0.last()) })) + } + } +} + +impl<'a> std::ops::Deref for Tokens<'a> { + type Target = Vec<Token<'a>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a> From<Vec<Token<'a>>> for Tokens<'a> { + fn from(v: Vec<Token<'a>>) -> Self { + Tokens(v) + } +} + +impl<'a> From<&[Token<'a>]> for Tokens<'a> { + fn from(v: &[Token<'a>]) -> Self { + Tokens(v.to_vec()) + } +} + +#[test] +fn check_regex() { + let source = r#"var x = /"\.x/g;"#; + let expected_result = r#"var x=/"\.x/g"#; + assert_eq!(crate::js::minify(source).to_string(), expected_result); + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + v.0[3], + Token::Regex { + regex: "\"\\.x", + is_global: true, + is_interactive: false, + } + ); + + let source = r#"var x = /"\.x/gigigigig;var x = "hello";"#; + let expected_result = r#"var x=/"\.x/gi;var x="hello""#; + assert_eq!(crate::js::minify(source).to_string(), expected_result); + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + v.0[3], + Token::Regex { + regex: "\"\\.x", + is_global: true, + is_interactive: true, + } + ); +} + +#[test] +fn more_regex() { + let source = r#"var x = /"\.x\/a/i;"#; + let expected_result = r#"var x=/"\.x\/a/i"#; + assert_eq!(crate::js::minify(source).to_string(), expected_result); + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + v.0[3], + Token::Regex { + regex: "\"\\.x\\/a", + is_global: false, + is_interactive: true, + } + ); + + let source = r#"var x = /\\/i;"#; + let expected_result = r#"var x=/\\/i"#; + assert_eq!(crate::js::minify(source).to_string(), expected_result); + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + v.0[3], + Token::Regex { + regex: "\\\\", + is_global: false, + is_interactive: true, + } + ); +} + +#[test] +fn even_more_regex() { + let source = r#"var x = /a-z /;"#; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + v.0[3], + Token::Regex { + regex: "a-z ", + is_global: false, + is_interactive: false, + } + ); +} + +#[test] +fn not_regex_test() { + let source = "( x ) / 2; x / y;x /= y"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Char(ReservedChar::OpenParenthese), + Token::Other("x"), + Token::Char(ReservedChar::CloseParenthese), + Token::Operation(Operation::Divide), + Token::Number(2), + Token::Char(ReservedChar::SemiColon), + Token::Other("x"), + Token::Operation(Operation::Divide), + Token::Other("y"), + Token::Char(ReservedChar::SemiColon), + Token::Other("x"), + Token::Operation(Operation::DivideEqual), + Token::Other("y") + ] + ); + + let source = "let x = /x\ny/;"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::Let), + Token::Other("x"), + Token::Operation(Operation::Equal), + Token::Operation(Operation::Divide), + Token::Other("x"), + Token::Other("y"), + Token::Operation(Operation::Divide) + ] + ); +} + +#[test] +fn test_tokens_parsing() { + let source = "true = == 2.3 === 32"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::True), + Token::Operation(Operation::Equal), + Token::Condition(Condition::EqualTo), + Token::FloatingNumber("2.3"), + Token::Condition(Condition::SuperEqualTo), + Token::Number(32) + ] + ); +} + +#[test] +fn test_string_parsing() { + let source = "var x = 'hello people!'"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::Var), + Token::Other("x"), + Token::Operation(Operation::Equal), + Token::String("\'hello people!\'") + ] + ); +} + +#[test] +fn test_number_parsing() { + let source = "var x = .12; let y = 4.; var z = 12; .3 4. 'a' let u = 12.2"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::Var), + Token::Other("x"), + Token::Operation(Operation::Equal), + Token::FloatingNumber(".12"), + Token::Char(ReservedChar::SemiColon), + Token::Keyword(Keyword::Let), + Token::Other("y"), + Token::Operation(Operation::Equal), + Token::FloatingNumber("4."), + Token::Char(ReservedChar::SemiColon), + Token::Keyword(Keyword::Var), + Token::Other("z"), + Token::Operation(Operation::Equal), + Token::Number(12), + Token::Char(ReservedChar::SemiColon), + Token::FloatingNumber(".3"), + Token::FloatingNumber("4."), + Token::String("'a'"), + Token::Keyword(Keyword::Let), + Token::Other("u"), + Token::Operation(Operation::Equal), + Token::FloatingNumber("12.2") + ] + ); +} + +#[test] +fn test_number_parsing2() { + let source = "var x = 12.a;"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::Var), + Token::Other("x"), + Token::Operation(Operation::Equal), + Token::Number(12), + Token::Char(ReservedChar::Dot), + Token::Other("a") + ] + ); +} + +#[test] +fn tokens_spaces() { + let source = "t in e"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Other("t"), + Token::Keyword(Keyword::In), + Token::Other("e") + ] + ); +} + +#[test] +fn division_by_id() { + let source = "100/abc"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Number(100), + Token::Operation(Operation::Divide), + Token::Other("abc") + ] + ); +} + +#[test] +fn weird_regex() { + let source = "if (!/\\/(contact|legal)\\//.test(a)) {}"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Keyword(Keyword::If), + Token::Char(ReservedChar::OpenParenthese), + Token::Char(ReservedChar::ExclamationMark), + Token::Regex { + regex: "\\/(contact|legal)\\/", + is_global: false, + is_interactive: false + }, + Token::Char(ReservedChar::Dot), + Token::Other("test"), + Token::Char(ReservedChar::OpenParenthese), + Token::Other("a"), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::CloseParenthese), + Token::Char(ReservedChar::OpenCurlyBrace), + Token::Char(ReservedChar::CloseCurlyBrace), + ] + ); +} + +#[test] +fn test_regexes() { + let source = "/\\/(contact|legal)\\//.test"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Regex { + regex: "\\/(contact|legal)\\/", + is_global: false, + is_interactive: false + }, + Token::Char(ReservedChar::Dot), + Token::Other("test"), + ] + ); + + let source = "/\\*(contact|legal)/.test"; + + let v = tokenize(source).apply(crate::js::clean_tokens); + assert_eq!( + &v.0, + &[ + Token::Regex { + regex: "\\*(contact|legal)", + is_global: false, + is_interactive: false + }, + Token::Char(ReservedChar::Dot), + Token::Other("test"), + ] + ); +} + +#[test] +fn test_comments() { + let source = "/*(contact|legal)/.test"; + + let v = tokenize(source); + assert_eq!(&v.0, &[Token::Comment("(contact|legal)/.test"),],); + + let source = "/*(contact|legal)/.test*/ a"; + + let v = tokenize(source); + assert_eq!( + &v.0, + &[ + Token::Comment("(contact|legal)/.test"), + Token::Char(ReservedChar::Space), + Token::Other("a"), + ], + ); +} diff --git a/vendor/minifier/src/js/tools.rs b/vendor/minifier/src/js/tools.rs new file mode 100644 index 000000000..42d32aaab --- /dev/null +++ b/vendor/minifier/src/js/tools.rs @@ -0,0 +1,1156 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::{fmt, io}; + +use crate::js::token::{self, Keyword, ReservedChar, Token, Tokens}; +use crate::js::utils::{get_array, get_variable_name_and_value_positions, VariableNameGenerator}; + +use std::collections::{HashMap, HashSet}; + +/*#[derive(Debug, Clone, PartialEq, Eq)] +enum Elem<'a> { + Function(Function<'a>), + Block(Block<'a>), + Variable(Variable<'a>), + Condition(token::Condition), + Loop(Loop<'a>), + Operation(Operation<'a>), +} + +impl<'a> Elem<'a> { + fn is_condition(&self) -> bool { + match *self { + Elem::Condition(_) => true, + _ => false, + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum ConditionType { + If, + ElseIf, + Else, + Ternary, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Block<'a> { + elems: Vec<Elem<'a>>, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Argument<'a> { + name: &'a str, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Function<'a> { + name: Option<&'a str>, + args: Vec<Argument<'a>>, + block: Block<'a>, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Variable<'a> { + name: &'a str, + value: Option<&'a str>, +} + +/*struct Condition<'a> { + ty_: ConditionType, + condition: &'a str, + block: Block<'a>, +}*/ + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum LoopType { + Do, + For, + While, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Loop<'a> { + ty_: LoopType, + condition: Vec<Elem<'a>>, + block: Block<'a>, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +struct Operation<'a> { + content: &'a str, +} + +fn get_while_condition<'a>(tokens: &[token::Token<'a>], pos: &mut usize) -> Result<Vec<Elem<'a>>, String> { + let tmp = *pos; + *pos += 1; + if let Err(e) = match tokens.get(tmp) { + Some(token::Token::Char(token::ReservedChar::OpenParenthese)) => Ok(()), + Some(e) => Err(format!("Expected \"(\", found \"{:?}\"", e)), + None => Err("Expected \"(\", found nothing...".to_owned()), + } { + return Err(e); + } + let mut elems: Vec<Elem<'a>> = Vec::with_capacity(1); + + while let Some(e) = tokens.get(*pos) { + *pos += 1; + match e { + token::Token::Char(token::ReservedChar::CloseParenthese) => return Ok(elems), + token::Token::Condition(e) => { + if let Some(cond) = elems.last() { + if cond.is_condition() { + return Err(format!("\"{:?}\" cannot follow \"{:?}\"", e, cond)); + } + } + } + _ => {} + } + } + Err("Expected \")\", found nothing...".to_owned()) +} + +fn get_do<'a>(tokens: &[token::Token<'a>], pos: &mut usize) -> Result<Elem<'a>, String> { + let tmp = *pos; + *pos += 1; + let block = match tokens.get(tmp) { + Some(token::Token::Char(token::ReservedChar::OpenCurlyBrace)) => get_block(tokens, pos, true), + Some(e) => Err(format!("Expected \"{{\", found \"{:?}\"", e)), + None => Err("Expected \"{\", found nothing...".to_owned()), + }?; + let tmp = *pos; + *pos += 1; + let condition = match tokens.get(tmp) { + Some(token::Token::Keyword(token::Keyword::While)) => get_while_condition(tokens, pos), + Some(e) => Err(format!("Expected \"while\", found \"{:?}\"", e)), + None => Err("Expected \"while\", found nothing...".to_owned()), + }?; + let mut loop_ = Loop { + ty_: LoopType::Do, + condition: condition, + block, + }; + Ok(Elem::Loop(loop_)) +} + +fn get_block<'a>(tokens: &[token::Token<'a>], pos: &mut usize, + start_with_paren: bool) -> Result<Block<'a>, String> { + let mut block = Block { elems: Vec::with_capacity(2) }; + while let Some(e) = tokens.get(*pos) { + *pos += 1; + block.elems.push(match e { + token::Token::Keyword(token::Keyword::Do) => get_do(tokens, pos), + token::Token::Char(token::ReservedChar::CloseCurlyBrace) => { + if start_with_paren { + return Ok(block); + } + return Err("Unexpected \"}\"".to_owned()); + } + }?); + } + if !start_with_paren { + Ok(block) + } else { + Err("Expected \"}\" at the end of the block but didn't find one...".to_owned()) + } +} + +fn build_ast<'a>(v: &[token::Token<'a>]) -> Result<Elem<'a>, String> { + let mut pos = 0; + + match get_block(v, &mut pos, false) { + Ok(ast) => Ok(Elem::Block(ast)), + Err(e) => Err(e), + } +}*/ + +/// Minifies a given JS source code. +/// +/// # Example +/// +/// ```rust +/// use minifier::js::minify; +/// +/// let js = r#" +/// function forEach(data, func) { +/// for (var i = 0; i < data.length; ++i) { +/// func(data[i]); +/// } +/// }"#.into(); +/// let js_minified = minify(js); +/// assert_eq!( +/// &js_minified.to_string(), +/// "function forEach(data,func){for(var i=0;i<data.length;++i){func(data[i])}}", +/// ); +/// ``` +#[inline] +pub fn minify(source: &str) -> Minified<'_> { + Minified(token::tokenize(source).apply(crate::js::clean_tokens)) +} + +pub struct Minified<'a>(token::Tokens<'a>); + +impl<'a> Minified<'a> { + pub fn write<W: io::Write>(self, w: W) -> io::Result<()> { + self.0.write(w) + } +} + +impl<'a> fmt::Display for Minified<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// TODO: No scope handling or anything. Might be nice as a second step to add it... +fn get_variables_name<'a>( + tokens: &'a Tokens<'a>, +) -> (HashSet<&'a str>, HashMap<&'a str, (usize, usize)>) { + let mut ret = HashSet::new(); + let mut variables = HashMap::new(); + let mut pos = 0; + + while pos < tokens.len() { + if tokens[pos].is_keyword() || tokens[pos].is_other() { + if let Some((var_pos, Some(value_pos))) = + get_variable_name_and_value_positions(tokens, pos) + { + pos = value_pos; + if let Some(var_name) = tokens[var_pos].get_other() { + if !var_name.starts_with("r_") { + pos += 1; + continue; + } + ret.insert(var_name); + } + if let Some(s) = tokens[value_pos].get_string() { + variables.insert(s, (var_pos, value_pos)); + } + } + } + pos += 1; + } + (ret, variables) +} + +fn aggregate_strings_inner<'a, 'b: 'a>( + mut tokens: Tokens<'a>, + separation_token: Option<Token<'b>>, +) -> Tokens<'a> { + let mut new_vars = Vec::with_capacity(50); + let mut to_replace: Vec<(usize, usize)> = Vec::new(); + + for (var_name, positions) in { + let mut strs: HashMap<&Token<'_>, Vec<usize>> = HashMap::with_capacity(1000); + let mut validated: HashMap<&Token<'_>, String> = HashMap::with_capacity(100); + + let mut var_gen = VariableNameGenerator::new(Some("r_"), 2); + let mut next_name = var_gen.to_string(); + + let (all_variables, values) = get_variables_name(&tokens); + while all_variables.contains(&next_name.as_str()) { + var_gen.next(); + next_name = var_gen.to_string(); + } + + for pos in 0..tokens.len() { + let token = &tokens[pos]; + if let Some(str_token) = token.get_string() { + if let Some((var_pos, string_pos)) = values.get(&str_token) { + if pos != *string_pos { + to_replace.push((pos, *var_pos)); + } + continue; + } + let x = strs.entry(token).or_insert_with(|| Vec::with_capacity(1)); + x.push(pos); + if x.len() > 1 && validated.get(token).is_none() { + let len = str_token.len(); + // Computation here is simple, we declare new variables when creating this so + // the total of characters must be shorter than: + // `var r_aa=...;` -> 10 + `r_aa` -> 14 + if (x.len() + 2/* quotes */) * len + > next_name.len() + str_token.len() + 6 /* var _=_;*/ + x.len() * next_name.len() + { + validated.insert(token, next_name.clone()); + var_gen.next(); + next_name = var_gen.to_string(); + while all_variables.contains(&next_name.as_str()) { + var_gen.next(); + next_name = var_gen.to_string(); + } + } + } + } + } + let mut ret = Vec::with_capacity(validated.len()); + + // We need this macro to avoid having to sort the set when not testing the crate. + //#[cfg(test)] + macro_rules! inner_loop { + ($x:ident) => {{ + let mut $x = $x.into_iter().collect::<Vec<_>>(); + $x.sort_unstable_by(|a, b| a.1.cmp(&b.1)); + $x + }}; + } + /*#[cfg(not(test))] + macro_rules! inner_loop { + ($x:ident) => { + $x.into_iter() + } + }*/ + + for (token, var_name) in inner_loop!(validated) { + ret.push((var_name, strs.remove(&token).unwrap())); + var_gen.next(); + } + ret + } { + if new_vars.is_empty() { + new_vars.push(Token::Keyword(Keyword::Var)); + } else { + new_vars.push(Token::Char(ReservedChar::Comma)); + } + new_vars.push(Token::CreatedVarDecl(format!( + "{}={}", + var_name, tokens[positions[0]] + ))); + for pos in positions { + tokens.0[pos] = Token::CreatedVar(var_name.clone()); + } + } + if !new_vars.is_empty() { + new_vars.push(Token::Char(ReservedChar::SemiColon)); + } + for (to_replace_pos, variable_pos) in to_replace { + tokens.0[to_replace_pos] = tokens.0[variable_pos].clone(); + } + if let Some(token) = separation_token { + new_vars.push(token); + } + new_vars.append(&mut tokens.0); + Tokens(new_vars) +} + +/// Aggregate litteral strings. For instance, if the string litteral "Oh look over there!" +/// appears more than once, a variable will be created with this value and used everywhere the +/// string appears. Of course, this replacement is only performed when it allows to take +/// less space. +/// +/// # Example +/// +/// ```rust,no_run +/// extern crate minifier; +/// use minifier::js::{aggregate_strings, clean_tokens, simple_minify}; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(aggregate_strings) // This `apply` aggregates string litterals. +/// .apply(clean_tokens) // This one is used to remove useless chars. +/// .to_string(); // And we finally convert to string. +/// println!("result: {}", s); +/// } +/// ``` +#[inline] +pub fn aggregate_strings(tokens: Tokens<'_>) -> Tokens<'_> { + aggregate_strings_inner(tokens, None) +} + +/// Exactly like `aggregate_strings` except this one expects a separation token +/// to be passed. This token will be placed between the created variables for the +/// strings aggregation and the rest. +/// +/// # Example +/// +/// Let's add a backline between the created variables and the rest of the code: +/// +/// ```rust,no_run +/// extern crate minifier; +/// use minifier::js::{ +/// aggregate_strings_with_separation, +/// clean_tokens, +/// simple_minify, +/// Token, +/// ReservedChar, +/// }; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(|f| { +/// aggregate_strings_with_separation(f, Token::Char(ReservedChar::Backline)) +/// }) // We add a backline between the variable and the rest. +/// .apply(clean_tokens) // We clean the tokens. +/// .to_string(); // And we finally convert to string. +/// println!("result: {}", s); +/// } +/// ``` +#[inline] +pub fn aggregate_strings_with_separation<'a, 'b: 'a>( + tokens: Tokens<'a>, + separation_token: Token<'b>, +) -> Tokens<'a> { + aggregate_strings_inner(tokens, Some(separation_token)) +} + +fn aggregate_strings_into_array_inner<'a, 'b: 'a, T: Fn(&Tokens<'a>, usize) -> bool>( + mut tokens: Tokens<'a>, + array_name: &str, + separation_token: Option<Token<'b>>, + filter: T, +) -> Tokens<'a> { + let mut to_insert = Vec::with_capacity(100); + let mut to_replace = Vec::with_capacity(100); + + { + let mut to_ignore = HashSet::new(); + // key: the token string + // value: (position in the array, positions in the tokens list, need creation) + let mut strs: HashMap<&str, (usize, Vec<usize>, bool)> = HashMap::with_capacity(1000); + let (current_array_values, need_recreate, mut end_bracket) = + match get_array(&tokens, array_name) { + Some((s, p)) => (s, false, p), + None => (Vec::new(), true, 0), + }; + let mut validated: HashSet<&str> = HashSet::new(); + + let mut array_pos = 0; + for s in current_array_values.iter() { + if let Some(st) = tokens.0[*s].get_string() { + strs.insert(&st[1..st.len() - 1], (array_pos, vec![], false)); + array_pos += 1; + validated.insert(&st[1..st.len() - 1]); + to_ignore.insert(*s); + } + } + + let mut array_pos_str = array_pos.to_string(); + for pos in 0..tokens.len() { + if to_ignore.contains(&pos) { + continue; + } + let token = &tokens[pos]; + if let Some(str_token) = token.get_string() { + if !filter(&tokens, pos) { + continue; + } + let s = &str_token[1..str_token.len() - 1]; + let x = strs + .entry(s) + .or_insert_with(|| (0, Vec::with_capacity(1), true)); + x.1.push(pos); + if x.1.len() > 1 && !validated.contains(s) { + let len = s.len(); + if len * x.1.len() + > (array_name.len() + array_pos_str.len() + 2) * x.1.len() + + array_pos_str.len() + + 2 + { + validated.insert(&str_token[1..str_token.len() - 1]); + x.0 = array_pos; + array_pos += 1; + array_pos_str = array_pos.to_string(); + } + } + } + } + + // TODO: + // 1. Sort strings by length (the smallest should take the smallest numbers + // for bigger gains). + // 2. Compute "score" for all strings of the same length and sort the strings + // of the same length with this score. + // 3. Loop again over strings and remove those who shouldn't be there anymore. + // 4. Repeat. + // + // ALTERNATIVE: + // + // Compute the score based on: + // current number of digits * str length * str occurence + // + // ^ This second solution should bring even better results. + // + // ALSO: if an array with such strings already exists, it'd be worth it to recompute + // everything again. + let mut validated = validated.iter().map(|v| (strs[v].0, v)).collect::<Vec<_>>(); + validated.sort_unstable_by(|(p1, _), (p2, _)| p2.cmp(p1)); + + if need_recreate && !validated.is_empty() { + if let Some(token) = separation_token { + to_insert.push((0, token)); + } + to_insert.push((0, Token::Char(ReservedChar::SemiColon))); + to_insert.push((0, Token::Char(ReservedChar::CloseBracket))); + to_insert.push((0, Token::Char(ReservedChar::OpenBracket))); + to_insert.push((0, Token::CreatedVarDecl(format!("var {}=", array_name)))); + + end_bracket = 2; + } + + let mut iter = validated.iter().peekable(); + while let Some((array_pos, s)) = iter.next() { + let (_, ref tokens_pos, create_array_entry) = strs[*s]; + let array_index = Token::CreatedVar(format!("{}[{}]", array_name, array_pos)); + for token in tokens_pos.iter() { + to_replace.push((*token, array_index.clone())); + } + if !create_array_entry { + continue; + } + to_insert.push((end_bracket, Token::CreatedVar(format!("\"{}\"", *s)))); + if iter.peek().is_none() && current_array_values.is_empty() { + continue; + } + to_insert.push((end_bracket, Token::Char(ReservedChar::Comma))); + } + } + for (pos, rep) in to_replace.into_iter() { + tokens.0[pos] = rep; + } + for (pos, rep) in to_insert.into_iter() { + tokens.0.insert(pos, rep); + } + tokens +} + +/// Exactly like `aggregate_strings_into_array` except this one expects a separation token +/// to be passed. This token will be placed between the created array for the +/// strings aggregation and the rest. +/// +/// # Example +/// +/// Let's add a backline between the created variables and the rest of the code: +/// +/// ```rust,no_run +/// extern crate minifier; +/// use minifier::js::{ +/// aggregate_strings_into_array_with_separation, +/// clean_tokens, +/// simple_minify, +/// Token, +/// ReservedChar, +/// }; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(|f| { +/// aggregate_strings_into_array_with_separation(f, "R", Token::Char(ReservedChar::Backline)) +/// }) // We add a backline between the variable and the rest. +/// .apply(clean_tokens) // We clean the tokens. +/// .to_string(); // And we finally convert to string. +/// println!("result: {}", s); +/// } +/// ``` +#[inline] +pub fn aggregate_strings_into_array_with_separation<'a, 'b: 'a>( + tokens: Tokens<'a>, + array_name: &str, + separation_token: Token<'b>, +) -> Tokens<'a> { + aggregate_strings_into_array_inner(tokens, array_name, Some(separation_token), |_, _| true) +} + +/// Same as [`aggregate_strings_into_array_with_separation`] except it allows certain strings to +/// not be aggregated thanks to the `filter` parameter. If it returns `false`, then the string will +/// be ignored. +#[inline] +pub fn aggregate_strings_into_array_with_separation_filter<'a, 'b: 'a, T>( + tokens: Tokens<'a>, + array_name: &str, + separation_token: Token<'b>, + filter: T, +) -> Tokens<'a> +where + T: Fn(&Tokens<'a>, usize) -> bool, +{ + aggregate_strings_into_array_inner(tokens, array_name, Some(separation_token), filter) +} + +/// Aggregate litteral strings. For instance, if the string litteral "Oh look over there!" +/// appears more than once, it will be added to the generated array and used everywhere the +/// string appears. Of course, this replacement is only performed when it allows to take +/// less space. +/// +/// # Example +/// +/// ```rust,no_run +/// extern crate minifier; +/// use minifier::js::{aggregate_strings_into_array, clean_tokens, simple_minify}; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(|f| aggregate_strings_into_array(f, "R")) // This `apply` aggregates string litterals. +/// .apply(clean_tokens) // This one is used to remove useless chars. +/// .to_string(); // And we finally convert to string. +/// println!("result: {}", s); +/// } +/// ``` +#[inline] +pub fn aggregate_strings_into_array<'a>(tokens: Tokens<'a>, array_name: &str) -> Tokens<'a> { + aggregate_strings_into_array_inner(tokens, array_name, None, |_, _| true) +} + +/// Same as [`aggregate_strings_into_array`] except it allows certain strings to not be aggregated +/// thanks to the `filter` parameter. If it returns `false`, then the string will be ignored. +#[inline] +pub fn aggregate_strings_into_array_filter<'a, T>( + tokens: Tokens<'a>, + array_name: &str, + filter: T, +) -> Tokens<'a> +where + T: Fn(&Tokens<'a>, usize) -> bool, +{ + aggregate_strings_into_array_inner(tokens, array_name, None, filter) +} + +/// Simple function to get the untouched token list. Useful in case you want to perform some +/// actions directly on it. +/// +/// # Example +/// +/// ```rust,no_run +/// extern crate minifier; +/// use minifier::js::simple_minify; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); +/// println!("result: {:?}", s); // We now have the tokens list. +/// } +/// ``` +#[inline] +pub fn simple_minify(source: &str) -> Tokens<'_> { + token::tokenize(source) +} + +#[test] +fn aggregate_strings_in_array() { + let source = r#"var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"a nice string\",\"cake!\"];var x=[R[0],R[0],\ + \"another nice string\",R[1],R[1],R[0],R[1],R[1],R[1]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| aggregate_strings_into_array(c, "R")) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"a nice string\",\"cake!\"];\nvar x=[R[0],R[0],\ + \"another nice string\",R[1],R[1],R[0],R[1],R[1],R[1]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| { + aggregate_strings_into_array_with_separation( + c, + "R", + Token::Char(ReservedChar::Backline), + ) + }) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var x = ["a nice string", "a nice string", "another nice string", "another nice string", "another nice string", "another nice string","cake!","cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"a nice string\",\"another nice string\",\"cake!\"];\n\ + var x=[R[0],R[0],R[1],R[1],R[1],R[1],R[2],R[2],R[0],R[2],\ + R[2],R[2]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| { + aggregate_strings_into_array_with_separation( + c, + "R", + Token::Char(ReservedChar::Backline), + ) + }) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn aggregate_strings_in_array_filter() { + let source = r#"var searchIndex = {};searchIndex['duplicate_paths'] = {'aaaaaaaa': 'bbbbbbbb', 'bbbbbbbb': 'aaaaaaaa', 'duplicate_paths': 'aaaaaaaa'};"#; + let expected_result = "var R=[\"bbbbbbbb\",\"aaaaaaaa\"];\nvar searchIndex={};searchIndex['duplicate_paths']={R[1]:R[0],R[0]:R[1],'duplicate_paths':R[1]}"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| { + aggregate_strings_into_array_with_separation_filter( + c, + "R", + Token::Char(ReservedChar::Backline), + |tokens, pos| { + pos < 2 + || !tokens[pos - 1].eq_char(ReservedChar::OpenBracket) + || tokens[pos - 2].get_other() != Some("searchIndex") + }, + ) + }) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var searchIndex = {};searchIndex['duplicate_paths'] = {'aaaaaaaa': 'bbbbbbbb', 'bbbbbbbb': 'aaaaaaaa', 'duplicate_paths': 'aaaaaaaa', 'x': 'duplicate_paths'};"#; + let expected_result = "var R=[\"bbbbbbbb\",\"aaaaaaaa\",\"duplicate_paths\"];\nvar searchIndex={};searchIndex['duplicate_paths']={R[1]:R[0],R[0]:R[1],R[2]:R[1],'x':R[2]}"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| { + aggregate_strings_into_array_with_separation_filter( + c, + "R", + Token::Char(ReservedChar::Backline), + |tokens, pos| { + pos < 2 + || !tokens[pos - 1].eq_char(ReservedChar::OpenBracket) + || tokens[pos - 2].get_other() != Some("searchIndex") + }, + ) + }) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn aggregate_strings_in_array_existing() { + let source = r#"var R=[];var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"a nice string\",\"cake!\"];var x=[R[0],R[0],\ + \"another nice string\",R[1],R[1],R[0],R[1],R[1],R[1]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| aggregate_strings_into_array(c, "R")) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var R=["a nice string"];var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"a nice string\",\"cake!\"];var x=[R[0],R[0],\ + \"another nice string\",R[1],R[1],R[0],R[1],R[1],R[1]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| aggregate_strings_into_array(c, "R")) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var y = 12;var R=["a nice string"];var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var y=12;var R=[\"a nice string\",\"cake!\"];var x=[R[0],R[0],\ + \"another nice string\",R[1],R[1],R[0],R[1],R[1],R[1]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| aggregate_strings_into_array(c, "R")) + .to_string(); + assert_eq!(result, expected_result); + + let source = r#"var R=["osef1", "o2", "damn"]; + var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var R=[\"osef1\",\"o2\",\"damn\",\"a nice string\",\"cake!\"];\ + var x=[R[3],R[3],\"another nice string\",R[4],R[4],R[3],R[4],R[4],R[4]]"; + + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|c| aggregate_strings_into_array(c, "R")) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn string_duplicates() { + let source = r#"var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var r_aa=\"a nice string\",r_ba=\"cake!\";var x=[r_aa,r_aa,\ + \"another nice string\",r_ba,r_ba,r_aa,r_ba,r_ba,r_ba]"; + + let result = simple_minify(source) + .apply(aggregate_strings) + .apply(crate::js::clean_tokens) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn already_existing_var() { + let source = r#"var r_aa = "a nice string"; var x = ["a nice string", "a nice string", + "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var r_ba=\"cake!\";var r_aa=\"a nice string\";var x=[r_aa,r_aa,\ + \"another nice string\",r_ba,r_ba,r_aa,r_ba,r_ba,r_ba]"; + + let result = simple_minify(source) + .apply(aggregate_strings) + .apply(crate::js::clean_tokens) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn string_duplicates_variables_already_exist() { + let source = r#"var r_aa=1;var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var r_ba=\"a nice string\",r_ca=\"cake!\";\ + var r_aa=1;var x=[r_ba,r_ba,\ + \"another nice string\",r_ca,r_ca,r_ba,r_ca,r_ca,r_ca]"; + + let result = simple_minify(source) + .apply(aggregate_strings) + .apply(crate::js::clean_tokens) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn string_duplicates_with_separator() { + use self::token::ReservedChar; + + let source = r#"var x = ["a nice string", "a nice string", "another nice string", "cake!", + "cake!", "a nice string", "cake!", "cake!", "cake!"];"#; + let expected_result = "var r_aa=\"a nice string\",r_ba=\"cake!\";\nvar x=[r_aa,r_aa,\ + \"another nice string\",r_ba,r_ba,r_aa,r_ba,r_ba,r_ba]"; + let result = simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|f| aggregate_strings_with_separation(f, Token::Char(ReservedChar::Backline))) + .to_string(); + assert_eq!(result, expected_result); +} + +#[test] +fn clean_except() { + use self::token::ReservedChar; + + let source = r#"var x = [1, 2, 3]; +var y = "salut"; +var z = "ok!";"#; + let expected = r#"var x=[1,2,3]; +var y="salut"; +var z="ok!""#; + + let result = simple_minify(source) + .apply(|f| { + crate::js::clean_tokens_except(f, |c| c.get_char() != Some(ReservedChar::Backline)) + }) + .to_string(); + assert_eq!(result, expected); +} + +#[test] +fn clean_except2() { + use self::token::ReservedChar; + + let source = "let x = [ 1, 2, \t3];"; + let expected = "let x = [ 1, 2, 3];"; + + let result = simple_minify(source) + .apply(|f| { + crate::js::clean_tokens_except(f, |c| { + c.get_char() != Some(ReservedChar::Space) + && c.get_char() != Some(ReservedChar::SemiColon) + }) + }) + .to_string(); + assert_eq!(result, expected); +} + +#[test] +fn clean_except3() { + use self::token::ReservedChar; + + let source = "let x = [ 1, 2, \t3];"; + let expected = "let x=[1,2,\t3];"; + + let result = simple_minify(source) + .apply(|f| { + crate::js::clean_tokens_except(f, |c| { + c.get_char() != Some(ReservedChar::Tab) + && c.get_char() != Some(ReservedChar::SemiColon) + }) + }) + .to_string(); + assert_eq!(result, expected); +} + +#[test] +fn name_generator() { + let s = std::iter::repeat('a').take(36).collect::<String>(); + // We need to generate enough long strings to reach the point that the name generator + // generates names with 3 characters. + let s = std::iter::repeat(s) + .take(20000) + .enumerate() + .map(|(pos, s)| format!("{}{}", s, pos)) + .collect::<Vec<_>>(); + let source = format!( + "var x = [{}];", + s.iter() + .map(|s| format!("\"{0}\",\"{0}\"", s)) + .collect::<Vec<_>>() + .join(",") + ); + let result = simple_minify(&source) + .apply(crate::js::clean_tokens) + .apply(aggregate_strings) + .to_string(); + assert!(result.find(",r_aaa=").is_some()); + assert!(result.find(",r_ab=").unwrap() < result.find(",r_ba=").unwrap()); +} + +#[test] +fn simple_quote() { + let source = r#"var x = "\\";"#; + let expected_result = r#"var x="\\""#; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn js_minify_test() { + let source = r##" +var foo = "something"; + +var another_var = 2348323; + +// who doesn't like comments? +/* and even longer comments? + +like +on +a +lot +of +lines! + +Fun! +*/ +function far_away(x, y) { + var x2 = x + 4; + return x * x2 + y; +} + +// this call is useless +far_away(another_var, 12); +// this call is useless too +far_away(another_var, 12); +"##; + + let expected_result = "var foo=\"something\";var another_var=2348323;function far_away(x,y){\ + var x2=x+4;return x*x2+y}far_away(another_var,12);far_away(another_var,\ + 12)"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn another_js_test() { + let source = r#" +/*! let's keep this license + * + * because everyone likes licenses! + * + * right? + */ + +function forEach(data, func) { + for (var i = 0; i < data.length; ++i) { + func(data[i]); + } +} + +forEach([0, 1, 2, 3, 4, + 5, 6, 7, 8, 9], function (x) { + console.log(x); + }); +// I think we're done? +console.log('done!'); +"#; + + let expected_result = r#"/*! let's keep this license + * + * because everyone likes licenses! + * + * right? + */function forEach(data,func){for(var i=0;i<data.length;++i){func(data[i])}}forEach([0,1,2,3,4,5,6,7,8,9],function(x){console.log(x)});console.log('done!')"#; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn comment_issue() { + let source = r#" +search_input.onchange = function(e) { + // Do NOT e.preventDefault() here. It will prevent pasting. + clearTimeout(searchTimeout); + // zero-timeout necessary here because at the time of event handler execution the + // pasted content is not in the input field yet. Shouldn’t make any difference for + // change, though. + setTimeout(search, 0); +}; +"#; + let expected_result = "search_input.onchange=function(e){clearTimeout(searchTimeout);\ + setTimeout(search,0)}"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn missing_whitespace() { + let source = r#" +for (var entry in results) { + if (results.hasOwnProperty(entry)) { + ar.push(results[entry]); + } +}"#; + let expected_result = "for(var entry in results){if(results.hasOwnProperty(entry)){\ + ar.push(results[entry])}}"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn weird_regex_issue() { + let source = r#" +val = val.replace(/\_/g, ""); + +var valGenerics = extractGenerics(val);"#; + let expected_result = "val=val.replace(/\\_/g,\"\");var valGenerics=extractGenerics(val)"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn keep_space() { + fn inner_double_checks(source: &str, expected: &str) { + assert_eq!(minify(source).to_string(), expected); + let s = minify(source); + let mut out: Vec<u8> = Vec::new(); + s.write(&mut out).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), expected); + } + + inner_double_checks("return 12;return x;", "return 12;return x"); + inner_double_checks("t in e", "t in e"); + inner_double_checks("t + 1 in e", "t+1 in e"); + inner_double_checks("t - 1 in e", "t-1 in e"); + inner_double_checks("'a' in e", "'a'in e"); + inner_double_checks("/a/g in e", "/a/g in e"); + inner_double_checks("/a/i in e", "/a/i in e"); + + inner_double_checks("t instanceof e", "t instanceof e"); + inner_double_checks("t + 1 instanceof e", "t+1 instanceof e"); + inner_double_checks("t - 1 instanceof e", "t-1 instanceof e"); + inner_double_checks("'a' instanceof e", "'a'instanceof e"); + inner_double_checks("/a/g instanceof e", "/a/g instanceof e"); + inner_double_checks("/a/i instanceof e", "/a/i instanceof e"); + + inner_double_checks("function foo() { let x = 12; }", "function foo(){let x=12}"); + inner_double_checks( + r#""use strict"; + +(function() { + const itemTypes = [ + "mod", + "externcrate", + "import", + "struct", + ]; + const TY_PRIMITIVE = itemTypes; + function hasOwnPropertyRustdoc() {} +})();"#, + "\"use strict\";(function(){const itemTypes=[\"mod\",\"externcrate\",\"import\",\"struct\"\ + ,];const TY_PRIMITIVE=itemTypes;function hasOwnPropertyRustdoc(){}})()", + ); +} + +#[test] +fn test_remove_extra_whitespace_before_typeof() { + let source = "var x = typeof 'foo';var y = typeof x;case typeof 'foo': 'bla'"; + + let expected_result = "var x=typeof'foo';var y=typeof x;case typeof'foo':'bla'"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn test_remove_extra_whitespace_before_in() { + let source = r#"if ("key" in ev && typeof ev) { return true; } +if (x in ev && typeof ev) { return true; } +if (true in ev) { return true; }"#; + + let expected_result = r#"if("key"in ev&&typeof ev){return true}if(x in ev&&typeof ev){return true}if(true in ev){return true}"#; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn test_remove_extra_whitespace_before_operator() { + let source = "( x ) / 2; x / y;x /= y"; + + let expected_result = "(x)/2;x/y;x/=y"; + assert_eq!(minify(source).to_string(), expected_result); +} + +#[test] +fn check_regex_syntax() { + let source = "console.log(/MSIE|Trident|Edge/.test(window.navigator.userAgent));"; + let expected = "console.log(/MSIE|Trident|Edge/.test(window.navigator.userAgent))"; + assert_eq!(minify(source).to_string(), expected); +} + +#[test] +fn minify_minified() { + let source = "function (i, n, a) { i[n].type.replace(/ *;(.|\\s)*/,\"\")===t&&a.push(i[n].MathJax.elementJax);return a}"; + let expected = "function(i,n,a){i[n].type.replace(/ *;(.|\\s)*/,\"\")===t&&a.push(i[n].MathJax.elementJax);return a}"; + assert_eq!(minify(source).to_string(), expected); +} + +#[test] +fn check_string() { + let source = r###" + const a = 123; + const b = "123"; + const c = `the number is ${a} <-- note the spaces here`; + const d = ` ${a} ${b} `; + "###; + let expected = "const a=123;const b=\"123\";const c=`the number is ${a} <-- note the spaces \ + here`;const d=` ${a} ${b} `"; + assert_eq!(minify(source).to_string(), expected); +} + +// TODO: requires AST to fix this issue! +/*#[test] +fn no_semi_colon() { + let source = r#" +console.log(1) +console.log(2) +var x = 12; +"#; + let expected_result = r#"console.log(1);console.log(2);var x=12;"#; + assert_eq!(minify(source).to_string(), expected_result); +}*/ + +// TODO: requires AST to fix this issue! +/*#[test] +fn correct_replace_for_backline() { + let source = r#" +function foo() { + return + 12; +} +"#; + let expected_result = r#"function foo(){return 12;}"#; + assert_eq!(minify(source).to_string(), expected_result); +}*/ diff --git a/vendor/minifier/src/js/utils.rs b/vendor/minifier/src/js/utils.rs new file mode 100644 index 000000000..db765e804 --- /dev/null +++ b/vendor/minifier/src/js/utils.rs @@ -0,0 +1,575 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::js::token::{Keyword, Operation, ReservedChar, Token, Tokens}; +use std::vec::IntoIter; + +pub(crate) struct VariableNameGenerator<'a> { + letter: char, + lower: Option<Box<VariableNameGenerator<'a>>>, + prepend: Option<&'a str>, +} + +impl<'a> VariableNameGenerator<'a> { + pub(crate) fn new(prepend: Option<&'a str>, nb_letter: usize) -> VariableNameGenerator<'a> { + if nb_letter > 1 { + VariableNameGenerator { + letter: 'a', + lower: Some(Box::new(VariableNameGenerator::new(None, nb_letter - 1))), + prepend, + } + } else { + VariableNameGenerator { + letter: 'a', + lower: None, + prepend, + } + } + } + + pub(crate) fn next(&mut self) { + self.incr_letters(); + } + + #[allow(clippy::inherent_to_string)] + pub(crate) fn to_string(&self) -> String { + if let Some(ref lower) = self.lower { + format!( + "{}{}{}", + self.prepend.unwrap_or(""), + self.letter, + lower.to_string() + ) + } else { + format!("{}{}", self.prepend.unwrap_or(""), self.letter) + } + } + + #[allow(dead_code)] + pub(crate) fn len(&self) -> usize { + let first = match self.prepend { + Some(s) => s.len(), + None => 0, + } + 1; + first + + match self.lower { + Some(ref s) => s.len(), + None => 0, + } + } + + pub(crate) fn incr_letters(&mut self) { + let max = [('z', 'A'), ('Z', '0'), ('9', 'a')]; + + for (m, next) in &max { + if self.letter == *m { + self.letter = *next; + if self.letter == 'a' { + if let Some(ref mut lower) = self.lower { + lower.incr_letters(); + } else { + self.lower = Some(Box::new(VariableNameGenerator::new(None, 1))); + } + } + return; + } + } + self.letter = ((self.letter as u8) + 1) as char; + } +} + +/// Replace given tokens with others. +/// +/// # Example +/// +/// ```rust +/// extern crate minifier; +/// use minifier::js::{Keyword, Token, replace_tokens_with, simple_minify}; +/// +/// fn main() { +/// let js = r#" +/// function replaceByNull(data, func) { +/// for (var i = 0; i < data.length; ++i) { +/// if func(data[i]) { +/// data[i] = null; +/// } +/// } +/// } +/// }"#.into(); +/// let js_minified = simple_minify(js) +/// .apply(|f| { +/// replace_tokens_with(f, |t| { +/// if *t == Token::Keyword(Keyword::Null) { +/// Some(Token::Other("N")) +/// } else { +/// None +/// } +/// }) +/// }); +/// println!("{}", js_minified.to_string()); +/// } +/// ``` +/// +/// The previous code will have all its `null` keywords replaced with `N`. In such cases, +/// don't forget to include the definition of `N` in the returned minified javascript: +/// +/// ```js +/// var N = null; +/// ``` +#[inline] +pub fn replace_tokens_with<'a, 'b: 'a, F: Fn(&Token<'a>) -> Option<Token<'b>>>( + mut tokens: Tokens<'a>, + callback: F, +) -> Tokens<'a> { + for token in tokens.0.iter_mut() { + if let Some(t) = callback(token) { + *token = t; + } + } + tokens +} + +/// Replace a given token with another. +#[inline] +pub fn replace_token_with<'a, 'b: 'a, F: Fn(&Token<'a>) -> Option<Token<'b>>>( + token: Token<'a>, + callback: &F, +) -> Token<'a> { + if let Some(t) = callback(&token) { + t + } else { + token + } +} + +/// When looping over `Tokens`, if you encounter `Keyword::Var`, `Keyword::Let` or +/// `Token::Other` using this function will allow you to get the variable name's +/// position and the variable value's position (if any). +/// +/// ## Note +/// +/// It'll return the value only if there is an `Operation::Equal` found. +/// +/// # Examples +/// +/// ``` +/// extern crate minifier; +/// use minifier::js::{Keyword, get_variable_name_and_value_positions, simple_minify}; +/// +/// fn main() { +/// let source = r#"var x = 1;var z;var y = "2";"#; +/// let mut result = Vec::new(); +/// +/// let tokens = simple_minify(source); +/// +/// for pos in 0..tokens.len() { +/// match tokens[pos].get_keyword() { +/// Some(k) if k == Keyword::Let || k == Keyword::Var => { +/// if let Some(x) = get_variable_name_and_value_positions(&tokens, pos) { +/// result.push(x); +/// } +/// } +/// _ => {} +/// } +/// } +/// assert_eq!(result, vec![(2, Some(6)), (10, None), (14, Some(22))]); +/// } +/// ``` +pub fn get_variable_name_and_value_positions<'a>( + tokens: &'a Tokens<'a>, + pos: usize, +) -> Option<(usize, Option<usize>)> { + if pos >= tokens.len() { + return None; + } + let mut tmp = pos; + match tokens[pos] { + Token::Keyword(Keyword::Let) | Token::Keyword(Keyword::Var) => { + tmp += 1; + } + Token::Other(_) if pos > 0 => { + let mut pos = pos - 1; + while pos > 0 { + if tokens[pos].is_comment() || tokens[pos].is_white_character() { + pos -= 1; + } else if tokens[pos] == Token::Char(ReservedChar::Comma) + || tokens[pos] == Token::Keyword(Keyword::Let) + || tokens[pos] == Token::Keyword(Keyword::Var) + { + break; + } else { + return None; + } + } + } + _ => return None, + } + while tmp < tokens.len() { + if tokens[tmp].is_other() { + let mut tmp2 = tmp + 1; + while tmp2 < tokens.len() { + if tokens[tmp2] == Token::Operation(Operation::Equal) { + tmp2 += 1; + while tmp2 < tokens.len() { + let token = &tokens[tmp2]; + if token.is_string() + || token.is_other() + || token.is_regex() + || token.is_number() + || token.is_floating_number() + { + return Some((tmp, Some(tmp2))); + } else if !tokens[tmp2].is_comment() && !tokens[tmp2].is_white_character() { + break; + } + tmp2 += 1; + } + break; + } else if matches!( + tokens[tmp2].get_char(), + Some(ReservedChar::Comma) | Some(ReservedChar::SemiColon) + ) { + return Some((tmp, None)); + } else if !(tokens[tmp2].is_comment() + || tokens[tmp2].is_white_character() + && tokens[tmp2].get_char() != Some(ReservedChar::Backline)) + { + break; + } + tmp2 += 1; + } + } else { + // We don't care about syntax errors. + } + tmp += 1; + } + None +} + +#[inline] +fn get_next<'a>(it: &mut IntoIter<Token<'a>>) -> Option<Token<'a>> { + for t in it { + if t.is_comment() || t.is_white_character() { + continue; + } + return Some(t); + } + None +} + +/// Convenient function used to clean useless tokens in a token list. +/// +/// # Example +/// +/// ```rust,no_run +/// extern crate minifier; +/// +/// use minifier::js::{clean_tokens, simple_minify}; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(clean_tokens); // We now have a cleaned token list! +/// println!("result: {:?}", s); +/// } +/// ``` +pub fn clean_tokens(tokens: Tokens<'_>) -> Tokens<'_> { + let mut v = Vec::with_capacity(tokens.len() / 3 * 2); + let mut it = tokens.0.into_iter(); + + loop { + let token = get_next(&mut it); + if token.is_none() { + break; + } + let token = token.unwrap(); + if token.is_white_character() { + continue; + } else if token.get_char() == Some(ReservedChar::SemiColon) { + if v.is_empty() { + continue; + } + if let Some(next) = get_next(&mut it) { + if next != Token::Char(ReservedChar::CloseCurlyBrace) { + v.push(token); + } + v.push(next); + } + continue; + } + v.push(token); + } + v.into() +} + +/// Returns true if the token is a "useful" one (so not a comment or a "useless" +/// character). +pub fn clean_token(token: &Token<'_>, next_token: &Option<&Token<'_>>) -> bool { + !token.is_comment() && { + if let Some(x) = token.get_char() { + !x.is_white_character() + && (x != ReservedChar::SemiColon + || *next_token != Some(&Token::Char(ReservedChar::CloseCurlyBrace))) + } else { + true + } + } +} + +#[inline] +fn get_next_except<'a, F: Fn(&Token<'a>) -> bool>( + it: &mut IntoIter<Token<'a>>, + f: &F, +) -> Option<Token<'a>> { + for t in it { + if (t.is_comment() || t.is_white_character()) && f(&t) { + continue; + } + return Some(t); + } + None +} + +/// Same as `clean_tokens` except that if a token is considered as not desired, +/// the callback is called. If the callback returns `false` as well, it will +/// be removed. +/// +/// # Example +/// +/// ```rust,no_run +/// extern crate minifier; +/// +/// use minifier::js::{clean_tokens_except, simple_minify, ReservedChar}; +/// use std::fs; +/// +/// fn main() { +/// let content = fs::read("some_file.js").expect("file not found"); +/// let source = String::from_utf8_lossy(&content); +/// let s = simple_minify(&source); // First we get the tokens list. +/// let s = s.apply(|f| { +/// clean_tokens_except(f, |c| { +/// c.get_char() != Some(ReservedChar::Backline) +/// }) +/// }); // We now have a cleaned token list which kept backlines! +/// println!("result: {:?}", s); +/// } +/// ``` +pub fn clean_tokens_except<'a, F: Fn(&Token<'a>) -> bool>(tokens: Tokens<'a>, f: F) -> Tokens<'a> { + let mut v = Vec::with_capacity(tokens.len() / 3 * 2); + let mut it = tokens.0.into_iter(); + + loop { + let token = get_next_except(&mut it, &f); + if token.is_none() { + break; + } + let token = token.unwrap(); + if token.is_white_character() { + if f(&token) { + continue; + } + } else if token.get_char() == Some(ReservedChar::SemiColon) { + if v.is_empty() { + if !f(&token) { + v.push(token); + } + continue; + } + if let Some(next) = get_next_except(&mut it, &f) { + if next != Token::Char(ReservedChar::CloseCurlyBrace) || !f(&token) { + v.push(token); + } + v.push(next); + } else if !f(&token) { + v.push(token); + } + continue; + } + v.push(token); + } + v.into() +} + +/// Returns true if the token is a "useful" one (so not a comment or a "useless" +/// character). +#[inline] +pub fn clean_token_except<'a, F: Fn(&Token<'a>) -> bool>( + token: &Token<'a>, + next_token: &Option<&Token<'_>>, + f: &F, +) -> bool { + if !clean_token(token, next_token) { + !f(token) + } else { + true + } +} + +pub(crate) fn get_array<'a>( + tokens: &'a Tokens<'a>, + array_name: &str, +) -> Option<(Vec<usize>, usize)> { + let mut ret = Vec::new(); + + let mut looking_for_var = false; + let mut looking_for_equal = false; + let mut looking_for_array_start = false; + let mut getting_values = false; + + for pos in 0..tokens.len() { + if looking_for_var { + match tokens[pos] { + Token::Other(s) => { + looking_for_var = false; + if s == array_name { + looking_for_equal = true; + } + } + ref s => { + looking_for_var = s.is_comment() || s.is_white_character(); + } + } + } else if looking_for_equal { + match tokens[pos] { + Token::Operation(Operation::Equal) => { + looking_for_equal = false; + looking_for_array_start = true; + } + ref s => { + looking_for_equal = s.is_comment() || s.is_white_character(); + } + } + } else if looking_for_array_start { + match tokens[pos] { + Token::Char(ReservedChar::OpenBracket) => { + looking_for_array_start = false; + getting_values = true; + } + ref s => { + looking_for_array_start = s.is_comment() || s.is_white_character(); + } + } + } else if getting_values { + match &tokens[pos] { + Token::Char(ReservedChar::CloseBracket) => { + return Some((ret, pos)); + } + s if s.is_comment() || s.is_white_character() => {} + _ => { + ret.push(pos); + } + } + } else { + match tokens[pos] { + Token::Keyword(Keyword::Let) | Token::Keyword(Keyword::Var) => { + looking_for_var = true; + } + _ => {} + } + } + } + None +} + +#[test] +fn check_get_array() { + let source = r#"var x = [ ]; var y = ['hello', + 12]; var z = []; var w = 12;"#; + + let tokens = crate::js::token::tokenize(source); + + let ar = get_array(&tokens, "x"); + assert!(ar.is_some()); + assert_eq!(ar.unwrap().1, 9); + + let ar = get_array(&tokens, "y"); + assert!(ar.is_some()); + assert_eq!(ar.unwrap().1, 27); + + let ar = get_array(&tokens, "z"); + assert!(ar.is_some()); + assert_eq!(ar.unwrap().1, 37); + + let ar = get_array(&tokens, "w"); + assert!(ar.is_none()); + + let ar = get_array(&tokens, "W"); + assert!(ar.is_none()); +} + +#[test] +fn check_get_variable_name_and_value_positions() { + let source = r#"var x = 1;var y = "2",we=4;"#; + let mut result = Vec::new(); + let mut pos = 0; + + let tokens = crate::js::token::tokenize(source); + + while pos < tokens.len() { + if let Some(x) = get_variable_name_and_value_positions(&tokens, pos) { + result.push(x); + pos = x.0; + } + pos += 1; + } + assert_eq!(result, vec![(2, Some(6)), (10, Some(18)), (20, Some(22))]); + + let mut result = Vec::new(); + let tokens = crate::js::clean_tokens(tokens); + pos = 0; + + while pos < tokens.len() { + if let Some(x) = get_variable_name_and_value_positions(&tokens, pos) { + result.push(x); + pos = x.0; + } + pos += 1; + } + assert_eq!(result, vec![(1, Some(3)), (6, Some(8)), (10, Some(12))]); +} + +#[test] +fn replace_tokens() { + let source = r#" +var x = ['a', 'b', null, 'd', {'x': null, 'e': null, 'z': 'w'}]; +var n = null; +"#; + let expected_result = "var x=['a','b',N,'d',{'x':N,'e':N,'z':'w'}];var n=N"; + + let res = crate::js::simple_minify(source) + .apply(crate::js::clean_tokens) + .apply(|f| { + replace_tokens_with(f, |t| { + if *t == Token::Keyword(Keyword::Null) { + Some(Token::Other("N")) + } else { + None + } + }) + }); + assert_eq!(res.to_string(), expected_result); +} + +#[test] +fn check_iterator() { + let source = r#" +var x = ['a', 'b', null, 'd', {'x': null, 'e': null, 'z': 'w'}]; +var n = null; +"#; + let expected_result = "var x=['a','b',N,'d',{'x':N,'e':N,'z':'w'}];var n=N;"; + + let res: Tokens = crate::js::simple_minify(source) + .into_iter() + .filter(|(x, next)| crate::js::clean_token(x, next)) + .map(|(t, _)| { + if t == Token::Keyword(Keyword::Null) { + Token::Other("N") + } else { + t + } + }) + .collect::<Vec<_>>() + .into(); + assert_eq!(res.to_string(), expected_result); +} diff --git a/vendor/minifier/src/json/json_minifier.rs b/vendor/minifier/src/json/json_minifier.rs new file mode 100644 index 000000000..ad9fae2ce --- /dev/null +++ b/vendor/minifier/src/json/json_minifier.rs @@ -0,0 +1,50 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +#[derive(Debug, Clone)] +pub struct JsonMinifier { + pub is_string: bool, + pub escaped_quotation: u8, +} + +impl Default for JsonMinifier { + fn default() -> Self { + Self::new() + } +} + +impl JsonMinifier { + pub fn new() -> Self { + JsonMinifier { + is_string: false, + escaped_quotation: 0, + } + } +} + +#[inline] +pub fn keep_element(minifier: &mut JsonMinifier, item1: &char, item2: Option<&char>) -> bool { + let remove_element = + item1.is_ascii_control() || is_whitespace_outside_string(minifier, item1, item2); + !remove_element +} + +#[inline] +fn is_whitespace_outside_string( + minifier: &mut JsonMinifier, + item1: &char, + item2: Option<&char>, +) -> bool { + if !minifier.is_string && item1.eq(&'"') { + minifier.is_string = true; + } else if minifier.is_string { + if item1.eq(&'\\') && item2.eq(&Some(&'"')) { + minifier.escaped_quotation = 4; + } + if minifier.escaped_quotation > 0 { + minifier.escaped_quotation -= 1; + } else if item1.eq(&'"') { + minifier.is_string = false; + } + } + !minifier.is_string && item1.is_whitespace() +} diff --git a/vendor/minifier/src/json/mod.rs b/vendor/minifier/src/json/mod.rs new file mode 100644 index 000000000..44c8a1c92 --- /dev/null +++ b/vendor/minifier/src/json/mod.rs @@ -0,0 +1,114 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::json::{ + json_minifier::{keep_element, JsonMinifier}, + read::json_read::JsonRead, + string::JsonMultiFilter, +}; +use std::fmt; +use std::io::{self, Read}; + +mod read { + mod byte_to_char; + mod internal_buffer; + mod internal_reader; + pub mod json_read; +} + +mod json_minifier; +mod string; + +type JsonMethod = fn(&mut JsonMinifier, &char, Option<&char>) -> bool; + +/// Minifies a given String by JSON minification rules +/// +/// # Example +/// +/// ```rust +/// use minifier::json::minify; +/// +/// let json = r#" +/// { +/// "test": "test", +/// "test2": 2 +/// } +/// "#.into(); +/// let json_minified = minify(json); +/// assert_eq!(&json_minified.to_string(), r#"{"test":"test","test2":2}"#); +/// ``` +#[inline] +pub fn minify(json: &str) -> Minified<'_> { + Minified(JsonMultiFilter::new(json.chars(), keep_element)) +} + +#[derive(Debug)] +pub struct Minified<'a>(JsonMultiFilter<'a, JsonMethod>); + +impl<'a> Minified<'a> { + pub fn write<W: io::Write>(self, w: W) -> io::Result<()> { + self.0.write(w) + } +} + +impl<'a> fmt::Display for Minified<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// Minifies a given Read by JSON minification rules +/// +/// # Example +/// +/// ```rust +/// extern crate minifier; +/// use std::fs::File; +/// use std::io::Read; +/// use minifier::json::minify_from_read; +/// +/// fn main() { +/// let mut html_minified = String::new(); +/// let mut file = File::open("tests/files/test.json").expect("file not found"); +/// minify_from_read(file).read_to_string(&mut html_minified); +/// } +/// ``` +#[inline] +pub fn minify_from_read<R: Read>(json: R) -> JsonRead<JsonMethod, R> { + JsonRead::new(json, keep_element) +} + +#[test] +fn removal_from_read() { + use std::fs::File; + + let input = File::open("tests/files/test.json").expect("file not found"); + let expected: String = "{\"test\":\"\\\" test2\",\"test2\":\"\",\"test3\":\" \"}".into(); + let mut actual = String::new(); + minify_from_read(input) + .read_to_string(&mut actual) + .expect("error at read"); + assert_eq!(actual, expected); +} + +#[test] +fn removal_of_control_characters() { + let input = "\n".into(); + let expected: String = "".into(); + let actual = minify(input); + assert_eq!(actual.to_string(), expected); +} + +#[test] +fn removal_of_whitespace_outside_of_tags() { + let input = r#" + { + "test": "\" test2", + "test2": "", + "test3": " " + } + "# + .into(); + let expected: String = "{\"test\":\"\\\" test2\",\"test2\":\"\",\"test3\":\" \"}".into(); + let actual = minify(input); + assert_eq!(actual.to_string(), expected); +} diff --git a/vendor/minifier/src/json/read/byte_to_char.rs b/vendor/minifier/src/json/read/byte_to_char.rs new file mode 100644 index 000000000..d3618b9cb --- /dev/null +++ b/vendor/minifier/src/json/read/byte_to_char.rs @@ -0,0 +1,132 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::json::read::internal_reader::InternalReader; +use std::{ + error, fmt, + io::{Error, Read}, + str::from_utf8, +}; + +pub struct ByteToChar<R> { + iter: InternalReader<R>, +} + +impl<R: Read> ByteToChar<R> { + #[inline] + pub fn new(read: R, buffer_size: usize) -> Result<Self, Error> { + Ok(ByteToChar { + iter: InternalReader::new(read, buffer_size)?, + }) + } + + fn get_next(&mut self) -> Result<Option<u8>, CharsError> { + match self.iter.next() { + None => Ok(None), + Some(item) => match item { + Ok(item) => Ok(Some(item)), + Err(err) => Err(CharsError::Other(err)), + }, + } + } +} + +impl<R: Read + fmt::Debug> fmt::Debug for ByteToChar<R> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Filter").field("iter", &self.iter).finish() + } +} + +impl<R: Read> Iterator for ByteToChar<R> { + type Item = Result<char, CharsError>; + + fn next(&mut self) -> Option<Result<char, CharsError>> { + let first_byte = match self.get_next() { + Err(err) => return Some(Err(err)), + Ok(item) => match item { + Some(item) => item, + None => return None, + }, + }; + + let width = utf8_char_width(first_byte); + if width == 1 { + return Some(Ok(first_byte as char)); + } + if width == 0 { + return Some(Err(CharsError::NotUtf8)); + } + let mut buf = [first_byte, 0, 0, 0]; + { + let mut start = 1; + while start < width { + let byte = match self.get_next() { + Err(err) => return Some(Err(err)), + Ok(item) => match item { + Some(item) => item, + None => return Some(Err(CharsError::NotUtf8)), + }, + }; + buf[start] = byte; + start += 1; + } + } + Some(match from_utf8(&buf[..width]).ok() { + Some(s) => Ok(s.chars().next().unwrap()), + None => Err(CharsError::NotUtf8), + }) + } +} + +fn utf8_char_width(b: u8) -> usize { + UTF8_CHAR_WIDTH[b as usize] as usize +} + +// https://tools.ietf.org/html/rfc3629 +static UTF8_CHAR_WIDTH: [u8; 256] = [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x1F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x3F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x5F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x7F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 0x9F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 0xBF + 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, // 0xDF + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF + 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF +]; + +/// An enumeration of possible errors that can be generated from the `Chars` +/// adapter. +#[derive(Debug)] +pub enum CharsError { + /// Variant representing that the underlying stream was read successfully + /// but it did not contain valid utf8 data. + NotUtf8, + + /// Variant representing that an I/O error occurred. + Other(Error), +} + +impl error::Error for CharsError { + fn cause(&self) -> Option<&dyn error::Error> { + match *self { + CharsError::NotUtf8 => None, + CharsError::Other(ref e) => e.source(), + } + } +} + +impl fmt::Display for CharsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + CharsError::NotUtf8 => "byte stream did not contain valid utf8".fmt(f), + CharsError::Other(ref e) => e.fmt(f), + } + } +} diff --git a/vendor/minifier/src/json/read/internal_buffer.rs b/vendor/minifier/src/json/read/internal_buffer.rs new file mode 100644 index 000000000..90eebcd73 --- /dev/null +++ b/vendor/minifier/src/json/read/internal_buffer.rs @@ -0,0 +1,44 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +const ARRAY_DEFAULT: u8 = 0; + +#[derive(Debug)] +pub struct Buffer { + buffer: Vec<u8>, + read_pos: usize, + buffer_size: usize, + data_size: usize, +} + +impl Buffer { + pub fn new(size: usize) -> Buffer { + Buffer { + buffer: vec![ARRAY_DEFAULT; size], + read_pos: 0, + buffer_size: size, + data_size: 0, + } + } + + pub fn as_mut(&mut self) -> &mut [u8] { + self.buffer.as_mut() + } + + pub fn update_metadata(&mut self, size: usize) { + self.read_pos = 0; + self.data_size = size; + } + + pub fn next(&mut self) -> Option<u8> { + if self.read_pos >= self.data_size { + return None; + } + let item = self.buffer.get(self.read_pos); + self.read_pos += 1; + item.copied() + } + + pub fn cont(&self) -> bool { + self.data_size == self.buffer_size + } +} diff --git a/vendor/minifier/src/json/read/internal_reader.rs b/vendor/minifier/src/json/read/internal_reader.rs new file mode 100644 index 000000000..45f178f08 --- /dev/null +++ b/vendor/minifier/src/json/read/internal_reader.rs @@ -0,0 +1,63 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use super::internal_buffer::Buffer; +use std::{ + fmt, + io::{Error, Read}, +}; + +pub struct InternalReader<R> { + read: R, + buffer_size: usize, + buffer: Buffer, +} + +impl<R: Read> InternalReader<R> { + pub fn new(mut read: R, buffer_size: usize) -> Result<Self, Error> { + let mut buffer = Buffer::new(buffer_size); + InternalReader::read_data(&mut read, &mut buffer)?; + Ok(InternalReader { + read, + buffer_size, + buffer, + }) + } + + fn read_data(read: &mut R, buffer: &mut Buffer) -> Result<(), Error> { + let size = read.read(buffer.as_mut())?; + buffer.update_metadata(size); + Ok(()) + } +} + +impl<R: Read + fmt::Debug> fmt::Debug for InternalReader<R> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("JsonReader") + .field("read", &self.read) + .field("buffer_size", &self.buffer_size) + .field("buffer", &self.buffer) + .finish() + } +} + +impl<R: Read> Iterator for InternalReader<R> { + type Item = Result<u8, Error>; + + #[inline] + fn next(&mut self) -> Option<Result<u8, Error>> { + if self.buffer_size == 0 { + return None; + } + loop { + if let Some(item) = self.buffer.next() { + return Some(Ok(item)); + } else if self.buffer.cont() { + if let Err(err) = InternalReader::read_data(&mut self.read, &mut self.buffer) { + return Some(Err(err)); + }; + } else { + return None; + } + } + } +} diff --git a/vendor/minifier/src/json/read/json_read.rs b/vendor/minifier/src/json/read/json_read.rs new file mode 100644 index 000000000..338db13c8 --- /dev/null +++ b/vendor/minifier/src/json/read/json_read.rs @@ -0,0 +1,106 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::json::{ + json_minifier::JsonMinifier, + read::byte_to_char::{ByteToChar, CharsError}, +}; +use std::{ + fmt, + io::{Error, ErrorKind, Read}, + vec::IntoIter, +}; + +pub struct JsonRead<P, R> { + minifier: JsonMinifier, + read: Option<R>, + iter: Option<ByteToChar<R>>, + predicate: P, + initialized: bool, + item_iter: Option<IntoIter<u8>>, + item1: Option<char>, +} + +impl<P, R: Read> JsonRead<P, R> { + #[inline] + pub fn new(read: R, predicate: P) -> Self { + JsonRead { + minifier: JsonMinifier::default(), + read: Some(read), + iter: None, + predicate, + initialized: false, + item_iter: None, + item1: None, + } + } + + fn get_next(&mut self) -> Result<Option<char>, CharsError> { + match self.iter.as_mut().unwrap().next() { + None => Ok(None), + Some(item) => match item { + Ok(item) => Ok(Some(item)), + Err(err) => Err(err), + }, + } + } + + fn add_char_to_buffer(&mut self, buf: &mut [u8], buf_pos: &mut usize) { + if let Some(ref mut iter) = self.item_iter { + while *buf_pos < buf.len() { + if let Some(byte) = iter.next() { + buf[*buf_pos] = byte; + *buf_pos += 1; + } else { + break; + } + } + } + } +} + +impl<P, R: Read + fmt::Debug> fmt::Debug for JsonRead<P, R> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Filter") + .field("iter", &self.iter) + .field("initialized", &self.initialized) + .finish() + } +} + +impl<P, R> Read for JsonRead<P, R> +where + R: Read, + P: FnMut(&mut JsonMinifier, &char, Option<&char>) -> bool, +{ + fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { + let mut buf_pos: usize = 0; + + if buf.is_empty() { + return Ok(0); + } + + if !self.initialized { + self.iter = Some(ByteToChar::new(self.read.take().unwrap(), buf.len())?); + self.item1 = self.get_next()?; + self.initialized = true; + } + + while let Some(item) = self.item1.take() { + self.item1 = self.get_next()?; + if (self.predicate)(&mut self.minifier, &item, self.item1.as_ref()) { + self.item_iter = Some(item.to_string().into_bytes().into_iter()); + self.add_char_to_buffer(buf, &mut buf_pos); + } + if buf_pos >= buf.len() { + break; + } + } + Ok(buf_pos) + } +} + +impl From<CharsError> for Error { + fn from(_: CharsError) -> Self { + Error::from(ErrorKind::InvalidData) + } +} diff --git a/vendor/minifier/src/json/string.rs b/vendor/minifier/src/json/string.rs new file mode 100644 index 000000000..071bf0012 --- /dev/null +++ b/vendor/minifier/src/json/string.rs @@ -0,0 +1,100 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::json::json_minifier::JsonMinifier; + +use std::fmt; +use std::str::Chars; + +#[derive(Clone)] +pub struct JsonMultiFilter<'a, P: Clone> { + minifier: JsonMinifier, + iter: Chars<'a>, + predicate: P, + initialized: bool, + item1: Option<<Chars<'a> as Iterator>::Item>, +} + +impl<'a, P: Clone> JsonMultiFilter<'a, P> { + #[inline] + pub fn new(iter: Chars<'a>, predicate: P) -> Self { + JsonMultiFilter { + minifier: JsonMinifier::default(), + iter, + predicate, + initialized: false, + item1: None, + } + } +} + +impl<'a, P: Clone> fmt::Debug for JsonMultiFilter<'a, P> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Filter") + .field("minifier", &self.minifier) + .field("iter", &self.iter) + .field("initialized", &self.initialized) + .finish() + } +} + +impl<'a, P: Clone> Iterator for JsonMultiFilter<'a, P> +where + P: FnMut( + &mut JsonMinifier, + &<Chars<'a> as Iterator>::Item, + Option<&<Chars<'a> as Iterator>::Item>, + ) -> bool, +{ + type Item = <Chars<'a> as Iterator>::Item; + + #[inline] + fn next(&mut self) -> Option<<Chars<'a> as Iterator>::Item> { + if !self.initialized { + self.item1 = self.iter.next(); + self.initialized = true; + } + + while let Some(item) = self.item1.take() { + self.item1 = self.iter.next(); + if (self.predicate)(&mut self.minifier, &item, self.item1.as_ref()) { + return Some(item); + } + } + None + } +} + +impl<'a, P> JsonMultiFilter<'a, P> +where + P: FnMut( + &mut JsonMinifier, + &<Chars<'a> as Iterator>::Item, + Option<&<Chars<'a> as Iterator>::Item>, + ) -> bool + + Clone, +{ + pub(super) fn write<W: std::io::Write>(self, mut w: W) -> std::io::Result<()> { + for token in self { + write!(w, "{}", token)?; + } + Ok(()) + } +} + +impl<'a, P> fmt::Display for JsonMultiFilter<'a, P> +where + P: FnMut( + &mut JsonMinifier, + &<Chars<'a> as Iterator>::Item, + Option<&<Chars<'a> as Iterator>::Item>, + ) -> bool + + Clone, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let s = (*self).clone(); + for token in s { + write!(f, "{}", token)?; + } + Ok(()) + } +} diff --git a/vendor/minifier/src/lib.rs b/vendor/minifier/src/lib.rs new file mode 100644 index 000000000..a88f9abb8 --- /dev/null +++ b/vendor/minifier/src/lib.rs @@ -0,0 +1,10 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +#[cfg(feature = "html")] +extern crate regex; + +pub mod css; +#[cfg(feature = "html")] +pub mod html; +pub mod js; +pub mod json; diff --git a/vendor/minifier/src/main.rs b/vendor/minifier/src/main.rs new file mode 100644 index 000000000..eb420325e --- /dev/null +++ b/vendor/minifier/src/main.rs @@ -0,0 +1,94 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +extern crate minifier; + +use std::env; +use std::ffi::OsStr; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; + +use minifier::{css, js, json}; + +fn print_help() { + println!( + r##"For now, this minifier supports the following type of files: + + * .css + * .js + * .json"## + ); +} + +pub fn get_all_data(file_path: &str) -> io::Result<String> { + let mut file = File::open(file_path)?; + let mut data = String::new(); + + file.read_to_string(&mut data).unwrap(); + Ok(data) +} + +fn call_minifier<F>(file_path: &str, func: F) +where + F: Fn(&str) -> String, +{ + match get_all_data(file_path) { + Ok(content) => { + let mut out = PathBuf::from(file_path); + let original_extension = out + .extension() + .unwrap_or_else(|| OsStr::new("")) + .to_str() + .unwrap_or("") + .to_owned(); + out.set_extension(format!("min.{}", original_extension)); + if let Ok(mut file) = OpenOptions::new() + .truncate(true) + .write(true) + .create(true) + .open(out.clone()) + { + if let Err(e) = write!(file, "{}", func(&content)) { + eprintln!("Impossible to write into {:?}: {}", out, e); + } else { + println!("{:?}: done -> generated into {:?}", file_path, out); + } + } else { + eprintln!("Impossible to create new file: {:?}", out); + } + } + Err(e) => eprintln!("\"{}\": {}", file_path, e), + } +} + +fn main() { + let args: Vec<_> = env::args().skip(1).collect(); + + if args.is_empty() { + println!("Missing files to work on...\nExample: ./minifier file.js\n"); + print_help(); + return; + } + for arg in &args { + let p = Path::new(arg); + + if !p.is_file() { + eprintln!("\"{}\" isn't a file", arg); + continue; + } + match p + .extension() + .unwrap_or_else(|| OsStr::new("")) + .to_str() + .unwrap_or("") + { + "css" => call_minifier(arg, |s| { + css::minify(s).expect("css minification failed").to_string() + }), + "js" => call_minifier(arg, |s| js::minify(s).to_string()), + "json" => call_minifier(arg, |s| json::minify(s).to_string()), + // "html" | "htm" => call_minifier(arg, html::minify), + x => println!("\"{}\": this format isn't supported", x), + } + } +} diff --git a/vendor/minifier/tests/files/main.js b/vendor/minifier/tests/files/main.js new file mode 100644 index 000000000..82d2c11b2 --- /dev/null +++ b/vendor/minifier/tests/files/main.js @@ -0,0 +1,2542 @@ +// From rust: +/* global ALIASES, currentCrate, rootPath */ + +// Local js definitions: +/* global addClass, getCurrentValue, hasClass */ +/* global isHidden onEach, removeClass, updateLocalStorage */ + +if (!String.prototype.startsWith) { + String.prototype.startsWith = function(searchString, position) { + position = position || 0; + return this.indexOf(searchString, position) === position; + }; +} +if (!String.prototype.endsWith) { + String.prototype.endsWith = function(suffix, length) { + var l = length || this.length; + return this.indexOf(suffix, l - suffix.length) !== -1; + }; +} + +if (!DOMTokenList.prototype.add) { + DOMTokenList.prototype.add = function(className) { + if (className && !hasClass(this, className)) { + if (this.className && this.className.length > 0) { + this.className += " " + className; + } else { + this.className = className; + } + } + }; +} + +if (!DOMTokenList.prototype.remove) { + DOMTokenList.prototype.remove = function(className) { + if (className && this.className) { + this.className = (" " + this.className + " ").replace(" " + className + " ", " ") + .trim(); + } + }; +} + +(function() { + "use strict"; + + // This mapping table should match the discriminants of + // `rustdoc::html::item_type::ItemType` type in Rust. + var itemTypes = ["mod", + "externcrate", + "import", + "struct", + "enum", + "fn", + "type", + "static", + "trait", + "impl", + "tymethod", + "method", + "structfield", + "variant", + "macro", + "primitive", + "associatedtype", + "constant", + "associatedconstant", + "union", + "foreigntype", + "keyword", + "existential", + "attr", + "derive", + "traitalias"]; + + var search_input = document.getElementsByClassName("search-input")[0]; + + // On the search screen, so you remain on the last tab you opened. + // + // 0 for "In Names" + // 1 for "In Parameters" + // 2 for "In Return Types" + var currentTab = 0; + + var titleBeforeSearch = document.title; + + function getPageId() { + var id = document.location.href.split("#")[1]; + if (id) { + return id.split("?")[0].split("&")[0]; + } + return null; + } + + function showSidebar() { + var elems = document.getElementsByClassName("sidebar-elems")[0]; + if (elems) { + addClass(elems, "show-it"); + } + var sidebar = document.getElementsByClassName("sidebar")[0]; + if (sidebar) { + addClass(sidebar, "mobile"); + var filler = document.getElementById("sidebar-filler"); + if (!filler) { + var div = document.createElement("div"); + div.id = "sidebar-filler"; + sidebar.appendChild(div); + } + } + var themePicker = document.getElementsByClassName("theme-picker"); + if (themePicker && themePicker.length > 0) { + themePicker[0].style.display = "none"; + } + } + + function hideSidebar() { + var elems = document.getElementsByClassName("sidebar-elems")[0]; + if (elems) { + removeClass(elems, "show-it"); + } + var sidebar = document.getElementsByClassName("sidebar")[0]; + removeClass(sidebar, "mobile"); + var filler = document.getElementById("sidebar-filler"); + if (filler) { + filler.remove(); + } + document.getElementsByTagName("body")[0].style.marginTop = ""; + var themePicker = document.getElementsByClassName("theme-picker"); + if (themePicker && themePicker.length > 0) { + themePicker[0].style.display = null; + } + } + + // used for special search precedence + var TY_PRIMITIVE = itemTypes.indexOf("primitive"); + var TY_KEYWORD = itemTypes.indexOf("keyword"); + + onEachLazy(document.getElementsByClassName("js-only"), function(e) { + removeClass(e, "js-only"); + }); + + function getQueryStringParams() { + var params = {}; + window.location.search.substring(1).split("&"). + map(function(s) { + var pair = s.split("="); + params[decodeURIComponent(pair[0])] = + typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]); + }); + return params; + } + + function browserSupportsHistoryApi() { + return window.history && typeof window.history.pushState === "function"; + } + + var main = document.getElementById("main"); + + function highlightSourceLines(ev) { + // If we're in mobile mode, we should add the sidebar in any case. + hideSidebar(); + var elem; + var search = document.getElementById("search"); + var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/); + if (match) { + from = parseInt(match[1], 10); + to = from; + if (typeof match[2] !== "undefined") { + to = parseInt(match[2], 10); + } + if (to < from) { + var tmp = to; + to = from; + from = tmp; + } + elem = document.getElementById(from); + if (!elem) { + return; + } + if (ev === null) { + var x = document.getElementById(from); + if (x) { + x.scrollIntoView(); + } + } + onEachLazy(document.getElementsByClassName("line-numbers"), function(e) { + onEachLazy(e.getElementsByTagName("span"), function(i_e) { + removeClass(i_e, "line-highlighted"); + }); + }); + for (i = from; i <= to; ++i) { + elem = document.getElementById(i); + if (!elem) { + break; + } + addClass(elem, "line-highlighted"); + } + } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) { + addClass(search, "hidden"); + removeClass(main, "hidden"); + var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1); + if (browserSupportsHistoryApi()) { + history.replaceState(hash, "", "?search=#" + hash); + } + elem = document.getElementById(hash); + if (elem) { + elem.scrollIntoView(); + } + } + } + + function expandSection(id) { + var elem = document.getElementById(id); + if (elem && isHidden(elem)) { + var h3 = elem.parentNode.previousElementSibling; + if (h3 && h3.tagName !== "H3") { + h3 = h3.previousElementSibling; // skip div.docblock + } + + if (h3) { + var collapses = h3.getElementsByClassName("collapse-toggle"); + if (collapses.length > 0) { + // The element is not visible, we need to make it appear! + collapseDocs(collapses[0], "show"); + } + } + } + } + + highlightSourceLines(null); + window.onhashchange = highlightSourceLines; + + // Gets the human-readable string for the virtual-key code of the + // given KeyboardEvent, ev. + // + // This function is meant as a polyfill for KeyboardEvent#key, + // since it is not supported in Trident. We also test for + // KeyboardEvent#keyCode because the handleShortcut handler is + // also registered for the keydown event, because Blink doesn't fire + // keypress on hitting the Escape key. + // + // So I guess you could say things are getting pretty interoperable. + function getVirtualKey(ev) { + if ("key" in ev && typeof ev.key != "undefined") { + return ev.key; + } + + var c = ev.charCode || ev.keyCode; + if (c == 27) { + return "Escape"; + } + return String.fromCharCode(c); + } + + function displayHelp(display, ev, help) { + if (display === true) { + if (hasClass(help, "hidden")) { + ev.preventDefault(); + removeClass(help, "hidden"); + addClass(document.body, "blur"); + } + } else if (hasClass(help, "hidden") === false) { + ev.preventDefault(); + addClass(help, "hidden"); + removeClass(document.body, "blur"); + } + } + + function handleEscape(ev, help) { + hideModal(); + var search = document.getElementById("search"); + if (hasClass(help, "hidden") === false) { + displayHelp(false, ev, help); + } else if (hasClass(search, "hidden") === false) { + ev.preventDefault(); + addClass(search, "hidden"); + removeClass(main, "hidden"); + document.title = titleBeforeSearch; + } + defocusSearchBar(); + } + + function handleShortcut(ev) { + // Don't interfere with browser shortcuts + if (ev.ctrlKey || ev.altKey || ev.metaKey) { + return; + } + + var help = document.getElementById("help"); + if (document.activeElement.tagName === "INPUT") { + switch (getVirtualKey(ev)) { + case "Escape": + handleEscape(ev, help); + break; + } + } else { + switch (getVirtualKey(ev)) { + case "Escape": + handleEscape(ev, help); + break; + + case "s": + case "S": + displayHelp(false, ev, help); + hideModal(); + ev.preventDefault(); + focusSearchBar(); + break; + + case "+": + case "-": + ev.preventDefault(); + toggleAllDocs(); + break; + + case "?": + if (ev.shiftKey) { + hideModal(); + displayHelp(true, ev, help); + } + break; + } + } + } + + function findParentElement(elem, tagName) { + do { + if (elem && elem.tagName === tagName) { + return elem; + } + elem = elem.parentNode; + } while (elem); + return null; + } + + document.onkeypress = handleShortcut; + document.onkeydown = handleShortcut; + document.onclick = function(ev) { + if (hasClass(ev.target, "collapse-toggle")) { + collapseDocs(ev.target, "toggle"); + } else if (hasClass(ev.target.parentNode, "collapse-toggle")) { + collapseDocs(ev.target.parentNode, "toggle"); + } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) { + var prev_id = 0; + + var set_fragment = function(name) { + if (browserSupportsHistoryApi()) { + history.replaceState(null, null, "#" + name); + window.hashchange(); + } else { + location.replace("#" + name); + } + }; + + var cur_id = parseInt(ev.target.id, 10); + + if (ev.shiftKey && prev_id) { + if (prev_id > cur_id) { + var tmp = prev_id; + prev_id = cur_id; + cur_id = tmp; + } + + set_fragment(prev_id + "-" + cur_id); + } else { + prev_id = cur_id; + + set_fragment(cur_id); + } + } else if (hasClass(document.getElementById("help"), "hidden") === false) { + addClass(document.getElementById("help"), "hidden"); + removeClass(document.body, "blur"); + } else { + // Making a collapsed element visible on onhashchange seems + // too late + var a = findParentElement(ev.target, "A"); + if (a && a.hash) { + expandSection(a.hash.replace(/^#/, "")); + } + } + }; + + var x = document.getElementsByClassName("version-selector"); + if (x.length > 0) { + x[0].onchange = function() { + var i, match, + url = document.location.href, + stripped = "", + len = rootPath.match(/\.\.\//g).length + 1; + + for (i = 0; i < len; ++i) { + match = url.match(/\/[^\/]*$/); + if (i < len - 1) { + stripped = match[0] + stripped; + } + url = url.substring(0, url.length - match[0].length); + } + + url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped; + + document.location.href = url; + }; + } + + /** + * A function to compute the Levenshtein distance between two strings + * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported + * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode + * This code is an unmodified version of the code written by Marco de Wit + * and was found at http://stackoverflow.com/a/18514751/745719 + */ + var levenshtein_row2 = []; + function levenshtein(s1, s2) { + if (s1 === s2) { + return 0; + } + var s1_len = s1.length, s2_len = s2.length; + if (s1_len && s2_len) { + var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2; + while (i1 < s1_len) { + row[i1] = ++i1; + } + while (i2 < s2_len) { + c2 = s2.charCodeAt(i2); + a = i2; + ++i2; + b = i2; + for (i1 = 0; i1 < s1_len; ++i1) { + c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0); + a = row[i1]; + b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c); + row[i1] = b; + } + } + return b; + } + return s1_len + s2_len; + } + + function initSearch(rawSearchIndex) { + var currentResults, index, searchIndex; + var MAX_LEV_DISTANCE = 3; + var MAX_RESULTS = 200; + var GENERICS_DATA = 1; + var NAME = 0; + var INPUTS_DATA = 0; + var OUTPUT_DATA = 1; + var params = getQueryStringParams(); + + // Populate search bar with query string search term when provided, + // but only if the input bar is empty. This avoid the obnoxious issue + // where you start trying to do a search, and the index loads, and + // suddenly your search is gone! + if (search_input.value === "") { + search_input.value = params.search || ""; + } + + /** + * Executes the query and builds an index of results + * @param {[Object]} query [The user query] + * @param {[type]} searchWords [The list of search words to query + * against] + * @param {[type]} filterCrates [Crate to search in if defined] + * @return {[type]} [A search index of results] + */ + function execQuery(query, searchWords, filterCrates) { + function itemTypeFromName(typename) { + var length = itemTypes.length; + for (var i = 0; i < length; ++i) { + if (itemTypes[i] === typename) { + return i; + } + } + return -1; + } + + var valLower = query.query.toLowerCase(), + val = valLower, + typeFilter = itemTypeFromName(query.type), + results = {}, results_in_args = {}, results_returned = {}, + split = valLower.split("::"); + + var length = split.length; + for (var z = 0; z < length; ++z) { + if (split[z] === "") { + split.splice(z, 1); + z -= 1; + } + } + + function transformResults(results, isType) { + var out = []; + var length = results.length; + for (var i = 0; i < length; ++i) { + if (results[i].id > -1) { + var obj = searchIndex[results[i].id]; + obj.lev = results[i].lev; + if (isType !== true || obj.type) { + var res = buildHrefAndPath(obj); + obj.displayPath = pathSplitter(res[0]); + obj.fullPath = obj.displayPath + obj.name; + // To be sure than it some items aren't considered as duplicate. + obj.fullPath += "|" + obj.ty; + obj.href = res[1]; + out.push(obj); + if (out.length >= MAX_RESULTS) { + break; + } + } + } + } + return out; + } + + function sortResults(results, isType) { + var ar = []; + for (var entry in results) { + if (results.hasOwnProperty(entry)) { + ar.push(results[entry]); + } + } + results = ar; + var i; + var nresults = results.length; + for (i = 0; i < nresults; ++i) { + results[i].word = searchWords[results[i].id]; + results[i].item = searchIndex[results[i].id] || {}; + } + // if there are no results then return to default and fail + if (results.length === 0) { + return []; + } + + results.sort(function(aaa, bbb) { + var a, b; + + // Sort by non levenshtein results and then levenshtein results by the distance + // (less changes required to match means higher rankings) + a = (aaa.lev); + b = (bbb.lev); + if (a !== b) { return a - b; } + + // sort by crate (non-current crate goes later) + a = (aaa.item.crate !== window.currentCrate); + b = (bbb.item.crate !== window.currentCrate); + if (a !== b) { return a - b; } + + // sort by exact match (mismatch goes later) + a = (aaa.word !== valLower); + b = (bbb.word !== valLower); + if (a !== b) { return a - b; } + + // sort by item name length (longer goes later) + a = aaa.word.length; + b = bbb.word.length; + if (a !== b) { return a - b; } + + // sort by item name (lexicographically larger goes later) + a = aaa.word; + b = bbb.word; + if (a !== b) { return (a > b ? +1 : -1); } + + // sort by index of keyword in item name (no literal occurrence goes later) + a = (aaa.index < 0); + b = (bbb.index < 0); + if (a !== b) { return a - b; } + // (later literal occurrence, if any, goes later) + a = aaa.index; + b = bbb.index; + if (a !== b) { return a - b; } + + // special precedence for primitive and keyword pages + if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) || + (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) { + return -1; + } + if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) || + (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) { + return 1; + } + + // sort by description (no description goes later) + a = (aaa.item.desc === ""); + b = (bbb.item.desc === ""); + if (a !== b) { return a - b; } + + // sort by type (later occurrence in `itemTypes` goes later) + a = aaa.item.ty; + b = bbb.item.ty; + if (a !== b) { return a - b; } + + // sort by path (lexicographically larger goes later) + a = aaa.item.path; + b = bbb.item.path; + if (a !== b) { return (a > b ? +1 : -1); } + + // que sera, sera + return 0; + }); + + var length = results.length; + for (i = 0; i < length; ++i) { + var result = results[i]; + + // this validation does not make sense when searching by types + if (result.dontValidate) { + continue; + } + var name = result.item.name.toLowerCase(), + path = result.item.path.toLowerCase(), + parent = result.item.parent; + + if (isType !== true && + validateResult(name, path, split, parent) === false) + { + result.id = -1; + } + } + return transformResults(results); + } + + function extractGenerics(val) { + val = val.toLowerCase(); + if (val.indexOf("<") !== -1) { + var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">")); + return { + name: val.substring(0, val.indexOf("<")), + generics: values.split(/\s*,\s*/), + }; + } + return { + name: val, + generics: [], + }; + } + + function checkGenerics(obj, val) { + // The names match, but we need to be sure that all generics kinda + // match as well. + var lev_distance = MAX_LEV_DISTANCE + 1; + if (val.generics.length > 0) { + if (obj.length > GENERICS_DATA && + obj[GENERICS_DATA].length >= val.generics.length) { + var elems = obj[GENERICS_DATA].slice(0); + var total = 0; + var done = 0; + // We need to find the type that matches the most to remove it in order + // to move forward. + var vlength = val.generics.length; + for (var y = 0; y < vlength; ++y) { + var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1}; + var elength = elems.length; + for (var x = 0; x < elength; ++x) { + var tmp_lev = levenshtein(elems[x], val.generics[y]); + if (tmp_lev < lev.lev) { + lev.lev = tmp_lev; + lev.pos = x; + } + } + if (lev.pos !== -1) { + elems.splice(lev.pos, 1); + lev_distance = Math.min(lev.lev, lev_distance); + total += lev.lev; + done += 1; + } else { + return MAX_LEV_DISTANCE + 1; + } + } + return Math.ceil(total / done); + } + } + return MAX_LEV_DISTANCE + 1; + } + + // Check for type name and type generics (if any). + function checkType(obj, val, literalSearch) { + var lev_distance = MAX_LEV_DISTANCE + 1; + var x; + if (obj[NAME] === val.name) { + if (literalSearch === true) { + if (val.generics && val.generics.length !== 0) { + if (obj.length > GENERICS_DATA && + obj[GENERICS_DATA].length >= val.generics.length) { + var elems = obj[GENERICS_DATA].slice(0); + var allFound = true; + + for (var y = 0; allFound === true && y < val.generics.length; ++y) { + allFound = false; + for (x = 0; allFound === false && x < elems.length; ++x) { + allFound = elems[x] === val.generics[y]; + } + if (allFound === true) { + elems.splice(x - 1, 1); + } + } + if (allFound === true) { + return true; + } + } else { + return false; + } + } + return true; + } + // If the type has generics but don't match, then it won't return at this point. + // Otherwise, `checkGenerics` will return 0 and it'll return. + if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) { + var tmp_lev = checkGenerics(obj, val); + if (tmp_lev <= MAX_LEV_DISTANCE) { + return tmp_lev; + } + } else { + return 0; + } + } + // Names didn't match so let's check if one of the generic types could. + if (literalSearch === true) { + if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) { + var length = obj[GENERICS_DATA].length; + for (x = 0; x < length; ++x) { + if (obj[GENERICS_DATA][x] === val.name) { + return true; + } + } + } + return false; + } + lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance); + if (lev_distance <= MAX_LEV_DISTANCE) { + // The generics didn't match but the name kinda did so we give it + // a levenshtein distance value that isn't *this* good so it goes + // into the search results but not too high. + lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2); + } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) { + // We can check if the type we're looking for is inside the generics! + var olength = obj[GENERICS_DATA].length; + for (x = 0; x < olength; ++x) { + lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name), + lev_distance); + } + } + // Now whatever happens, the returned distance is "less good" so we should mark it + // as such, and so we add 1 to the distance to make it "less good". + return lev_distance + 1; + } + + function findArg(obj, val, literalSearch) { + var lev_distance = MAX_LEV_DISTANCE + 1; + + if (obj && obj.type && obj.type[INPUTS_DATA] && + obj.type[INPUTS_DATA].length > 0) { + var length = obj.type[INPUTS_DATA].length; + for (var i = 0; i < length; i++) { + var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch); + if (literalSearch === true && tmp === true) { + return true; + } + lev_distance = Math.min(tmp, lev_distance); + if (lev_distance === 0) { + return 0; + } + } + } + return literalSearch === true ? false : lev_distance; + } + + function checkReturned(obj, val, literalSearch) { + var lev_distance = MAX_LEV_DISTANCE + 1; + + if (obj && obj.type && obj.type.length > OUTPUT_DATA) { + var ret = obj.type[OUTPUT_DATA]; + if (!obj.type[OUTPUT_DATA].length) { + ret = [ret]; + } + for (var x = 0; x < ret.length; ++x) { + var r = ret[x]; + if (typeof r === "string") { + r = [r]; + } + var tmp = checkType(r, val, literalSearch); + if (literalSearch === true) { + if (tmp === true) { + return true; + } + continue; + } + lev_distance = Math.min(tmp, lev_distance); + if (lev_distance === 0) { + return 0; + } + } + } + return literalSearch === true ? false : lev_distance; + } + + function checkPath(contains, lastElem, ty) { + if (contains.length === 0) { + return 0; + } + var ret_lev = MAX_LEV_DISTANCE + 1; + var path = ty.path.split("::"); + + if (ty.parent && ty.parent.name) { + path.push(ty.parent.name.toLowerCase()); + } + + var length = path.length; + var clength = contains.length; + if (clength > length) { + return MAX_LEV_DISTANCE + 1; + } + for (var i = 0; i < length; ++i) { + if (i + clength > length) { + break; + } + var lev_total = 0; + var aborted = false; + for (var x = 0; x < clength; ++x) { + var lev = levenshtein(path[i + x], contains[x]); + if (lev > MAX_LEV_DISTANCE) { + aborted = true; + break; + } + lev_total += lev; + } + if (aborted === false) { + ret_lev = Math.min(ret_lev, Math.round(lev_total / clength)); + } + } + return ret_lev; + } + + function typePassesFilter(filter, type) { + // No filter + if (filter < 0) return true; + + // Exact match + if (filter === type) return true; + + // Match related items + var name = itemTypes[type]; + switch (itemTypes[filter]) { + case "constant": + return (name == "associatedconstant"); + case "fn": + return (name == "method" || name == "tymethod"); + case "type": + return (name == "primitive" || name == "keyword"); + } + + // No match + return false; + } + + function generateId(ty) { + if (ty.parent && ty.parent.name) { + return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name; + } + return itemTypes[ty.ty] + ty.path + ty.name; + } + + // quoted values mean literal search + var nSearchWords = searchWords.length; + var i; + var ty; + var fullId; + var returned; + var in_args; + if ((val.charAt(0) === "\"" || val.charAt(0) === "'") && + val.charAt(val.length - 1) === val.charAt(0)) + { + val = extractGenerics(val.substr(1, val.length - 2)); + for (i = 0; i < nSearchWords; ++i) { + if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) { + continue; + } + in_args = findArg(searchIndex[i], val, true); + returned = checkReturned(searchIndex[i], val, true); + ty = searchIndex[i]; + fullId = generateId(ty); + + if (searchWords[i] === val.name) { + // filter type: ... queries + if (typePassesFilter(typeFilter, searchIndex[i].ty) && + results[fullId] === undefined) + { + results[fullId] = {id: i, index: -1}; + } + } else if ((in_args === true || returned === true) && + typePassesFilter(typeFilter, searchIndex[i].ty)) { + if (in_args === true || returned === true) { + if (in_args === true) { + results_in_args[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + if (returned === true) { + results_returned[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + } else { + results[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + } + } + query.inputs = [val]; + query.output = val; + query.search = val; + // searching by type + } else if (val.search("->") > -1) { + var trimmer = function(s) { return s.trim(); }; + var parts = val.split("->").map(trimmer); + var input = parts[0]; + // sort inputs so that order does not matter + var inputs = input.split(",").map(trimmer).sort(); + for (i = 0; i < inputs.length; ++i) { + inputs[i] = extractGenerics(inputs[i]); + } + var output = extractGenerics(parts[1]); + + for (i = 0; i < nSearchWords; ++i) { + if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) { + continue; + } + var type = searchIndex[i].type; + ty = searchIndex[i]; + if (!type) { + continue; + } + fullId = generateId(ty); + + // allow searching for void (no output) functions as well + var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : ""; + returned = checkReturned(ty, output, true); + if (output.name === "*" || returned === true) { + in_args = false; + var is_module = false; + + if (input === "*") { + is_module = true; + } else { + var allFound = true; + for (var it = 0; allFound === true && it < inputs.length; it++) { + allFound = checkType(type, inputs[it], true); + } + in_args = allFound; + } + if (in_args === true) { + results_in_args[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + if (returned === true) { + results_returned[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + if (is_module === true) { + results[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + } + } + query.inputs = inputs.map(function(input) { + return input.name; + }); + query.output = output.name; + } else { + query.inputs = [val]; + query.output = val; + query.search = val; + // gather matching search results up to a certain maximum + val = val.replace(/\_/g, ""); + + var valGenerics = extractGenerics(val); + + var paths = valLower.split("::"); + var j; + for (j = 0; j < paths.length; ++j) { + if (paths[j] === "") { + paths.splice(j, 1); + j -= 1; + } + } + val = paths[paths.length - 1]; + var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1); + + for (j = 0; j < nSearchWords; ++j) { + var lev; + var lev_distance; + ty = searchIndex[j]; + if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) { + continue; + } + var lev_distance; + var lev_add = 0; + if (paths.length > 1) { + lev = checkPath(contains, paths[paths.length - 1], ty); + if (lev > MAX_LEV_DISTANCE) { + continue; + } else if (lev > 0) { + lev_add = 1; + } + } + + returned = MAX_LEV_DISTANCE + 1; + in_args = MAX_LEV_DISTANCE + 1; + var index = -1; + // we want lev results to go lower than others + lev = MAX_LEV_DISTANCE + 1; + fullId = generateId(ty); + + if (searchWords[j].indexOf(split[i]) > -1 || + searchWords[j].indexOf(val) > -1 || + searchWords[j].replace(/_/g, "").indexOf(val) > -1) + { + // filter type: ... queries + if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) { + index = searchWords[j].replace(/_/g, "").indexOf(val); + } + } + if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) { + if (typePassesFilter(typeFilter, ty.ty) === false) { + lev = MAX_LEV_DISTANCE + 1; + } else { + lev += 1; + } + } + if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) { + if (typePassesFilter(typeFilter, ty.ty) === false) { + in_args = MAX_LEV_DISTANCE + 1; + } + } + if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) { + if (typePassesFilter(typeFilter, ty.ty) === false) { + returned = MAX_LEV_DISTANCE + 1; + } + } + + lev += lev_add; + if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) { + if (val.length < 6) { + lev -= 1; + } else { + lev = 0; + } + } + if (in_args <= MAX_LEV_DISTANCE) { + if (results_in_args[fullId] === undefined) { + results_in_args[fullId] = { + id: j, + index: index, + lev: in_args, + }; + } + results_in_args[fullId].lev = + Math.min(results_in_args[fullId].lev, in_args); + } + if (returned <= MAX_LEV_DISTANCE) { + if (results_returned[fullId] === undefined) { + results_returned[fullId] = { + id: j, + index: index, + lev: returned, + }; + } + results_returned[fullId].lev = + Math.min(results_returned[fullId].lev, returned); + } + if (index !== -1 || lev <= MAX_LEV_DISTANCE) { + if (index !== -1 && paths.length < 2) { + lev = 0; + } else if (searchWords[j] === val) { + // Small trick to fix when you're looking for a one letter type + // and there are other short named types. + lev = -1; + } + if (results[fullId] === undefined) { + results[fullId] = { + id: j, + index: index, + lev: lev, + }; + } + results[fullId].lev = Math.min(results[fullId].lev, lev); + } + } + } + + var ret = { + "in_args": sortResults(results_in_args, true), + "returned": sortResults(results_returned, true), + "others": sortResults(results), + }; + if (ALIASES && ALIASES[window.currentCrate] && + ALIASES[window.currentCrate][query.raw]) { + var aliases = ALIASES[window.currentCrate][query.raw]; + for (i = 0; i < aliases.length; ++i) { + aliases[i].is_alias = true; + aliases[i].alias = query.raw; + aliases[i].path = aliases[i].p; + var res = buildHrefAndPath(aliases[i]); + aliases[i].displayPath = pathSplitter(res[0]); + aliases[i].fullPath = aliases[i].displayPath + aliases[i].name; + aliases[i].href = res[1]; + ret.others.unshift(aliases[i]); + if (ret.others.length > MAX_RESULTS) { + ret.others.pop(); + } + } + } + return ret; + } + + /** + * Validate performs the following boolean logic. For example: + * "File::open" will give IF A PARENT EXISTS => ("file" && "open") + * exists in (name || path || parent) OR => ("file" && "open") exists in + * (name || path ) + * + * This could be written functionally, but I wanted to minimise + * functions on stack. + * + * @param {[string]} name [The name of the result] + * @param {[string]} path [The path of the result] + * @param {[string]} keys [The keys to be used (["file", "open"])] + * @param {[object]} parent [The parent of the result] + * @return {[boolean]} [Whether the result is valid or not] + */ + function validateResult(name, path, keys, parent) { + for (var i = 0; i < keys.length; ++i) { + // each check is for validation so we negate the conditions and invalidate + if (!( + // check for an exact name match + name.indexOf(keys[i]) > -1 || + // then an exact path match + path.indexOf(keys[i]) > -1 || + // next if there is a parent, check for exact parent match + (parent !== undefined && + parent.name.toLowerCase().indexOf(keys[i]) > -1) || + // lastly check to see if the name was a levenshtein match + levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) { + return false; + } + } + return true; + } + + function getQuery(raw) { + var matches, type, query; + query = raw; + + matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i); + if (matches) { + type = matches[1].replace(/^const$/, "constant"); + query = query.substring(matches[0].length); + } + + return { + raw: raw, + query: query, + type: type, + id: query + type + }; + } + + function initSearchNav() { + var hoverTimeout; + + var click_func = function(e) { + var el = e.target; + // to retrieve the real "owner" of the event. + while (el.tagName !== "TR") { + el = el.parentNode; + } + var dst = e.target.getElementsByTagName("a"); + if (dst.length < 1) { + return; + } + dst = dst[0]; + if (window.location.pathname === dst.pathname) { + addClass(document.getElementById("search"), "hidden"); + removeClass(main, "hidden"); + document.location.href = dst.href; + } + }; + var mouseover_func = function(e) { + var el = e.target; + // to retrieve the real "owner" of the event. + while (el.tagName !== "TR") { + el = el.parentNode; + } + clearTimeout(hoverTimeout); + hoverTimeout = setTimeout(function() { + onEachLazy(document.getElementsByClassName("search-results"), function(e) { + onEachLazy(e.getElementsByClassName("result"), function(i_e) { + removeClass(i_e, "highlighted"); + }); + }); + addClass(el, "highlighted"); + }, 20); + }; + onEachLazy(document.getElementsByClassName("search-results"), function(e) { + onEachLazy(e.getElementsByClassName("result"), function(i_e) { + i_e.onclick = click_func; + i_e.onmouseover = mouseover_func; + }); + }); + + search_input.onkeydown = function(e) { + // "actives" references the currently highlighted item in each search tab. + // Each array in "actives" represents a tab. + var actives = [[], [], []]; + // "current" is used to know which tab we're looking into. + var current = 0; + onEachLazy(document.getElementById("results").childNodes, function(e) { + onEachLazy(e.getElementsByClassName("highlighted"), function(e) { + actives[current].push(e); + }); + current += 1; + }); + + if (e.which === 38) { // up + if (!actives[currentTab].length || + !actives[currentTab][0].previousElementSibling) { + return; + } + + addClass(actives[currentTab][0].previousElementSibling, "highlighted"); + removeClass(actives[currentTab][0], "highlighted"); + } else if (e.which === 40) { // down + if (!actives[currentTab].length) { + var results = document.getElementById("results").childNodes; + if (results.length > 0) { + var res = results[currentTab].getElementsByClassName("result"); + if (res.length > 0) { + addClass(res[0], "highlighted"); + } + } + } else if (actives[currentTab][0].nextElementSibling) { + addClass(actives[currentTab][0].nextElementSibling, "highlighted"); + removeClass(actives[currentTab][0], "highlighted"); + } + } else if (e.which === 13) { // return + if (actives[currentTab].length) { + document.location.href = + actives[currentTab][0].getElementsByTagName("a")[0].href; + } + } else if (e.which === 9) { // tab + if (e.shiftKey) { + printTab(currentTab > 0 ? currentTab - 1 : 2); + } else { + printTab(currentTab > 1 ? 0 : currentTab + 1); + } + e.preventDefault(); + } else if (e.which === 16) { // shift + // Does nothing, it's just to avoid losing "focus" on the highlighted element. + } else if (e.which === 27) { // escape + removeClass(actives[currentTab][0], "highlighted"); + search_input.value = ""; + defocusSearchBar(); + } else if (actives[currentTab].length > 0) { + removeClass(actives[currentTab][0], "highlighted"); + } + }; + } + + function buildHrefAndPath(item) { + var displayPath; + var href; + var type = itemTypes[item.ty]; + var name = item.name; + + if (type === "mod") { + displayPath = item.path + "::"; + href = rootPath + item.path.replace(/::/g, "/") + "/" + + name + "/index.html"; + } else if (type === "primitive" || type === "keyword") { + displayPath = ""; + href = rootPath + item.path.replace(/::/g, "/") + + "/" + type + "." + name + ".html"; + } else if (type === "externcrate") { + displayPath = ""; + href = rootPath + name + "/index.html"; + } else if (item.parent !== undefined) { + var myparent = item.parent; + var anchor = "#" + type + "." + name; + var parentType = itemTypes[myparent.ty]; + if (parentType === "primitive") { + displayPath = myparent.name + "::"; + } else { + displayPath = item.path + "::" + myparent.name + "::"; + } + href = rootPath + item.path.replace(/::/g, "/") + + "/" + parentType + + "." + myparent.name + + ".html" + anchor; + } else { + displayPath = item.path + "::"; + href = rootPath + item.path.replace(/::/g, "/") + + "/" + type + "." + name + ".html"; + } + return [displayPath, href]; + } + + function escape(content) { + var h1 = document.createElement("h1"); + h1.textContent = content; + return h1.innerHTML; + } + + function pathSplitter(path) { + var tmp = "<span>" + path.replace(/::/g, "::</span><span>"); + if (tmp.endsWith("<span>")) { + return tmp.slice(0, tmp.length - 6); + } + return tmp; + } + + function addTab(array, query, display) { + var extraStyle = ""; + if (display === false) { + extraStyle = " style=\"display: none;\""; + } + + var output = ""; + var duplicates = {}; + var length = 0; + if (array.length > 0) { + output = "<table class=\"search-results\"" + extraStyle + ">"; + + array.forEach(function(item) { + var name, type; + + name = item.name; + type = itemTypes[item.ty]; + + if (item.is_alias !== true) { + if (duplicates[item.fullPath]) { + return; + } + duplicates[item.fullPath] = true; + } + length += 1; + + output += "<tr class=\"" + type + " result\"><td>" + + "<a href=\"" + item.href + "\">" + + (item.is_alias === true ? + ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " + + "class=\"grey\"><i> - see </i></span>") : "") + + item.displayPath + "<span class=\"" + type + "\">" + + name + "</span></a></td><td>" + + "<a href=\"" + item.href + "\">" + + "<span class=\"desc\">" + escape(item.desc) + + " </span></a></td></tr>"; + }); + output += "</table>"; + } else { + output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" + + "Try on <a href=\"https://duckduckgo.com/?q=" + + encodeURIComponent("rust " + query.query) + + "\">DuckDuckGo</a>?<br/><br/>" + + "Or try looking in one of these:<ul><li>The <a " + + "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " + + " for technical details about the language.</li><li><a " + + "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " + + "Example</a> for expository code examples.</a></li><li>The <a " + + "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " + + "introductions to language features and the language itself.</li><li><a " + + "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" + + " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>"; + } + return [output, length]; + } + + function makeTabHeader(tabNb, text, nbElems) { + if (currentTab === tabNb) { + return "<div class=\"selected\">" + text + + " <div class=\"count\">(" + nbElems + ")</div></div>"; + } + return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>"; + } + + function showResults(results) { + if (results.others.length === 1 && + getCurrentValue("rustdoc-go-to-only-result") === "true") { + var elem = document.createElement("a"); + elem.href = results.others[0].href; + elem.style.display = "none"; + // For firefox, we need the element to be in the DOM so it can be clicked. + document.body.appendChild(elem); + elem.click(); + } + var query = getQuery(search_input.value); + + currentResults = query.id; + + var ret_others = addTab(results.others, query); + var ret_in_args = addTab(results.in_args, query, false); + var ret_returned = addTab(results.returned, query, false); + + var output = "<h1>Results for " + escape(query.query) + + (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" + + "<div id=\"titles\">" + + makeTabHeader(0, "In Names", ret_others[1]) + + makeTabHeader(1, "In Parameters", ret_in_args[1]) + + makeTabHeader(2, "In Return Types", ret_returned[1]) + + "</div><div id=\"results\">" + + ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>"; + + addClass(main, "hidden"); + var search = document.getElementById("search"); + removeClass(search, "hidden"); + search.innerHTML = output; + var tds = search.getElementsByTagName("td"); + var td_width = 0; + if (tds.length > 0) { + td_width = tds[0].offsetWidth; + } + var width = search.offsetWidth - 40 - td_width; + onEachLazy(search.getElementsByClassName("desc"), function(e) { + e.style.width = width + "px"; + }); + initSearchNav(); + var elems = document.getElementById("titles").childNodes; + elems[0].onclick = function() { printTab(0); }; + elems[1].onclick = function() { printTab(1); }; + elems[2].onclick = function() { printTab(2); }; + printTab(currentTab); + } + + function execSearch(query, searchWords, filterCrates) { + function getSmallest(arrays, positions, notDuplicates) { + var start = null; + + for (var it = 0; it < positions.length; ++it) { + if (arrays[it].length > positions[it] && + (start === null || start > arrays[it][positions[it]].lev) && + !notDuplicates[arrays[it][positions[it]].fullPath]) { + start = arrays[it][positions[it]].lev; + } + } + return start; + } + + function mergeArrays(arrays) { + var ret = []; + var positions = []; + var notDuplicates = {}; + + for (var x = 0; x < arrays.length; ++x) { + positions.push(0); + } + while (ret.length < MAX_RESULTS) { + var smallest = getSmallest(arrays, positions, notDuplicates); + + if (smallest === null) { + break; + } + for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) { + if (arrays[x].length > positions[x] && + arrays[x][positions[x]].lev === smallest && + !notDuplicates[arrays[x][positions[x]].fullPath]) { + ret.push(arrays[x][positions[x]]); + notDuplicates[arrays[x][positions[x]].fullPath] = true; + positions[x] += 1; + } + } + } + return ret; + } + + var queries = query.raw.split(","); + var results = { + "in_args": [], + "returned": [], + "others": [], + }; + + for (var i = 0; i < queries.length; ++i) { + query = queries[i].trim(); + if (query.length !== 0) { + var tmp = execQuery(getQuery(query), searchWords, filterCrates); + + results.in_args.push(tmp.in_args); + results.returned.push(tmp.returned); + results.others.push(tmp.others); + } + } + if (queries.length > 1) { + return { + "in_args": mergeArrays(results.in_args), + "returned": mergeArrays(results.returned), + "others": mergeArrays(results.others), + }; + } else { + return { + "in_args": results.in_args[0], + "returned": results.returned[0], + "others": results.others[0], + }; + } + } + + function getFilterCrates() { + var elem = document.getElementById("crate-search"); + + if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) { + return elem.value; + } + return undefined; + } + + function search(e, forced) { + var params = getQueryStringParams(); + var query = getQuery(search_input.value.trim()); + + if (e) { + e.preventDefault(); + } + + if (query.query.length === 0) { + return; + } + if (forced !== true && query.id === currentResults) { + if (query.query.length > 0) { + putBackSearch(search_input); + } + return; + } + + // Update document title to maintain a meaningful browser history + document.title = "Results for " + query.query + " - Rust"; + + // Because searching is incremental by character, only the most + // recent search query is added to the browser history. + if (browserSupportsHistoryApi()) { + if (!history.state && !params.search) { + history.pushState(query, "", "?search=" + encodeURIComponent(query.raw)); + } else { + history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw)); + } + } + + var filterCrates = getFilterCrates(); + showResults(execSearch(query, index, filterCrates), filterCrates); + } + + function buildIndex(rawSearchIndex) { + searchIndex = []; + var searchWords = []; + var i; + + for (var crate in rawSearchIndex) { + if (!rawSearchIndex.hasOwnProperty(crate)) { continue; } + + searchWords.push(crate); + searchIndex.push({ + crate: crate, + ty: 1, // == ExternCrate + name: crate, + path: "", + desc: rawSearchIndex[crate].doc, + type: null, + }); + + // an array of [(Number) item type, + // (String) name, + // (String) full path or empty string for previous path, + // (String) description, + // (Number | null) the parent path index to `paths`] + // (Object | null) the type of the function (if any) + var items = rawSearchIndex[crate].i; + // an array of [(Number) item type, + // (String) name] + var paths = rawSearchIndex[crate].p; + + // convert `paths` into an object form + var len = paths.length; + for (i = 0; i < len; ++i) { + paths[i] = {ty: paths[i][0], name: paths[i][1]}; + } + + // convert `items` into an object form, and construct word indices. + // + // before any analysis is performed lets gather the search terms to + // search against apart from the rest of the data. This is a quick + // operation that is cached for the life of the page state so that + // all other search operations have access to this cached data for + // faster analysis operations + len = items.length; + var lastPath = ""; + for (i = 0; i < len; ++i) { + var rawRow = items[i]; + var row = {crate: crate, ty: rawRow[0], name: rawRow[1], + path: rawRow[2] || lastPath, desc: rawRow[3], + parent: paths[rawRow[4]], type: rawRow[5]}; + searchIndex.push(row); + if (typeof row.name === "string") { + var word = row.name.toLowerCase(); + searchWords.push(word); + } else { + searchWords.push(""); + } + lastPath = row.path; + } + } + return searchWords; + } + + function startSearch() { + var searchTimeout; + var callback = function() { + clearTimeout(searchTimeout); + if (search_input.value.length === 0) { + if (browserSupportsHistoryApi()) { + history.replaceState("", window.currentCrate + " - Rust", "?search="); + } + if (hasClass(main, "content")) { + removeClass(main, "hidden"); + } + var search_c = document.getElementById("search"); + if (hasClass(search_c, "content")) { + addClass(search_c, "hidden"); + } + } else { + searchTimeout = setTimeout(search, 500); + } + }; + search_input.onkeyup = callback; + search_input.oninput = callback; + document.getElementsByClassName("search-form")[0].onsubmit = function(e) { + e.preventDefault(); + clearTimeout(searchTimeout); + search(); + }; + search_input.onchange = function(e) { + // Do NOT e.preventDefault() here. It will prevent pasting. + clearTimeout(searchTimeout); + // zero-timeout necessary here because at the time of event handler execution the + // pasted content is not in the input field yet. Shouldn’t make any difference for + // change, though. + setTimeout(search, 0); + }; + search_input.onpaste = search_input.onchange; + + var selectCrate = document.getElementById('crate-search'); + if (selectCrate) { + selectCrate.onchange = function() { + search(undefined, true); + }; + } + + // Push and pop states are used to add search results to the browser + // history. + if (browserSupportsHistoryApi()) { + // Store the previous <title> so we can revert back to it later. + var previousTitle = document.title; + + window.onpopstate = function(e) { + var params = getQueryStringParams(); + // When browsing back from search results the main page + // visibility must be reset. + if (!params.search) { + if (hasClass(main, "content")) { + removeClass(main, "hidden"); + } + var search_c = document.getElementById("search"); + if (hasClass(search_c, "content")) { + addClass(search_c, "hidden"); + } + } + // Revert to the previous title manually since the History + // API ignores the title parameter. + document.title = previousTitle; + // When browsing forward to search results the previous + // search will be repeated, so the currentResults are + // cleared to ensure the search is successful. + currentResults = null; + // Synchronize search bar with query string state and + // perform the search. This will empty the bar if there's + // nothing there, which lets you really go back to a + // previous state with nothing in the bar. + if (params.search) { + search_input.value = params.search; + } else { + search_input.value = ""; + } + // Some browsers fire "onpopstate" for every page load + // (Chrome), while others fire the event only when actually + // popping a state (Firefox), which is why search() is + // called both here and at the end of the startSearch() + // function. + search(); + }; + } + search(); + } + + index = buildIndex(rawSearchIndex); + startSearch(); + + // Draw a convenient sidebar of known crates if we have a listing + if (rootPath === "../" || rootPath === "./") { + var sidebar = document.getElementsByClassName("sidebar-elems")[0]; + if (sidebar) { + var div = document.createElement("div"); + div.className = "block crate"; + div.innerHTML = "<h3>Crates</h3>"; + var ul = document.createElement("ul"); + div.appendChild(ul); + + var crates = []; + for (var crate in rawSearchIndex) { + if (!rawSearchIndex.hasOwnProperty(crate)) { + continue; + } + crates.push(crate); + } + crates.sort(); + for (var i = 0; i < crates.length; ++i) { + var klass = "crate"; + if (rootPath !== "./" && crates[i] === window.currentCrate) { + klass += " current"; + } + var link = document.createElement("a"); + link.href = rootPath + crates[i] + "/index.html"; + link.title = rawSearchIndex[crates[i]].doc; + link.className = klass; + link.textContent = crates[i]; + + var li = document.createElement("li"); + li.appendChild(link); + ul.appendChild(li); + } + sidebar.appendChild(div); + } + } + } + + window.initSearch = initSearch; + + // delayed sidebar rendering. + function initSidebarItems(items) { + var sidebar = document.getElementsByClassName("sidebar-elems")[0]; + var current = window.sidebarCurrent; + + function block(shortty, longty) { + var filtered = items[shortty]; + if (!filtered) { + return; + } + + var div = document.createElement("div"); + div.className = "block " + shortty; + var h3 = document.createElement("h3"); + h3.textContent = longty; + div.appendChild(h3); + var ul = document.createElement("ul"); + + var length = filtered.length; + for (var i = 0; i < length; ++i) { + var item = filtered[i]; + var name = item[0]; + var desc = item[1]; // can be null + + var klass = shortty; + if (name === current.name && shortty === current.ty) { + klass += " current"; + } + var path; + if (shortty === "mod") { + path = name + "/index.html"; + } else { + path = shortty + "." + name + ".html"; + } + var link = document.createElement("a"); + link.href = current.relpath + path; + link.title = desc; + link.className = klass; + link.textContent = name; + var li = document.createElement("li"); + li.appendChild(link); + ul.appendChild(li); + } + div.appendChild(ul); + if (sidebar) { + sidebar.appendChild(div); + } + } + + block("primitive", "Primitive Types"); + block("mod", "Modules"); + block("macro", "Macros"); + block("struct", "Structs"); + block("enum", "Enums"); + block("union", "Unions"); + block("constant", "Constants"); + block("static", "Statics"); + block("trait", "Traits"); + block("fn", "Functions"); + block("type", "Type Definitions"); + block("foreigntype", "Foreign Types"); + block("keyword", "Keywords"); + block("traitalias", "Trait Aliases"); + } + + window.initSidebarItems = initSidebarItems; + + window.register_implementors = function(imp) { + var implementors = document.getElementById("implementors-list"); + var synthetic_implementors = document.getElementById("synthetic-implementors-list"); + + var libs = Object.getOwnPropertyNames(imp); + var llength = libs.length; + for (var i = 0; i < llength; ++i) { + if (libs[i] === currentCrate) { continue; } + var structs = imp[libs[i]]; + + var slength = structs.length; + struct_loop: + for (var j = 0; j < slength; ++j) { + var struct = structs[j]; + + var list = struct.synthetic ? synthetic_implementors : implementors; + + if (struct.synthetic) { + var stlength = struct.types.length; + for (var k = 0; k < stlength; k++) { + if (window.inlined_types.has(struct.types[k])) { + continue struct_loop; + } + window.inlined_types.add(struct.types[k]); + } + } + + var code = document.createElement("code"); + code.innerHTML = struct.text; + + var x = code.getElementsByTagName("a"); + var xlength = x.length; + for (var it = 0; it < xlength; it++) { + var href = x[it].getAttribute("href"); + if (href && href.indexOf("http") !== 0) { + x[it].setAttribute("href", rootPath + href); + } + } + var display = document.createElement("h3"); + addClass(display, "impl"); + display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" + + "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" + + "</tbody></table></span>"; + list.appendChild(display); + } + } + }; + if (window.pending_implementors) { + window.register_implementors(window.pending_implementors); + } + + function labelForToggleButton(sectionIsCollapsed) { + if (sectionIsCollapsed) { + // button will expand the section + return "+"; + } + // button will collapse the section + // note that this text is also set in the HTML template in render.rs + return "\u2212"; // "\u2212" is "−" minus sign + } + + function onEveryMatchingChild(elem, className, func) { + if (elem && className && func) { + var length = elem.childNodes.length; + var nodes = elem.childNodes; + for (var i = 0; i < length; ++i) { + if (hasClass(nodes[i], className)) { + func(nodes[i]); + } else { + onEveryMatchingChild(nodes[i], className, func); + } + } + } + } + + function toggleAllDocs(pageId, fromAutoCollapse) { + var innerToggle = document.getElementById("toggle-all-docs"); + if (!innerToggle) { + return; + } + if (hasClass(innerToggle, "will-expand")) { + updateLocalStorage("rustdoc-collapse", "false"); + removeClass(innerToggle, "will-expand"); + onEveryMatchingChild(innerToggle, "inner", function(e) { + e.innerHTML = labelForToggleButton(false); + }); + innerToggle.title = "collapse all docs"; + if (fromAutoCollapse !== true) { + onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) { + collapseDocs(e, "show"); + }); + } + } else { + updateLocalStorage("rustdoc-collapse", "true"); + addClass(innerToggle, "will-expand"); + onEveryMatchingChild(innerToggle, "inner", function(e) { + var parent = e.parentNode; + var superParent = null; + + if (parent) { + superParent = parent.parentNode; + } + if (!parent || !superParent || superParent.id !== "main" || + hasClass(parent, "impl") === false) { + e.innerHTML = labelForToggleButton(true); + } + }); + innerToggle.title = "expand all docs"; + if (fromAutoCollapse !== true) { + onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) { + var parent = e.parentNode; + var superParent = null; + + if (parent) { + superParent = parent.parentNode; + } + if (!parent || !superParent || superParent.id !== "main" || + hasClass(parent, "impl") === false) { + collapseDocs(e, "hide", pageId); + } + }); + } + } + } + + function collapseDocs(toggle, mode, pageId) { + if (!toggle || !toggle.parentNode) { + return; + } + + function adjustToggle(arg) { + return function(e) { + if (hasClass(e, "toggle-label")) { + if (arg) { + e.style.display = "inline-block"; + } else { + e.style.display = "none"; + } + } + if (hasClass(e, "inner")) { + e.innerHTML = labelForToggleButton(arg); + } + }; + } + + function implHider(addOrRemove, fullHide) { + return function(n) { + var is_method = hasClass(n, "method") || fullHide; + if (is_method || hasClass(n, "type")) { + if (is_method === true) { + if (addOrRemove) { + addClass(n, "hidden-by-impl-hider"); + } else { + removeClass(n, "hidden-by-impl-hider"); + } + } + var ns = n.nextElementSibling; + while (true) { + if (ns && ( + hasClass(ns, "docblock") || + hasClass(ns, "stability"))) { + if (addOrRemove) { + addClass(ns, "hidden-by-impl-hider"); + } else { + removeClass(ns, "hidden-by-impl-hider"); + } + ns = ns.nextElementSibling; + continue; + } + break; + } + } + }; + } + + var relatedDoc; + var action = mode; + if (hasClass(toggle.parentNode, "impl") === false) { + relatedDoc = toggle.parentNode.nextElementSibling; + if (hasClass(relatedDoc, "stability")) { + relatedDoc = relatedDoc.nextElementSibling; + } + if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) { + if (mode === "toggle") { + if (hasClass(relatedDoc, "hidden-by-usual-hider")) { + action = "show"; + } else { + action = "hide"; + } + } + if (action === "hide") { + addClass(relatedDoc, "hidden-by-usual-hider"); + onEachLazy(toggle.childNodes, adjustToggle(true)); + addClass(toggle.parentNode, "collapsed"); + } else if (action === "show") { + removeClass(relatedDoc, "hidden-by-usual-hider"); + removeClass(toggle.parentNode, "collapsed"); + onEachLazy(toggle.childNodes, adjustToggle(false)); + } + } + } else { + // we are collapsing the impl block(s). + + var parentElem = toggle.parentNode; + relatedDoc = parentElem; + var docblock = relatedDoc.nextElementSibling; + + while (hasClass(relatedDoc, "impl-items") === false) { + relatedDoc = relatedDoc.nextElementSibling; + } + + if ((!relatedDoc && hasClass(docblock, "docblock") === false) || + (pageId && document.getElementById(pageId))) { + return; + } + + // Hide all functions, but not associated types/consts. + + if (mode === "toggle") { + if (hasClass(relatedDoc, "fns-now-collapsed") || + hasClass(docblock, "hidden-by-impl-hider")) { + action = "show"; + } else { + action = "hide"; + } + } + + var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main"; + if (action === "show") { + removeClass(relatedDoc, "fns-now-collapsed"); + removeClass(docblock, "hidden-by-usual-hider"); + onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule)); + onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule)); + } else if (action === "hide") { + addClass(relatedDoc, "fns-now-collapsed"); + addClass(docblock, "hidden-by-usual-hider"); + onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule)); + onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule)); + } + } + } + + function collapser(e, collapse) { + // inherent impl ids are like "impl" or impl-<number>'. + // they will never be hidden by default. + var n = e.parentElement; + if (n.id.match(/^impl(?:-\d+)?$/) === null) { + // Automatically minimize all non-inherent impls + if (collapse || hasClass(n, "impl")) { + collapseDocs(e, "hide", pageId); + } + } + } + + function autoCollapse(pageId, collapse) { + if (collapse) { + toggleAllDocs(pageId, true); + } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") { + var impl_list = document.getElementById("implementations-list"); + + if (impl_list !== null) { + onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) { + collapser(e, collapse); + }); + } + + var blanket_list = document.getElementById("blanket-implementations-list"); + + if (blanket_list !== null) { + onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) { + collapser(e, collapse); + }); + } + } + } + + var toggles = document.getElementById("toggle-all-docs"); + if (toggles) { + toggles.onclick = toggleAllDocs; + } + + function insertAfter(newNode, referenceNode) { + referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); + } + + function createSimpleToggle(sectionIsCollapsed) { + var toggle = document.createElement("a"); + toggle.href = "javascript:void(0)"; + toggle.className = "collapse-toggle"; + toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) + + "</span>]"; + return toggle; + } + + var toggle = createSimpleToggle(false); + var hideMethodDocs = getCurrentValue("rustdoc-method-docs") === "true"; + var pageId = getPageId(); + + var func = function(e) { + var next = e.nextElementSibling; + if (!next) { + return; + } + if (hasClass(next, "docblock") === true || + (hasClass(next, "stability") === true && + hasClass(next.nextElementSibling, "docblock") === true)) { + var newToggle = toggle.cloneNode(true); + insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]); + if (hideMethodDocs === true && hasClass(e, "method") === true) { + collapseDocs(newToggle, "hide", pageId); + } + } + }; + + var funcImpl = function(e) { + var next = e.nextElementSibling; + if (next && hasClass(next, "docblock")) { + next = next.nextElementSibling; + } + if (!next) { + return; + } + if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) { + insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]); + } + }; + + onEachLazy(document.getElementsByClassName("method"), func); + onEachLazy(document.getElementsByClassName("associatedconstant"), func); + onEachLazy(document.getElementsByClassName("impl"), funcImpl); + var impl_call = function() {}; + if (hideMethodDocs === true) { + impl_call = function(e, newToggle, pageId) { + if (e.id.match(/^impl(?:-\d+)?$/) === null) { + // Automatically minimize all non-inherent impls + if (hasClass(e, "impl") === true) { + collapseDocs(newToggle, "hide", pageId); + } + } + }; + } + var newToggle = document.createElement("a"); + newToggle.href = "javascript:void(0)"; + newToggle.className = "collapse-toggle hidden-default collapsed"; + newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) + + "</span>] Show hidden undocumented items"; + function toggleClicked() { + if (hasClass(this, "collapsed")) { + removeClass(this, "collapsed"); + onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) { + if (hasClass(x, "content") === false) { + removeClass(x, "hidden"); + addClass(x, "x"); + } + }, true); + this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) + + "</span>] Hide undocumented items"; + } else { + addClass(this, "collapsed"); + onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) { + if (hasClass(x, "content") === false) { + addClass(x, "hidden"); + removeClass(x, "x"); + } + }, true); + this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) + + "</span>] Show hidden undocumented items"; + } + } + onEachLazy(document.getElementsByClassName("impl-items"), function(e) { + onEachLazy(e.getElementsByClassName("associatedconstant"), func); + var hiddenElems = e.getElementsByClassName("hidden"); + var needToggle = false; + + var hlength = hiddenElems.length; + for (var i = 0; i < hlength; ++i) { + if (hasClass(hiddenElems[i], "content") === false && + hasClass(hiddenElems[i], "docblock") === false) { + needToggle = true; + break; + } + } + if (needToggle === true) { + var inner_toggle = newToggle.cloneNode(true); + inner_toggle.onclick = toggleClicked; + e.insertBefore(inner_toggle, e.firstChild); + impl_call(e.previousSibling, inner_toggle, pageId); + } + }); + + function createToggle(otherMessage, fontSize, extraClass, show) { + var span = document.createElement("span"); + span.className = "toggle-label"; + if (show) { + span.style.display = "none"; + } + if (!otherMessage) { + span.innerHTML = " Expand description"; + } else { + span.innerHTML = otherMessage; + } + + if (fontSize) { + span.style.fontSize = fontSize; + } + + var mainToggle = toggle.cloneNode(true); + mainToggle.appendChild(span); + + var wrapper = document.createElement("div"); + wrapper.className = "toggle-wrapper"; + if (!show) { + addClass(wrapper, "collapsed"); + var inner = mainToggle.getElementsByClassName("inner"); + if (inner && inner.length > 0) { + inner[0].innerHTML = "+"; + } + } + if (extraClass) { + addClass(wrapper, extraClass); + } + wrapper.appendChild(mainToggle); + return wrapper; + } + + var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false"; + function buildToggleWrapper(e) { + if (hasClass(e, "autohide")) { + var wrap = e.previousElementSibling; + if (wrap && hasClass(wrap, "toggle-wrapper")) { + var inner_toggle = wrap.childNodes[0]; + var extra = e.childNodes[0].tagName === "H3"; + + e.style.display = "none"; + addClass(wrap, "collapsed"); + onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) { + e.innerHTML = labelForToggleButton(true); + }); + onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) { + e.style.display = "inline-block"; + if (extra === true) { + i_e.innerHTML = " Show " + e.childNodes[0].innerHTML; + } + }); + } + } + if (e.parentNode.id === "main") { + var otherMessage = ""; + var fontSize; + var extraClass; + + if (hasClass(e, "type-decl")) { + fontSize = "20px"; + otherMessage = " Show declaration"; + if (showItemDeclarations === false) { + extraClass = "collapsed"; + } + } else if (hasClass(e, "sub-variant")) { + otherMessage = " Show fields"; + } else if (hasClass(e, "non-exhaustive")) { + otherMessage = " This "; + if (hasClass(e, "non-exhaustive-struct")) { + otherMessage += "struct"; + } else if (hasClass(e, "non-exhaustive-enum")) { + otherMessage += "enum"; + } else if (hasClass(e, "non-exhaustive-variant")) { + otherMessage += "enum variant"; + } else if (hasClass(e, "non-exhaustive-type")) { + otherMessage += "type"; + } + otherMessage += " is marked as non-exhaustive"; + } else if (hasClass(e.childNodes[0], "impl-items")) { + extraClass = "marg-left"; + } + + e.parentNode.insertBefore( + createToggle(otherMessage, + fontSize, + extraClass, + hasClass(e, "type-decl") === false || showItemDeclarations === true), + e); + if (hasClass(e, "type-decl") === true && showItemDeclarations === true) { + collapseDocs(e.previousSibling.childNodes[0], "toggle"); + } + if (hasClass(e, "non-exhaustive") === true) { + collapseDocs(e.previousSibling.childNodes[0], "toggle"); + } + } + } + + onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper); + onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper); + + function createToggleWrapper(tog) { + var span = document.createElement("span"); + span.className = "toggle-label"; + span.style.display = "none"; + span.innerHTML = " Expand attributes"; + tog.appendChild(span); + + var wrapper = document.createElement("div"); + wrapper.className = "toggle-wrapper toggle-attributes"; + wrapper.appendChild(tog); + return wrapper; + } + + // To avoid checking on "rustdoc-item-attributes" value on every loop... + var itemAttributesFunc = function() {}; + if (getCurrentValue("rustdoc-item-attributes") !== "false") { + itemAttributesFunc = function(x) { + collapseDocs(x.previousSibling.childNodes[0], "toggle"); + }; + } + var attributesToggle = createToggleWrapper(createSimpleToggle(false)); + onEachLazy(main.getElementsByClassName("attributes"), function(i_e) { + var attr_tog = attributesToggle.cloneNode(true); + if (hasClass(i_e, "top-attr") === true) { + addClass(attr_tog, "top-attr"); + } + i_e.parentNode.insertBefore(attr_tog, i_e); + itemAttributesFunc(i_e); + }); + + // To avoid checking on "rustdoc-line-numbers" value on every loop... + var lineNumbersFunc = function() {}; + if (getCurrentValue("rustdoc-line-numbers") === "true") { + lineNumbersFunc = function(x) { + var count = x.textContent.split("\n").length; + var elems = []; + for (var i = 0; i < count; ++i) { + elems.push(i + 1); + } + var node = document.createElement("pre"); + addClass(node, "line-number"); + node.innerHTML = elems.join("\n"); + x.parentNode.insertBefore(node, x); + }; + } + onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) { + if (hasClass(e, "compile_fail")) { + e.addEventListener("mouseover", function(event) { + this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00"; + }); + e.addEventListener("mouseout", function(event) { + this.parentElement.previousElementSibling.childNodes[0].style.color = ""; + }); + } else if (hasClass(e, "ignore")) { + e.addEventListener("mouseover", function(event) { + this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200"; + }); + e.addEventListener("mouseout", function(event) { + this.parentElement.previousElementSibling.childNodes[0].style.color = ""; + }); + } + lineNumbersFunc(e); + }); + + function showModal(content) { + var modal = document.createElement("div"); + modal.id = "important"; + addClass(modal, "modal"); + modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" + + "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content + + "</span></div>"; + document.getElementsByTagName("body")[0].appendChild(modal); + document.getElementById("modal-close").onclick = hideModal; + modal.onclick = hideModal; + } + + function hideModal() { + var modal = document.getElementById("important"); + if (modal) { + modal.parentNode.removeChild(modal); + } + } + + onEachLazy(document.getElementsByClassName("important-traits"), function(e) { + e.onclick = function() { + showModal(e.lastElementChild.innerHTML); + }; + }); + + // In the search display, allows to switch between tabs. + function printTab(nb) { + if (nb === 0 || nb === 1 || nb === 2) { + currentTab = nb; + } + var nb_copy = nb; + onEachLazy(document.getElementById("titles").childNodes, function(elem) { + if (nb_copy === 0) { + addClass(elem, "selected"); + } else { + removeClass(elem, "selected"); + } + nb_copy -= 1; + }); + onEachLazy(document.getElementById("results").childNodes, function(elem) { + if (nb === 0) { + elem.style.display = ""; + } else { + elem.style.display = "none"; + } + nb -= 1; + }); + } + + function putBackSearch(search_input) { + if (search_input.value !== "") { + addClass(main, "hidden"); + removeClass(document.getElementById("search"), "hidden"); + if (browserSupportsHistoryApi()) { + history.replaceState(search_input.value, + "", + "?search=" + encodeURIComponent(search_input.value)); + } + } + } + + if (search_input) { + search_input.onfocus = function() { + putBackSearch(this); + }; + } + + var params = getQueryStringParams(); + if (params && params.search) { + addClass(main, "hidden"); + var search = document.getElementById("search"); + removeClass(search, "hidden"); + search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>"; + } + + var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0]; + if (sidebar_menu) { + sidebar_menu.onclick = function() { + var sidebar = document.getElementsByClassName("sidebar")[0]; + if (hasClass(sidebar, "mobile") === true) { + hideSidebar(); + } else { + showSidebar(); + } + }; + } + + window.onresize = function() { + hideSidebar(); + }; + + autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true"); + + if (window.location.hash && window.location.hash.length > 0) { + expandSection(window.location.hash.replace(/^#/, "")); + } + + if (main) { + onEachLazy(main.getElementsByClassName("loading-content"), function(e) { + e.remove(); + }); + onEachLazy(main.childNodes, function(e) { + // Unhide the actual content once loading is complete. Headers get + // flex treatment for their horizontal layout, divs get block treatment + // for vertical layout (column-oriented flex layout for divs caused + // errors in mobile browsers). + if (e.tagName === "H2" || e.tagName === "H3") { + var nextTagName = e.nextElementSibling.tagName; + if (nextTagName == "H2" || nextTagName == "H3") { + e.nextElementSibling.style.display = "flex"; + } else { + e.nextElementSibling.style.display = "block"; + } + } + }); + } + + function addSearchOptions(crates) { + var elem = document.getElementById('crate-search'); + + if (!elem) { + return; + } + var crates_text = []; + if (Object.keys(crates).length > 1) { + for (var crate in crates) { + if (crates.hasOwnProperty(crate)) { + crates_text.push(crate); + } + } + } + crates_text.sort(function(a, b) { + var lower_a = a.toLowerCase(); + var lower_b = b.toLowerCase(); + + if (lower_a < lower_b) { + return -1; + } else if (lower_a > lower_b) { + return 1; + } + return 0; + }); + for (var i = 0; i < crates_text.length; ++i) { + var option = document.createElement("option"); + option.value = crates_text[i]; + option.innerText = crates_text[i]; + elem.appendChild(option); + } + } + + window.addSearchOptions = addSearchOptions; +}()); + +// Sets the focus on the search bar at the top of the page +function focusSearchBar() { + document.getElementsByClassName("search-input")[0].focus(); +} + +// Removes the focus from the search bar +function defocusSearchBar() { + document.getElementsByClassName("search-input")[0].blur(); +} diff --git a/vendor/minifier/tests/files/minified_main.js b/vendor/minifier/tests/files/minified_main.js new file mode 100644 index 000000000..37ffbe201 --- /dev/null +++ b/vendor/minifier/tests/files/minified_main.js @@ -0,0 +1 @@ +if(!String.prototype.startsWith){String.prototype.startsWith=function(searchString,position){position=position||0;return this.indexOf(searchString,position)===position}}if(!String.prototype.endsWith){String.prototype.endsWith=function(suffix,length){var l=length||this.length;return this.indexOf(suffix,l-suffix.length)!==-1}}if(!DOMTokenList.prototype.add){DOMTokenList.prototype.add=function(className){if(className&&!hasClass(this,className)){if(this.className&&this.className.length>0){this.className+=" "+className}else{this.className=className}}}}if(!DOMTokenList.prototype.remove){DOMTokenList.prototype.remove=function(className){if(className&&this.className){this.className=(" "+this.className+" ").replace(" "+className+" "," ").trim()}}}(function(){"use strict";var itemTypes=["mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","primitive","associatedtype","constant","associatedconstant","union","foreigntype","keyword","existential","attr","derive","traitalias"];var search_input=document.getElementsByClassName("search-input")[0];var currentTab=0;var titleBeforeSearch=document.title;function getPageId(){var id=document.location.href.split("#")[1];if(id){return id.split("?")[0].split("&")[0]}return null}function showSidebar(){var elems=document.getElementsByClassName("sidebar-elems")[0];if(elems){addClass(elems,"show-it")}var sidebar=document.getElementsByClassName("sidebar")[0];if(sidebar){addClass(sidebar,"mobile");var filler=document.getElementById("sidebar-filler");if(!filler){var div=document.createElement("div");div.id="sidebar-filler";sidebar.appendChild(div)}}var themePicker=document.getElementsByClassName("theme-picker");if(themePicker&&themePicker.length>0){themePicker[0].style.display="none"}}function hideSidebar(){var elems=document.getElementsByClassName("sidebar-elems")[0];if(elems){removeClass(elems,"show-it")}var sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"mobile");var filler=document.getElementById("sidebar-filler");if(filler){filler.remove()}document.getElementsByTagName("body")[0].style.marginTop="";var themePicker=document.getElementsByClassName("theme-picker");if(themePicker&&themePicker.length>0){themePicker[0].style.display=null}}var TY_PRIMITIVE=itemTypes.indexOf("primitive");var TY_KEYWORD=itemTypes.indexOf("keyword");onEachLazy(document.getElementsByClassName("js-only"),function(e){removeClass(e,"js-only")});function getQueryStringParams(){var params={};window.location.search.substring(1).split("&").map(function(s){var pair=s.split("=");params[decodeURIComponent(pair[0])]=typeof pair[1]==="undefined"?null:decodeURIComponent(pair[1])});return params}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}var main=document.getElementById("main");function highlightSourceLines(ev){hideSidebar();var elem;var search=document.getElementById("search");var i,from,to,match=window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);if(match){from=parseInt(match[1],10);to=from;if(typeof match[2]!=="undefined"){to=parseInt(match[2],10)}if(to<from){var tmp=to;to=from;from=tmp}elem=document.getElementById(from);if(!elem){return}if(ev===null){var x=document.getElementById(from);if(x){x.scrollIntoView()}}onEachLazy(document.getElementsByClassName("line-numbers"),function(e){onEachLazy(e.getElementsByTagName("span"),function(i_e){removeClass(i_e,"line-highlighted")})});for(i=from;i<=to;++i){elem=document.getElementById(i);if(!elem){break}addClass(elem,"line-highlighted")}}else if(ev!==null&&search&&!hasClass(search,"hidden")&&ev.newURL){addClass(search,"hidden");removeClass(main,"hidden");var hash=ev.newURL.slice(ev.newURL.indexOf("#")+1);if(browserSupportsHistoryApi()){history.replaceState(hash,"","?search=#"+hash)}elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}}function expandSection(id){var elem=document.getElementById(id);if(elem&&isHidden(elem)){var h3=elem.parentNode.previousElementSibling;if(h3&&h3.tagName!=="H3"){h3=h3.previousElementSibling}if(h3){var collapses=h3.getElementsByClassName("collapse-toggle");if(collapses.length>0){collapseDocs(collapses[0],"show")}}}}highlightSourceLines(null);window.onhashchange=highlightSourceLines;function getVirtualKey(ev){if("key"in ev&&typeof ev.key!="undefined"){return ev.key}var c=ev.charCode||ev.keyCode;if(c==27){return"Escape"}return String.fromCharCode(c)}function displayHelp(display,ev,help){if(display===true){if(hasClass(help,"hidden")){ev.preventDefault();removeClass(help,"hidden");addClass(document.body,"blur")}}else if(hasClass(help,"hidden")===false){ev.preventDefault();addClass(help,"hidden");removeClass(document.body,"blur")}}function handleEscape(ev,help){hideModal();var search=document.getElementById("search");if(hasClass(help,"hidden")===false){displayHelp(false,ev,help)}else if(hasClass(search,"hidden")===false){ev.preventDefault();addClass(search,"hidden");removeClass(main,"hidden");document.title=titleBeforeSearch}defocusSearchBar()}function handleShortcut(ev){if(ev.ctrlKey||ev.altKey||ev.metaKey){return}var help=document.getElementById("help");if(document.activeElement.tagName==="INPUT"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev,help);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev,help);break;case"s":case"S":displayHelp(false,ev,help);hideModal();ev.preventDefault();focusSearchBar();break;case"+":case"-":ev.preventDefault();toggleAllDocs();break;case"?":if(ev.shiftKey){hideModal();displayHelp(true,ev,help)}break}}}function findParentElement(elem,tagName){do{if(elem&&elem.tagName===tagName){return elem}elem=elem.parentNode}while(elem);return null}document.onkeypress=handleShortcut;document.onkeydown=handleShortcut;document.onclick=function(ev){if(hasClass(ev.target,"collapse-toggle")){collapseDocs(ev.target,"toggle")}else if(hasClass(ev.target.parentNode,"collapse-toggle")){collapseDocs(ev.target.parentNode,"toggle")}else if(ev.target.tagName==="SPAN"&&hasClass(ev.target.parentNode,"line-numbers")){var prev_id=0;var set_fragment=function(name){if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);window.hashchange()}else{location.replace("#"+name)}};var cur_id=parseInt(ev.target.id,10);if(ev.shiftKey&&prev_id){if(prev_id>cur_id){var tmp=prev_id;prev_id=cur_id;cur_id=tmp}set_fragment(prev_id+"-"+cur_id)}else{prev_id=cur_id;set_fragment(cur_id)}}else if(hasClass(document.getElementById("help"),"hidden")===false){addClass(document.getElementById("help"),"hidden");removeClass(document.body,"blur")}else{var a=findParentElement(ev.target,"A");if(a&&a.hash){expandSection(a.hash.replace(/^#/,""))}}};var x=document.getElementsByClassName("version-selector");if(x.length>0){x[0].onchange=function(){var i,match,url=document.location.href,stripped="",len=rootPath.match(/\.\.\//g).length+1;for(i=0;i<len;++i){match=url.match(/\/[^\/]*$/);if(i<len-1){stripped=match[0]+stripped}url=url.substring(0,url.length-match[0].length)}url+="/"+document.getElementsByClassName("version-selector")[0].value+stripped;document.location.href=url}}var levenshtein_row2=[];function levenshtein(s1,s2){if(s1===s2){return 0}var s1_len=s1.length,s2_len=s2.length;if(s1_len&&s2_len){var i1=0,i2=0,a,b,c,c2,row=levenshtein_row2;while(i1<s1_len){row[i1]=++i1}while(i2<s2_len){c2=s2.charCodeAt(i2);a=i2;++i2;b=i2;for(i1=0;i1<s1_len;++i1){c=a+(s1.charCodeAt(i1)!==c2?1:0);a=row[i1];b=b<a?(b<c?b+1:c):(a<c?a+1:c);row[i1]=b}}return b}return s1_len+s2_len}function initSearch(rawSearchIndex){var currentResults,index,searchIndex;var MAX_LEV_DISTANCE=3;var MAX_RESULTS=200;var GENERICS_DATA=1;var NAME=0;var INPUTS_DATA=0;var OUTPUT_DATA=1;var params=getQueryStringParams();if(search_input.value===""){search_input.value=params.search||""}function execQuery(query,searchWords,filterCrates){function itemTypeFromName(typename){var length=itemTypes.length;for(var i=0;i<length;++i){if(itemTypes[i]===typename){return i}}return-1}var valLower=query.query.toLowerCase(),val=valLower,typeFilter=itemTypeFromName(query.type),results={},results_in_args={},results_returned={},split=valLower.split("::");var length=split.length;for(var z=0;z<length;++z){if(split[z]===""){split.splice(z,1);z-=1}}function transformResults(results,isType){var out=[];var length=results.length;for(var i=0;i<length;++i){if(results[i].id>-1){var obj=searchIndex[results[i].id];obj.lev=results[i].lev;if(isType!==true||obj.type){var res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=obj.displayPath+obj.name;obj.fullPath+="|"+obj.ty;obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}}return out}function sortResults(results,isType){var ar=[];for(var entry in results){if(results.hasOwnProperty(entry)){ar.push(results[entry])}}results=ar;var i;var nresults=results.length;for(i=0;i<nresults;++i){results[i].word=searchWords[results[i].id];results[i].item=searchIndex[results[i].id]||{}}if(results.length===0){return[]}results.sort(function(aaa,bbb){var a,b;a=(aaa.lev);b=(bbb.lev);if(a!==b){return a-b}a=(aaa.item.crate!==window.currentCrate);b=(bbb.item.crate!==window.currentCrate);if(a!==b){return a-b}a=(aaa.word!==valLower);b=(bbb.word!==valLower);if(a!==b){return a-b}a=aaa.word.length;b=bbb.word.length;if(a!==b){return a-b}a=aaa.word;b=bbb.word;if(a!==b){return(a>b?+1:-1)}a=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}if((aaa.item.ty===TY_PRIMITIVE&&bbb.item.ty!==TY_KEYWORD)||(aaa.item.ty===TY_KEYWORD&&bbb.item.ty!==TY_PRIMITIVE)){return-1}if((bbb.item.ty===TY_PRIMITIVE&&aaa.item.ty!==TY_PRIMITIVE)||(bbb.item.ty===TY_KEYWORD&&aaa.item.ty!==TY_KEYWORD)){return 1}a=(aaa.item.desc==="");b=(bbb.item.desc==="");if(a!==b){return a-b}a=aaa.item.ty;b=bbb.item.ty;if(a!==b){return a-b}a=aaa.item.path;b=bbb.item.path;if(a!==b){return(a>b?+1:-1)}return 0});var length=results.length;for(i=0;i<length;++i){var result=results[i];if(result.dontValidate){continue}var name=result.item.name.toLowerCase(),path=result.item.path.toLowerCase(),parent=result.item.parent;if(isType!==true&&validateResult(name,path,split,parent)===false){result.id=-1}}return transformResults(results)}function extractGenerics(val){val=val.toLowerCase();if(val.indexOf("<")!==-1){var values=val.substring(val.indexOf("<")+1,val.lastIndexOf(">"));return{name:val.substring(0,val.indexOf("<")),generics:values.split(/\s*,\s*/),}}return{name:val,generics:[],}}function checkGenerics(obj,val){var lev_distance=MAX_LEV_DISTANCE+1;if(val.generics.length>0){if(obj.length>GENERICS_DATA&&obj[GENERICS_DATA].length>=val.generics.length){var elems=obj[GENERICS_DATA].slice(0);var total=0;var done=0;var vlength=val.generics.length;for(var y=0;y<vlength;++y){var lev={pos:-1,lev:MAX_LEV_DISTANCE+1};var elength=elems.length;for(var x=0;x<elength;++x){var tmp_lev=levenshtein(elems[x],val.generics[y]);if(tmp_lev<lev.lev){lev.lev=tmp_lev;lev.pos=x}}if(lev.pos!==-1){elems.splice(lev.pos,1);lev_distance=Math.min(lev.lev,lev_distance);total+=lev.lev;done+=1}else{return MAX_LEV_DISTANCE+1}}return Math.ceil(total/done)}}return MAX_LEV_DISTANCE+1}function checkType(obj,val,literalSearch){var lev_distance=MAX_LEV_DISTANCE+1;var x;if(obj[NAME]===val.name){if(literalSearch===true){if(val.generics&&val.generics.length!==0){if(obj.length>GENERICS_DATA&&obj[GENERICS_DATA].length>=val.generics.length){var elems=obj[GENERICS_DATA].slice(0);var allFound=true;for(var y=0;allFound===true&&y<val.generics.length;++y){allFound=false;for(x=0;allFound===false&&x<elems.length;++x){allFound=elems[x]===val.generics[y]}if(allFound===true){elems.splice(x-1,1)}}if(allFound===true){return true}}else{return false}}return true}if(obj.length>GENERICS_DATA&&obj[GENERICS_DATA].length!==0){var tmp_lev=checkGenerics(obj,val);if(tmp_lev<=MAX_LEV_DISTANCE){return tmp_lev}}else{return 0}}if(literalSearch===true){if(obj.length>GENERICS_DATA&&obj[GENERICS_DATA].length>0){var length=obj[GENERICS_DATA].length;for(x=0;x<length;++x){if(obj[GENERICS_DATA][x]===val.name){return true}}}return false}lev_distance=Math.min(levenshtein(obj[NAME],val.name),lev_distance);if(lev_distance<=MAX_LEV_DISTANCE){lev_distance=Math.ceil((checkGenerics(obj,val)+lev_distance)/2)}else if(obj.length>GENERICS_DATA&&obj[GENERICS_DATA].length>0){var olength=obj[GENERICS_DATA].length;for(x=0;x<olength;++x){lev_distance=Math.min(levenshtein(obj[GENERICS_DATA][x],val.name),lev_distance)}}return lev_distance+1}function findArg(obj,val,literalSearch){var lev_distance=MAX_LEV_DISTANCE+1;if(obj&&obj.type&&obj.type[INPUTS_DATA]&&obj.type[INPUTS_DATA].length>0){var length=obj.type[INPUTS_DATA].length;for(var i=0;i<length;i++){var tmp=checkType(obj.type[INPUTS_DATA][i],val,literalSearch);if(literalSearch===true&&tmp===true){return true}lev_distance=Math.min(tmp,lev_distance);if(lev_distance===0){return 0}}}return literalSearch===true?false:lev_distance}function checkReturned(obj,val,literalSearch){var lev_distance=MAX_LEV_DISTANCE+1;if(obj&&obj.type&&obj.type.length>OUTPUT_DATA){var ret=obj.type[OUTPUT_DATA];if(!obj.type[OUTPUT_DATA].length){ret=[ret]}for(var x=0;x<ret.length;++x){var r=ret[x];if(typeof r==="string"){r=[r]}var tmp=checkType(r,val,literalSearch);if(literalSearch===true){if(tmp===true){return true}continue}lev_distance=Math.min(tmp,lev_distance);if(lev_distance===0){return 0}}}return literalSearch===true?false:lev_distance}function checkPath(contains,lastElem,ty){if(contains.length===0){return 0}var ret_lev=MAX_LEV_DISTANCE+1;var path=ty.path.split("::");if(ty.parent&&ty.parent.name){path.push(ty.parent.name.toLowerCase())}var length=path.length;var clength=contains.length;if(clength>length){return MAX_LEV_DISTANCE+1}for(var i=0;i<length;++i){if(i+clength>length){break}var lev_total=0;var aborted=false;for(var x=0;x<clength;++x){var lev=levenshtein(path[i+x],contains[x]);if(lev>MAX_LEV_DISTANCE){aborted=true;break}lev_total+=lev}if(aborted===false){ret_lev=Math.min(ret_lev,Math.round(lev_total/clength))}}return ret_lev}function typePassesFilter(filter,type){if(filter<0)return true;if(filter===type)return true;var name=itemTypes[type];switch(itemTypes[filter]){case"constant":return(name=="associatedconstant");case"fn":return(name=="method"||name=="tymethod");case"type":return(name=="primitive"||name=="keyword")}return false}function generateId(ty){if(ty.parent&&ty.parent.name){return itemTypes[ty.ty]+ty.path+ty.parent.name+ty.name}return itemTypes[ty.ty]+ty.path+ty.name}var nSearchWords=searchWords.length;var i;var ty;var fullId;var returned;var in_args;if((val.charAt(0)==="\""||val.charAt(0)==="'")&&val.charAt(val.length-1)===val.charAt(0)){val=extractGenerics(val.substr(1,val.length-2));for(i=0;i<nSearchWords;++i){if(filterCrates!==undefined&&searchIndex[i].crate!==filterCrates){continue}in_args=findArg(searchIndex[i],val,true);returned=checkReturned(searchIndex[i],val,true);ty=searchIndex[i];fullId=generateId(ty);if(searchWords[i]===val.name){if(typePassesFilter(typeFilter,searchIndex[i].ty)&&results[fullId]===undefined){results[fullId]={id:i,index:-1}}}else if((in_args===true||returned===true)&&typePassesFilter(typeFilter,searchIndex[i].ty)){if(in_args===true||returned===true){if(in_args===true){results_in_args[fullId]={id:i,index:-1,dontValidate:true,}}if(returned===true){results_returned[fullId]={id:i,index:-1,dontValidate:true,}}}else{results[fullId]={id:i,index:-1,dontValidate:true,}}}}query.inputs=[val];query.output=val;query.search=val}else if(val.search("->")>-1){var trimmer=function(s){return s.trim()};var parts=val.split("->").map(trimmer);var input=parts[0];var inputs=input.split(",").map(trimmer).sort();for(i=0;i<inputs.length;++i){inputs[i]=extractGenerics(inputs[i])}var output=extractGenerics(parts[1]);for(i=0;i<nSearchWords;++i){if(filterCrates!==undefined&&searchIndex[i].crate!==filterCrates){continue}var type=searchIndex[i].type;ty=searchIndex[i];if(!type){continue}fullId=generateId(ty);var typeOutput=type.length>OUTPUT_DATA?type[OUTPUT_DATA].name:"";returned=checkReturned(ty,output,true);if(output.name==="*"||returned===true){in_args=false;var is_module=false;if(input==="*"){is_module=true}else{var allFound=true;for(var it=0;allFound===true&&it<inputs.length;it++){allFound=checkType(type,inputs[it],true)}in_args=allFound}if(in_args===true){results_in_args[fullId]={id:i,index:-1,dontValidate:true,}}if(returned===true){results_returned[fullId]={id:i,index:-1,dontValidate:true,}}if(is_module===true){results[fullId]={id:i,index:-1,dontValidate:true,}}}}query.inputs=inputs.map(function(input){return input.name});query.output=output.name}else{query.inputs=[val];query.output=val;query.search=val;val=val.replace(/\_/g,"");var valGenerics=extractGenerics(val);var paths=valLower.split("::");var j;for(j=0;j<paths.length;++j){if(paths[j]===""){paths.splice(j,1);j-=1}}val=paths[paths.length-1];var contains=paths.slice(0,paths.length>1?paths.length-1:1);for(j=0;j<nSearchWords;++j){var lev;var lev_distance;ty=searchIndex[j];if(!ty||(filterCrates!==undefined&&ty.crate!==filterCrates)){continue}var lev_distance;var lev_add=0;if(paths.length>1){lev=checkPath(contains,paths[paths.length-1],ty);if(lev>MAX_LEV_DISTANCE){continue}else if(lev>0){lev_add=1}}returned=MAX_LEV_DISTANCE+1;in_args=MAX_LEV_DISTANCE+1;var index=-1;lev=MAX_LEV_DISTANCE+1;fullId=generateId(ty);if(searchWords[j].indexOf(split[i])>-1||searchWords[j].indexOf(val)>-1||searchWords[j].replace(/_/g,"").indexOf(val)>-1){if(typePassesFilter(typeFilter,ty.ty)&&results[fullId]===undefined){index=searchWords[j].replace(/_/g,"").indexOf(val)}}if((lev=levenshtein(searchWords[j],val))<=MAX_LEV_DISTANCE){if(typePassesFilter(typeFilter,ty.ty)===false){lev=MAX_LEV_DISTANCE+1}else{lev+=1}}if((in_args=findArg(ty,valGenerics))<=MAX_LEV_DISTANCE){if(typePassesFilter(typeFilter,ty.ty)===false){in_args=MAX_LEV_DISTANCE+1}}if((returned=checkReturned(ty,valGenerics))<=MAX_LEV_DISTANCE){if(typePassesFilter(typeFilter,ty.ty)===false){returned=MAX_LEV_DISTANCE+1}}lev+=lev_add;if(lev>0&&val.length>3&&searchWords[j].indexOf(val)>-1){if(val.length<6){lev-=1}else{lev=0}}if(in_args<=MAX_LEV_DISTANCE){if(results_in_args[fullId]===undefined){results_in_args[fullId]={id:j,index:index,lev:in_args,}}results_in_args[fullId].lev=Math.min(results_in_args[fullId].lev,in_args)}if(returned<=MAX_LEV_DISTANCE){if(results_returned[fullId]===undefined){results_returned[fullId]={id:j,index:index,lev:returned,}}results_returned[fullId].lev=Math.min(results_returned[fullId].lev,returned)}if(index!==-1||lev<=MAX_LEV_DISTANCE){if(index!==-1&&paths.length<2){lev=0}else if(searchWords[j]===val){lev=-1}if(results[fullId]===undefined){results[fullId]={id:j,index:index,lev:lev,}}results[fullId].lev=Math.min(results[fullId].lev,lev)}}}var ret={"in_args":sortResults(results_in_args,true),"returned":sortResults(results_returned,true),"others":sortResults(results),};if(ALIASES&&ALIASES[window.currentCrate]&&ALIASES[window.currentCrate][query.raw]){var aliases=ALIASES[window.currentCrate][query.raw];for(i=0;i<aliases.length;++i){aliases[i].is_alias=true;aliases[i].alias=query.raw;aliases[i].path=aliases[i].p;var res=buildHrefAndPath(aliases[i]);aliases[i].displayPath=pathSplitter(res[0]);aliases[i].fullPath=aliases[i].displayPath+aliases[i].name;aliases[i].href=res[1];ret.others.unshift(aliases[i]);if(ret.others.length>MAX_RESULTS){ret.others.pop()}}}return ret}function validateResult(name,path,keys,parent){for(var i=0;i<keys.length;++i){if(!(name.indexOf(keys[i])>-1||path.indexOf(keys[i])>-1||(parent!==undefined&&parent.name.toLowerCase().indexOf(keys[i])>-1)||levenshtein(name,keys[i])<=MAX_LEV_DISTANCE)){return false}}return true}function getQuery(raw){var matches,type,query;query=raw;matches=query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);if(matches){type=matches[1].replace(/^const$/,"constant");query=query.substring(matches[0].length)}return{raw:raw,query:query,type:type,id:query+type}}function initSearchNav(){var hoverTimeout;var click_func=function(e){var el=e.target;while(el.tagName!=="TR"){el=el.parentNode}var dst=e.target.getElementsByTagName("a");if(dst.length<1){return}dst=dst[0];if(window.location.pathname===dst.pathname){addClass(document.getElementById("search"),"hidden");removeClass(main,"hidden");document.location.href=dst.href}};var mouseover_func=function(e){var el=e.target;while(el.tagName!=="TR"){el=el.parentNode}clearTimeout(hoverTimeout);hoverTimeout=setTimeout(function(){onEachLazy(document.getElementsByClassName("search-results"),function(e){onEachLazy(e.getElementsByClassName("result"),function(i_e){removeClass(i_e,"highlighted")})});addClass(el,"highlighted")},20)};onEachLazy(document.getElementsByClassName("search-results"),function(e){onEachLazy(e.getElementsByClassName("result"),function(i_e){i_e.onclick=click_func;i_e.onmouseover=mouseover_func})});search_input.onkeydown=function(e){var actives=[[],[],[]];var current=0;onEachLazy(document.getElementById("results").childNodes,function(e){onEachLazy(e.getElementsByClassName("highlighted"),function(e){actives[current].push(e)});current+=1});if(e.which===38){if(!actives[currentTab].length||!actives[currentTab][0].previousElementSibling){return}addClass(actives[currentTab][0].previousElementSibling,"highlighted");removeClass(actives[currentTab][0],"highlighted")}else if(e.which===40){if(!actives[currentTab].length){var results=document.getElementById("results").childNodes;if(results.length>0){var res=results[currentTab].getElementsByClassName("result");if(res.length>0){addClass(res[0],"highlighted")}}}else if(actives[currentTab][0].nextElementSibling){addClass(actives[currentTab][0].nextElementSibling,"highlighted");removeClass(actives[currentTab][0],"highlighted")}}else if(e.which===13){if(actives[currentTab].length){document.location.href=actives[currentTab][0].getElementsByTagName("a")[0].href}}else if(e.which===9){if(e.shiftKey){printTab(currentTab>0?currentTab-1:2)}else{printTab(currentTab>1?0:currentTab+1)}e.preventDefault()}else if(e.which===16){}else if(e.which===27){removeClass(actives[currentTab][0],"highlighted");search_input.value="";defocusSearchBar()}else if(actives[currentTab].length>0){removeClass(actives[currentTab][0],"highlighted")}}}function buildHrefAndPath(item){var displayPath;var href;var type=itemTypes[item.ty];var name=item.name;if(type==="mod"){displayPath=item.path+"::";href=rootPath+item.path.replace(/::/g,"/")+"/"+name+"/index.html"}else if(type==="primitive"||type==="keyword"){displayPath="";href=rootPath+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}else if(type==="externcrate"){displayPath="";href=rootPath+name+"/index.html"}else if(item.parent!==undefined){var myparent=item.parent;var anchor="#"+type+"."+name;var parentType=itemTypes[myparent.ty];if(parentType==="primitive"){displayPath=myparent.name+"::"}else{displayPath=item.path+"::"+myparent.name+"::"}href=rootPath+item.path.replace(/::/g,"/")+"/"+parentType+"."+myparent.name+".html"+anchor}else{displayPath=item.path+"::";href=rootPath+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}return[displayPath,href]}function escape(content){var h1=document.createElement("h1");h1.textContent=content;return h1.innerHTML}function pathSplitter(path){var tmp="<span>"+path.replace(/::/g,"::</span><span>");if(tmp.endsWith("<span>")){return tmp.slice(0,tmp.length-6)}return tmp}function addTab(array,query,display){var extraStyle="";if(display===false){extraStyle=" style=\"display: none;\""}var output="";var duplicates={};var length=0;if(array.length>0){output="<table class=\"search-results\""+extraStyle+">";array.forEach(function(item){var name,type;name=item.name;type=itemTypes[item.ty];if(item.is_alias!==true){if(duplicates[item.fullPath]){return}duplicates[item.fullPath]=true}length+=1;output+="<tr class=\""+type+" result\"><td>"+"<a href=\""+item.href+"\">"+(item.is_alias===true?("<span class=\"alias\"><b>"+item.alias+" </b></span><span "+"class=\"grey\"><i> - see </i></span>"):"")+item.displayPath+"<span class=\""+type+"\">"+name+"</span></a></td><td>"+"<a href=\""+item.href+"\">"+"<span class=\"desc\">"+escape(item.desc)+" </span></a></td></tr>"});output+="</table>"}else{output="<div class=\"search-failed\""+extraStyle+">No results :(<br/>"+"Try on <a href=\"https://duckduckgo.com/?q="+encodeURIComponent("rust "+query.query)+"\">DuckDuckGo</a>?<br/><br/>"+"Or try looking in one of these:<ul><li>The <a "+"href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> "+" for technical details about the language.</li><li><a "+"href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By "+"Example</a> for expository code examples.</a></li><li>The <a "+"href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for "+"introductions to language features and the language itself.</li><li><a "+"href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on"+" <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>"}return[output,length]}function makeTabHeader(tabNb,text,nbElems){if(currentTab===tabNb){return"<div class=\"selected\">"+text+" <div class=\"count\">("+nbElems+")</div></div>"}return"<div>"+text+" <div class=\"count\">("+nbElems+")</div></div>"}function showResults(results){if(results.others.length===1&&getCurrentValue("rustdoc-go-to-only-result")==="true"){var elem=document.createElement("a");elem.href=results.others[0].href;elem.style.display="none";document.body.appendChild(elem);elem.click()}var query=getQuery(search_input.value);currentResults=query.id;var ret_others=addTab(results.others,query);var ret_in_args=addTab(results.in_args,query,false);var ret_returned=addTab(results.returned,query,false);var output="<h1>Results for "+escape(query.query)+(query.type?" (type: "+escape(query.type)+")":"")+"</h1>"+"<div id=\"titles\">"+makeTabHeader(0,"In Names",ret_others[1])+makeTabHeader(1,"In Parameters",ret_in_args[1])+makeTabHeader(2,"In Return Types",ret_returned[1])+"</div><div id=\"results\">"+ret_others[0]+ret_in_args[0]+ret_returned[0]+"</div>";addClass(main,"hidden");var search=document.getElementById("search");removeClass(search,"hidden");search.innerHTML=output;var tds=search.getElementsByTagName("td");var td_width=0;if(tds.length>0){td_width=tds[0].offsetWidth}var width=search.offsetWidth-40-td_width;onEachLazy(search.getElementsByClassName("desc"),function(e){e.style.width=width+"px"});initSearchNav();var elems=document.getElementById("titles").childNodes;elems[0].onclick=function(){printTab(0)};elems[1].onclick=function(){printTab(1)};elems[2].onclick=function(){printTab(2)};printTab(currentTab)}function execSearch(query,searchWords,filterCrates){function getSmallest(arrays,positions,notDuplicates){var start=null;for(var it=0;it<positions.length;++it){if(arrays[it].length>positions[it]&&(start===null||start>arrays[it][positions[it]].lev)&&!notDuplicates[arrays[it][positions[it]].fullPath]){start=arrays[it][positions[it]].lev}}return start}function mergeArrays(arrays){var ret=[];var positions=[];var notDuplicates={};for(var x=0;x<arrays.length;++x){positions.push(0)}while(ret.length<MAX_RESULTS){var smallest=getSmallest(arrays,positions,notDuplicates);if(smallest===null){break}for(x=0;x<arrays.length&&ret.length<MAX_RESULTS;++x){if(arrays[x].length>positions[x]&&arrays[x][positions[x]].lev===smallest&&!notDuplicates[arrays[x][positions[x]].fullPath]){ret.push(arrays[x][positions[x]]);notDuplicates[arrays[x][positions[x]].fullPath]=true;positions[x]+=1}}}return ret}var queries=query.raw.split(",");var results={"in_args":[],"returned":[],"others":[],};for(var i=0;i<queries.length;++i){query=queries[i].trim();if(query.length!==0){var tmp=execQuery(getQuery(query),searchWords,filterCrates);results.in_args.push(tmp.in_args);results.returned.push(tmp.returned);results.others.push(tmp.others)}}if(queries.length>1){return{"in_args":mergeArrays(results.in_args),"returned":mergeArrays(results.returned),"others":mergeArrays(results.others),}}else{return{"in_args":results.in_args[0],"returned":results.returned[0],"others":results.others[0],}}}function getFilterCrates(){var elem=document.getElementById("crate-search");if(elem&&elem.value!=="All crates"&&rawSearchIndex.hasOwnProperty(elem.value)){return elem.value}return undefined}function search(e,forced){var params=getQueryStringParams();var query=getQuery(search_input.value.trim());if(e){e.preventDefault()}if(query.query.length===0){return}if(forced!==true&&query.id===currentResults){if(query.query.length>0){putBackSearch(search_input)}return}document.title="Results for "+query.query+" - Rust";if(browserSupportsHistoryApi()){if(!history.state&&!params.search){history.pushState(query,"","?search="+encodeURIComponent(query.raw))}else{history.replaceState(query,"","?search="+encodeURIComponent(query.raw))}}var filterCrates=getFilterCrates();showResults(execSearch(query,index,filterCrates),filterCrates)}function buildIndex(rawSearchIndex){searchIndex=[];var searchWords=[];var i;for(var crate in rawSearchIndex){if(!rawSearchIndex.hasOwnProperty(crate)){continue}searchWords.push(crate);searchIndex.push({crate:crate,ty:1,name:crate,path:"",desc:rawSearchIndex[crate].doc,type:null,});var items=rawSearchIndex[crate].i;var paths=rawSearchIndex[crate].p;var len=paths.length;for(i=0;i<len;++i){paths[i]={ty:paths[i][0],name:paths[i][1]}}len=items.length;var lastPath="";for(i=0;i<len;++i){var rawRow=items[i];var row={crate:crate,ty:rawRow[0],name:rawRow[1],path:rawRow[2]||lastPath,desc:rawRow[3],parent:paths[rawRow[4]],type:rawRow[5]};searchIndex.push(row);if(typeof row.name==="string"){var word=row.name.toLowerCase();searchWords.push(word)}else{searchWords.push("")}lastPath=row.path}}return searchWords}function startSearch(){var searchTimeout;var callback=function(){clearTimeout(searchTimeout);if(search_input.value.length===0){if(browserSupportsHistoryApi()){history.replaceState("",window.currentCrate+" - Rust","?search=")}if(hasClass(main,"content")){removeClass(main,"hidden")}var search_c=document.getElementById("search");if(hasClass(search_c,"content")){addClass(search_c,"hidden")}}else{searchTimeout=setTimeout(search,500)}};search_input.onkeyup=callback;search_input.oninput=callback;document.getElementsByClassName("search-form")[0].onsubmit=function(e){e.preventDefault();clearTimeout(searchTimeout);search()};search_input.onchange=function(e){clearTimeout(searchTimeout);setTimeout(search,0)};search_input.onpaste=search_input.onchange;var selectCrate=document.getElementById('crate-search');if(selectCrate){selectCrate.onchange=function(){search(undefined,true)}}if(browserSupportsHistoryApi()){var previousTitle=document.title;window.onpopstate=function(e){var params=getQueryStringParams();if(!params.search){if(hasClass(main,"content")){removeClass(main,"hidden")}var search_c=document.getElementById("search");if(hasClass(search_c,"content")){addClass(search_c,"hidden")}}document.title=previousTitle;currentResults=null;if(params.search){search_input.value=params.search}else{search_input.value=""}search()}}search()}index=buildIndex(rawSearchIndex);startSearch();if(rootPath==="../"||rootPath==="./"){var sidebar=document.getElementsByClassName("sidebar-elems")[0];if(sidebar){var div=document.createElement("div");div.className="block crate";div.innerHTML="<h3>Crates</h3>";var ul=document.createElement("ul");div.appendChild(ul);var crates=[];for(var crate in rawSearchIndex){if(!rawSearchIndex.hasOwnProperty(crate)){continue}crates.push(crate)}crates.sort();for(var i=0;i<crates.length;++i){var klass="crate";if(rootPath!=="./"&&crates[i]===window.currentCrate){klass+=" current"}var link=document.createElement("a");link.href=rootPath+crates[i]+"/index.html";link.title=rawSearchIndex[crates[i]].doc;link.className=klass;link.textContent=crates[i];var li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}sidebar.appendChild(div)}}}window.initSearch=initSearch;function initSidebarItems(items){var sidebar=document.getElementsByClassName("sidebar-elems")[0];var current=window.sidebarCurrent;function block(shortty,longty){var filtered=items[shortty];if(!filtered){return}var div=document.createElement("div");div.className="block "+shortty;var h3=document.createElement("h3");h3.textContent=longty;div.appendChild(h3);var ul=document.createElement("ul");var length=filtered.length;for(var i=0;i<length;++i){var item=filtered[i];var name=item[0];var desc=item[1];var klass=shortty;if(name===current.name&&shortty===current.ty){klass+=" current"}var path;if(shortty==="mod"){path=name+"/index.html"}else{path=shortty+"."+name+".html"}var link=document.createElement("a");link.href=current.relpath+path;link.title=desc;link.className=klass;link.textContent=name;var li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);if(sidebar){sidebar.appendChild(div)}}block("primitive","Primitive Types");block("mod","Modules");block("macro","Macros");block("struct","Structs");block("enum","Enums");block("union","Unions");block("constant","Constants");block("static","Statics");block("trait","Traits");block("fn","Functions");block("type","Type Definitions");block("foreigntype","Foreign Types");block("keyword","Keywords");block("traitalias","Trait Aliases")}window.initSidebarItems=initSidebarItems;window.register_implementors=function(imp){var implementors=document.getElementById("implementors-list");var synthetic_implementors=document.getElementById("synthetic-implementors-list");var libs=Object.getOwnPropertyNames(imp);var llength=libs.length;for(var i=0;i<llength;++i){if(libs[i]===currentCrate){continue}var structs=imp[libs[i]];var slength=structs.length;struct_loop:for(var j=0;j<slength;++j){var struct=structs[j];var list=struct.synthetic?synthetic_implementors:implementors;if(struct.synthetic){var stlength=struct.types.length;for(var k=0;k<stlength;k++){if(window.inlined_types.has(struct.types[k])){continue struct_loop}window.inlined_types.add(struct.types[k])}}var code=document.createElement("code");code.innerHTML=struct.text;var x=code.getElementsByTagName("a");var xlength=x.length;for(var it=0;it<xlength;it++){var href=x[it].getAttribute("href");if(href&&href.indexOf("http")!==0){x[it].setAttribute("href",rootPath+href)}}var display=document.createElement("h3");addClass(display,"impl");display.innerHTML="<span class=\"in-band\"><table class=\"table-display\">"+"<tbody><tr><td><code>"+code.outerHTML+"</code></td><td></td></tr>"+"</tbody></table></span>";list.appendChild(display)}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return"+"}return"\u2212"}function onEveryMatchingChild(elem,className,func){if(elem&&className&&func){var length=elem.childNodes.length;var nodes=elem.childNodes;for(var i=0;i<length;++i){if(hasClass(nodes[i],className)){func(nodes[i])}else{onEveryMatchingChild(nodes[i],className,func)}}}}function toggleAllDocs(pageId,fromAutoCollapse){var innerToggle=document.getElementById("toggle-all-docs");if(!innerToggle){return}if(hasClass(innerToggle,"will-expand")){updateLocalStorage("rustdoc-collapse","false");removeClass(innerToggle,"will-expand");onEveryMatchingChild(innerToggle,"inner",function(e){e.innerHTML=labelForToggleButton(false)});innerToggle.title="collapse all docs";if(fromAutoCollapse!==true){onEachLazy(document.getElementsByClassName("collapse-toggle"),function(e){collapseDocs(e,"show")})}}else{updateLocalStorage("rustdoc-collapse","true");addClass(innerToggle,"will-expand");onEveryMatchingChild(innerToggle,"inner",function(e){var parent=e.parentNode;var superParent=null;if(parent){superParent=parent.parentNode}if(!parent||!superParent||superParent.id!=="main"||hasClass(parent,"impl")===false){e.innerHTML=labelForToggleButton(true)}});innerToggle.title="expand all docs";if(fromAutoCollapse!==true){onEachLazy(document.getElementsByClassName("collapse-toggle"),function(e){var parent=e.parentNode;var superParent=null;if(parent){superParent=parent.parentNode}if(!parent||!superParent||superParent.id!=="main"||hasClass(parent,"impl")===false){collapseDocs(e,"hide",pageId)}})}}}function collapseDocs(toggle,mode,pageId){if(!toggle||!toggle.parentNode){return}function adjustToggle(arg){return function(e){if(hasClass(e,"toggle-label")){if(arg){e.style.display="inline-block"}else{e.style.display="none"}}if(hasClass(e,"inner")){e.innerHTML=labelForToggleButton(arg)}}}function implHider(addOrRemove,fullHide){return function(n){var is_method=hasClass(n,"method")||fullHide;if(is_method||hasClass(n,"type")){if(is_method===true){if(addOrRemove){addClass(n,"hidden-by-impl-hider")}else{removeClass(n,"hidden-by-impl-hider")}}var ns=n.nextElementSibling;while(true){if(ns&&(hasClass(ns,"docblock")||hasClass(ns,"stability"))){if(addOrRemove){addClass(ns,"hidden-by-impl-hider")}else{removeClass(ns,"hidden-by-impl-hider")}ns=ns.nextElementSibling;continue}break}}}}var relatedDoc;var action=mode;if(hasClass(toggle.parentNode,"impl")===false){relatedDoc=toggle.parentNode.nextElementSibling;if(hasClass(relatedDoc,"stability")){relatedDoc=relatedDoc.nextElementSibling}if(hasClass(relatedDoc,"docblock")||hasClass(relatedDoc,"sub-variant")){if(mode==="toggle"){if(hasClass(relatedDoc,"hidden-by-usual-hider")){action="show"}else{action="hide"}}if(action==="hide"){addClass(relatedDoc,"hidden-by-usual-hider");onEachLazy(toggle.childNodes,adjustToggle(true));addClass(toggle.parentNode,"collapsed")}else if(action==="show"){removeClass(relatedDoc,"hidden-by-usual-hider");removeClass(toggle.parentNode,"collapsed");onEachLazy(toggle.childNodes,adjustToggle(false))}}}else{var parentElem=toggle.parentNode;relatedDoc=parentElem;var docblock=relatedDoc.nextElementSibling;while(hasClass(relatedDoc,"impl-items")===false){relatedDoc=relatedDoc.nextElementSibling}if((!relatedDoc&&hasClass(docblock,"docblock")===false)||(pageId&&document.getElementById(pageId))){return}if(mode==="toggle"){if(hasClass(relatedDoc,"fns-now-collapsed")||hasClass(docblock,"hidden-by-impl-hider")){action="show"}else{action="hide"}}var dontApplyBlockRule=toggle.parentNode.parentNode.id!=="main";if(action==="show"){removeClass(relatedDoc,"fns-now-collapsed");removeClass(docblock,"hidden-by-usual-hider");onEachLazy(toggle.childNodes,adjustToggle(false,dontApplyBlockRule));onEachLazy(relatedDoc.childNodes,implHider(false,dontApplyBlockRule))}else if(action==="hide"){addClass(relatedDoc,"fns-now-collapsed");addClass(docblock,"hidden-by-usual-hider");onEachLazy(toggle.childNodes,adjustToggle(true,dontApplyBlockRule));onEachLazy(relatedDoc.childNodes,implHider(true,dontApplyBlockRule))}}}function collapser(e,collapse){var n=e.parentElement;if(n.id.match(/^impl(?:-\d+)?$/)===null){if(collapse||hasClass(n,"impl")){collapseDocs(e,"hide",pageId)}}}function autoCollapse(pageId,collapse){if(collapse){toggleAllDocs(pageId,true)}else if(getCurrentValue("rustdoc-trait-implementations")!=="false"){var impl_list=document.getElementById("implementations-list");if(impl_list!==null){onEachLazy(impl_list.getElementsByClassName("collapse-toggle"),function(e){collapser(e,collapse)})}var blanket_list=document.getElementById("blanket-implementations-list");if(blanket_list!==null){onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"),function(e){collapser(e,collapse)})}}}var toggles=document.getElementById("toggle-all-docs");if(toggles){toggles.onclick=toggleAllDocs}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}function createSimpleToggle(sectionIsCollapsed){var toggle=document.createElement("a");toggle.href="javascript:void(0)";toggle.className="collapse-toggle";toggle.innerHTML="[<span class=\"inner\">"+labelForToggleButton(sectionIsCollapsed)+"</span>]";return toggle}var toggle=createSimpleToggle(false);var hideMethodDocs=getCurrentValue("rustdoc-method-docs")==="true";var pageId=getPageId();var func=function(e){var next=e.nextElementSibling;if(!next){return}if(hasClass(next,"docblock")===true||(hasClass(next,"stability")===true&&hasClass(next.nextElementSibling,"docblock")===true)){var newToggle=toggle.cloneNode(true);insertAfter(newToggle,e.childNodes[e.childNodes.length-1]);if(hideMethodDocs===true&&hasClass(e,"method")===true){collapseDocs(newToggle,"hide",pageId)}}};var funcImpl=function(e){var next=e.nextElementSibling;if(next&&hasClass(next,"docblock")){next=next.nextElementSibling}if(!next){return}if(next.getElementsByClassName("method").length>0&&hasClass(e,"impl")){insertAfter(toggle.cloneNode(true),e.childNodes[e.childNodes.length-1])}};onEachLazy(document.getElementsByClassName("method"),func);onEachLazy(document.getElementsByClassName("associatedconstant"),func);onEachLazy(document.getElementsByClassName("impl"),funcImpl);var impl_call=function(){};if(hideMethodDocs===true){impl_call=function(e,newToggle,pageId){if(e.id.match(/^impl(?:-\d+)?$/)===null){if(hasClass(e,"impl")===true){collapseDocs(newToggle,"hide",pageId)}}}}var newToggle=document.createElement("a");newToggle.href="javascript:void(0)";newToggle.className="collapse-toggle hidden-default collapsed";newToggle.innerHTML="[<span class=\"inner\">"+labelForToggleButton(true)+"</span>] Show hidden undocumented items";function toggleClicked(){if(hasClass(this,"collapsed")){removeClass(this,"collapsed");onEachLazy(this.parentNode.getElementsByClassName("hidden"),function(x){if(hasClass(x,"content")===false){removeClass(x,"hidden");addClass(x,"x")}},true);this.innerHTML="[<span class=\"inner\">"+labelForToggleButton(false)+"</span>] Hide undocumented items"}else{addClass(this,"collapsed");onEachLazy(this.parentNode.getElementsByClassName("x"),function(x){if(hasClass(x,"content")===false){addClass(x,"hidden");removeClass(x,"x")}},true);this.innerHTML="[<span class=\"inner\">"+labelForToggleButton(true)+"</span>] Show hidden undocumented items"}}onEachLazy(document.getElementsByClassName("impl-items"),function(e){onEachLazy(e.getElementsByClassName("associatedconstant"),func);var hiddenElems=e.getElementsByClassName("hidden");var needToggle=false;var hlength=hiddenElems.length;for(var i=0;i<hlength;++i){if(hasClass(hiddenElems[i],"content")===false&&hasClass(hiddenElems[i],"docblock")===false){needToggle=true;break}}if(needToggle===true){var inner_toggle=newToggle.cloneNode(true);inner_toggle.onclick=toggleClicked;e.insertBefore(inner_toggle,e.firstChild);impl_call(e.previousSibling,inner_toggle,pageId)}});function createToggle(otherMessage,fontSize,extraClass,show){var span=document.createElement("span");span.className="toggle-label";if(show){span.style.display="none"}if(!otherMessage){span.innerHTML=" Expand description"}else{span.innerHTML=otherMessage}if(fontSize){span.style.fontSize=fontSize}var mainToggle=toggle.cloneNode(true);mainToggle.appendChild(span);var wrapper=document.createElement("div");wrapper.className="toggle-wrapper";if(!show){addClass(wrapper,"collapsed");var inner=mainToggle.getElementsByClassName("inner");if(inner&&inner.length>0){inner[0].innerHTML="+"}}if(extraClass){addClass(wrapper,extraClass)}wrapper.appendChild(mainToggle);return wrapper}var showItemDeclarations=getCurrentValue("rustdoc-item-declarations")==="false";function buildToggleWrapper(e){if(hasClass(e,"autohide")){var wrap=e.previousElementSibling;if(wrap&&hasClass(wrap,"toggle-wrapper")){var inner_toggle=wrap.childNodes[0];var extra=e.childNodes[0].tagName==="H3";e.style.display="none";addClass(wrap,"collapsed");onEachLazy(inner_toggle.getElementsByClassName("inner"),function(e){e.innerHTML=labelForToggleButton(true)});onEachLazy(inner_toggle.getElementsByClassName("toggle-label"),function(e){e.style.display="inline-block";if(extra===true){i_e.innerHTML=" Show "+e.childNodes[0].innerHTML}})}}if(e.parentNode.id==="main"){var otherMessage="";var fontSize;var extraClass;if(hasClass(e,"type-decl")){fontSize="20px";otherMessage=" Show declaration";if(showItemDeclarations===false){extraClass="collapsed"}}else if(hasClass(e,"sub-variant")){otherMessage=" Show fields"}else if(hasClass(e,"non-exhaustive")){otherMessage=" This ";if(hasClass(e,"non-exhaustive-struct")){otherMessage+="struct"}else if(hasClass(e,"non-exhaustive-enum")){otherMessage+="enum"}else if(hasClass(e,"non-exhaustive-variant")){otherMessage+="enum variant"}else if(hasClass(e,"non-exhaustive-type")){otherMessage+="type"}otherMessage+=" is marked as non-exhaustive"}else if(hasClass(e.childNodes[0],"impl-items")){extraClass="marg-left"}e.parentNode.insertBefore(createToggle(otherMessage,fontSize,extraClass,hasClass(e,"type-decl")===false||showItemDeclarations===true),e);if(hasClass(e,"type-decl")===true&&showItemDeclarations===true){collapseDocs(e.previousSibling.childNodes[0],"toggle")}if(hasClass(e,"non-exhaustive")===true){collapseDocs(e.previousSibling.childNodes[0],"toggle")}}}onEachLazy(document.getElementsByClassName("docblock"),buildToggleWrapper);onEachLazy(document.getElementsByClassName("sub-variant"),buildToggleWrapper);function createToggleWrapper(tog){var span=document.createElement("span");span.className="toggle-label";span.style.display="none";span.innerHTML=" Expand attributes";tog.appendChild(span);var wrapper=document.createElement("div");wrapper.className="toggle-wrapper toggle-attributes";wrapper.appendChild(tog);return wrapper}var itemAttributesFunc=function(){};if(getCurrentValue("rustdoc-item-attributes")!=="false"){itemAttributesFunc=function(x){collapseDocs(x.previousSibling.childNodes[0],"toggle")}}var attributesToggle=createToggleWrapper(createSimpleToggle(false));onEachLazy(main.getElementsByClassName("attributes"),function(i_e){var attr_tog=attributesToggle.cloneNode(true);if(hasClass(i_e,"top-attr")===true){addClass(attr_tog,"top-attr")}i_e.parentNode.insertBefore(attr_tog,i_e);itemAttributesFunc(i_e)});var lineNumbersFunc=function(){};if(getCurrentValue("rustdoc-line-numbers")==="true"){lineNumbersFunc=function(x){var count=x.textContent.split("\n").length;var elems=[];for(var i=0;i<count;++i){elems.push(i+1)}var node=document.createElement("pre");addClass(node,"line-number");node.innerHTML=elems.join("\n");x.parentNode.insertBefore(node,x)}}onEachLazy(document.getElementsByClassName("rust-example-rendered"),function(e){if(hasClass(e,"compile_fail")){e.addEventListener("mouseover",function(event){this.parentElement.previousElementSibling.childNodes[0].style.color="#f00"});e.addEventListener("mouseout",function(event){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}else if(hasClass(e,"ignore")){e.addEventListener("mouseover",function(event){this.parentElement.previousElementSibling.childNodes[0].style.color="#ff9200"});e.addEventListener("mouseout",function(event){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}lineNumbersFunc(e)});function showModal(content){var modal=document.createElement("div");modal.id="important";addClass(modal,"modal");modal.innerHTML="<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕"+"</div><div class=\"whiter\"></div><span class=\"docblock\">"+content+"</span></div>";document.getElementsByTagName("body")[0].appendChild(modal);document.getElementById("modal-close").onclick=hideModal;modal.onclick=hideModal}function hideModal(){var modal=document.getElementById("important");if(modal){modal.parentNode.removeChild(modal)}}onEachLazy(document.getElementsByClassName("important-traits"),function(e){e.onclick=function(){showModal(e.lastElementChild.innerHTML)}});function printTab(nb){if(nb===0||nb===1||nb===2){currentTab=nb}var nb_copy=nb;onEachLazy(document.getElementById("titles").childNodes,function(elem){if(nb_copy===0){addClass(elem,"selected")}else{removeClass(elem,"selected")}nb_copy-=1});onEachLazy(document.getElementById("results").childNodes,function(elem){if(nb===0){elem.style.display=""}else{elem.style.display="none"}nb-=1})}function putBackSearch(search_input){if(search_input.value!==""){addClass(main,"hidden");removeClass(document.getElementById("search"),"hidden");if(browserSupportsHistoryApi()){history.replaceState(search_input.value,"","?search="+encodeURIComponent(search_input.value))}}}if(search_input){search_input.onfocus=function(){putBackSearch(this)}}var params=getQueryStringParams();if(params&¶ms.search){addClass(main,"hidden");var search=document.getElementById("search");removeClass(search,"hidden");search.innerHTML="<h3 style=\"text-align: center;\">Loading search results...</h3>"}var sidebar_menu=document.getElementsByClassName("sidebar-menu")[0];if(sidebar_menu){sidebar_menu.onclick=function(){var sidebar=document.getElementsByClassName("sidebar")[0];if(hasClass(sidebar,"mobile")===true){hideSidebar()}else{showSidebar()}}}window.onresize=function(){hideSidebar()};autoCollapse(getPageId(),getCurrentValue("rustdoc-collapse")==="true");if(window.location.hash&&window.location.hash.length>0){expandSection(window.location.hash.replace(/^#/,""))}if(main){onEachLazy(main.getElementsByClassName("loading-content"),function(e){e.remove()});onEachLazy(main.childNodes,function(e){if(e.tagName==="H2"||e.tagName==="H3"){var nextTagName=e.nextElementSibling.tagName;if(nextTagName=="H2"||nextTagName=="H3"){e.nextElementSibling.style.display="flex"}else{e.nextElementSibling.style.display="block"}}})}function addSearchOptions(crates){var elem=document.getElementById('crate-search');if(!elem){return}var crates_text=[];if(Object.keys(crates).length>1){for(var crate in crates){if(crates.hasOwnProperty(crate)){crates_text.push(crate)}}}crates_text.sort(function(a,b){var lower_a=a.toLowerCase();var lower_b=b.toLowerCase();if(lower_a<lower_b){return-1}else if(lower_a>lower_b){return 1}return 0});for(var i=0;i<crates_text.length;++i){var option=document.createElement("option");option.value=crates_text[i];option.innerText=crates_text[i];elem.appendChild(option)}}window.addSearchOptions=addSearchOptions}());function focusSearchBar(){document.getElementsByClassName("search-input")[0].focus()}function defocusSearchBar(){document.getElementsByClassName("search-input")[0].blur()}
\ No newline at end of file diff --git a/vendor/minifier/tests/files/test.json b/vendor/minifier/tests/files/test.json new file mode 100644 index 000000000..b252fcfa7 --- /dev/null +++ b/vendor/minifier/tests/files/test.json @@ -0,0 +1,5 @@ +{ + "test": "\" test2", + "test2": "", + "test3": " " +}
\ No newline at end of file diff --git a/vendor/minifier/tests/js_minify.rs b/vendor/minifier/tests/js_minify.rs new file mode 100644 index 000000000..6d0df664a --- /dev/null +++ b/vendor/minifier/tests/js_minify.rs @@ -0,0 +1,61 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +extern crate minifier; + +use std::ops::Range; + +fn get_ranges(pos: usize, s: &str) -> Range<usize> { + let mut start = pos; + let mut end = pos; + if start >= 20 { + start -= 20; + } else { + start = 0; + } + if end < s.len() - 20 { + end += 20; + } else { + end = s.len(); + } + start..end +} + +fn compare_strs(minified: &str, str2: &str) { + let mut it1 = minified.char_indices(); + let mut it2 = str2.char_indices(); + + loop { + match (it1.next(), it2.next()) { + (Some((pos, c1)), Some((_, c2))) => { + if c1 != c2 { + println!( + "{}\n==== differs from: ====\n{}", + &minified[get_ranges(pos, minified)], + &str2[get_ranges(pos, str2)] + ); + panic!("Chars differ"); + } + } + (None, Some((pos, _))) => { + println!("missing: {}...", &str2[get_ranges(pos + 20, str2)]); + panic!("Missing parts of minified content"); + } + (Some((pos, _)), None) => { + println!("extra: {}...", &minified[get_ranges(pos + 20, minified)]); + panic!("Extra part in minified content"); + } + (None, None) => { + break; + } + } + } +} + +#[test] +fn test_minification() { + use minifier::js::minify; + + let source = include_str!("./files/main.js"); + let expected_result = include_str!("./files/minified_main.js"); + compare_strs(&minify(source).to_string(), expected_result); +} |