2 * Copyright 2014 The Rust Project Developers. See the COPYRIGHT
3 * file at the top-level directory of this distribution and at
4 * http://rust-lang.org/COPYRIGHT.
6 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 * option. This file may not be copied, modified, or distributed
10 * except according to those terms.
14 /* global ALIASES, currentCrate, rootPath */
16 // Local js definitions:
17 /* global addClass, getCurrentValue, hasClass */
18 /* global isHidden onEach, removeClass, updateLocalStorage */
20 if (!String.prototype.startsWith) {
21 String.prototype.startsWith = function(searchString, position) {
22 position = position || 0;
23 return this.indexOf(searchString, position) === position;
26 if (!String.prototype.endsWith) {
27 String.prototype.endsWith = function(suffix, length) {
28 var l = length || this.length;
29 return this.indexOf(suffix, l - suffix.length) !== -1;
33 if (!DOMTokenList.prototype.add) {
34 DOMTokenList.prototype.add = function(className) {
35 if (className && !hasClass(this, className)) {
36 if (this.className && this.className.length > 0) {
37 this.className += " " + className;
39 this.className = className;
45 if (!DOMTokenList.prototype.remove) {
46 DOMTokenList.prototype.remove = function(className) {
47 if (className && this.className) {
48 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
57 // This mapping table should match the discriminants of
58 // `rustdoc::html::item_type::ItemType` type in Rust.
59 var itemTypes = ["mod",
85 var search_input = document.getElementsByClassName("search-input")[0];
87 // On the search screen, so you remain on the last tab you opened.
90 // 1 for "In Parameters"
91 // 2 for "In Return Types"
94 var themesWidth = null;
96 var titleBeforeSearch = document.title;
98 function getPageId() {
99 var id = document.location.href.split("#")[1];
101 return id.split("?")[0].split("&")[0];
106 function showSidebar() {
107 var elems = document.getElementsByClassName("sidebar-elems")[0];
109 addClass(elems, "show-it");
111 var sidebar = document.getElementsByClassName("sidebar")[0];
113 addClass(sidebar, "mobile");
114 var filler = document.getElementById("sidebar-filler");
116 var div = document.createElement("div");
117 div.id = "sidebar-filler";
118 sidebar.appendChild(div);
121 var themePicker = document.getElementsByClassName("theme-picker");
122 if (themePicker && themePicker.length > 0) {
123 themePicker[0].style.display = "none";
127 function hideSidebar() {
128 var elems = document.getElementsByClassName("sidebar-elems")[0];
130 removeClass(elems, "show-it");
132 var sidebar = document.getElementsByClassName("sidebar")[0];
133 removeClass(sidebar, "mobile");
134 var filler = document.getElementById("sidebar-filler");
138 document.getElementsByTagName("body")[0].style.marginTop = "";
139 var themePicker = document.getElementsByClassName("theme-picker");
140 if (themePicker && themePicker.length > 0) {
141 themePicker[0].style.display = null;
145 // used for special search precedence
146 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
147 var TY_KEYWORD = itemTypes.indexOf("keyword");
149 onEachLazy(document.getElementsByClassName("js-only"), function(e) {
150 removeClass(e, "js-only");
153 function getQueryStringParams() {
155 window.location.search.substring(1).split("&").
157 var pair = s.split("=");
158 params[decodeURIComponent(pair[0])] =
159 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
164 function browserSupportsHistoryApi() {
165 return document.location.protocol != "file:" &&
166 window.history && typeof window.history.pushState === "function";
169 var main = document.getElementById("main");
171 function highlightSourceLines(ev) {
172 // If we're in mobile mode, we should add the sidebar in any case.
175 var search = document.getElementById("search");
176 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
178 from = parseInt(match[1], 10);
179 to = Math.min(50000, parseInt(match[2] || match[1], 10));
180 from = Math.min(from, to);
181 elem = document.getElementById(from);
186 var x = document.getElementById(from);
191 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
192 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
193 removeClass(i_e, "line-highlighted");
196 for (i = from; i <= to; ++i) {
197 addClass(document.getElementById(i), "line-highlighted");
199 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
200 addClass(search, "hidden");
201 removeClass(main, "hidden");
202 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
203 if (browserSupportsHistoryApi()) {
204 history.replaceState(hash, "", "?search=#" + hash);
206 elem = document.getElementById(hash);
208 elem.scrollIntoView();
213 function expandSection(id) {
214 var elem = document.getElementById(id);
215 if (elem && isHidden(elem)) {
216 var h3 = elem.parentNode.previousSibling;
217 if (h3 && h3.tagName !== "H3") {
218 h3 = h3.previousSibling; // skip div.docblock
222 var collapses = h3.getElementsByClassName("collapse-toggle");
223 if (collapses.length > 0) {
224 // The element is not visible, we need to make it appear!
225 collapseDocs(collapses[0], "show");
231 highlightSourceLines(null);
232 window.onhashchange = highlightSourceLines;
234 // Gets the human-readable string for the virtual-key code of the
235 // given KeyboardEvent, ev.
237 // This function is meant as a polyfill for KeyboardEvent#key,
238 // since it is not supported in Trident. We also test for
239 // KeyboardEvent#keyCode because the handleShortcut handler is
240 // also registered for the keydown event, because Blink doesn't fire
241 // keypress on hitting the Escape key.
243 // So I guess you could say things are getting pretty interoperable.
244 function getVirtualKey(ev) {
245 if ("key" in ev && typeof ev.key != "undefined") {
249 var c = ev.charCode || ev.keyCode;
253 return String.fromCharCode(c);
256 function displayHelp(display, ev) {
257 if (display === true) {
258 if (hasClass(help, "hidden")) {
260 removeClass(help, "hidden");
261 addClass(document.body, "blur");
263 } else if (hasClass(help, "hidden") === false) {
265 addClass(help, "hidden");
266 removeClass(document.body, "blur");
270 function handleEscape(ev, help) {
272 var search = document.getElementById("search");
273 if (hasClass(help, "hidden") === false) {
274 displayHelp(false, ev);
275 } else if (hasClass(search, "hidden") === false) {
277 addClass(search, "hidden");
278 removeClass(main, "hidden");
279 document.title = titleBeforeSearch;
284 function handleShortcut(ev) {
285 // Don't interfere with browser shortcuts
286 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
290 var help = document.getElementById("help");
291 if (document.activeElement.tagName === "INPUT") {
292 switch (getVirtualKey(ev)) {
294 handleEscape(ev, help);
298 switch (getVirtualKey(ev)) {
300 handleEscape(ev, help);
305 displayHelp(false, ev);
320 displayHelp(true, ev);
327 function findParentElement(elem, tagName) {
329 if (elem && elem.tagName === tagName) {
332 elem = elem.parentNode;
337 document.onkeypress = handleShortcut;
338 document.onkeydown = handleShortcut;
339 document.onclick = function(ev) {
340 if (hasClass(ev.target, "collapse-toggle")) {
341 collapseDocs(ev.target, "toggle");
342 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
343 collapseDocs(ev.target.parentNode, "toggle");
344 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
347 var set_fragment = function(name) {
348 if (browserSupportsHistoryApi()) {
349 history.replaceState(null, null, "#" + name);
352 location.replace("#" + name);
356 var cur_id = parseInt(ev.target.id, 10);
358 if (ev.shiftKey && prev_id) {
359 if (prev_id > cur_id) {
365 set_fragment(prev_id + "-" + cur_id);
369 set_fragment(cur_id);
371 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
372 addClass(document.getElementById("help"), "hidden");
373 removeClass(document.body, "blur");
375 // Making a collapsed element visible on onhashchange seems
377 var a = findParentElement(ev.target, "A");
379 expandSection(a.hash.replace(/^#/, ""));
384 var x = document.getElementsByClassName("version-selector");
386 x[0].onchange = function() {
388 url = document.location.href,
390 len = rootPath.match(/\.\.\//g).length + 1;
392 for (i = 0; i < len; ++i) {
393 match = url.match(/\/[^\/]*$/);
395 stripped = match[0] + stripped;
397 url = url.substring(0, url.length - match[0].length);
400 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
402 document.location.href = url;
407 * A function to compute the Levenshtein distance between two strings
408 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
409 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
410 * This code is an unmodified version of the code written by Marco de Wit
411 * and was found at http://stackoverflow.com/a/18514751/745719
413 var levenshtein_row2 = [];
414 function levenshtein(s1, s2) {
418 var s1_len = s1.length, s2_len = s2.length;
419 if (s1_len && s2_len) {
420 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
421 while (i1 < s1_len) {
424 while (i2 < s2_len) {
425 c2 = s2.charCodeAt(i2);
429 for (i1 = 0; i1 < s1_len; ++i1) {
430 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
432 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
438 return s1_len + s2_len;
441 function initSearch(rawSearchIndex) {
442 var currentResults, index, searchIndex;
443 var MAX_LEV_DISTANCE = 3;
444 var MAX_RESULTS = 200;
445 var GENERICS_DATA = 1;
449 var params = getQueryStringParams();
451 // Populate search bar with query string search term when provided,
452 // but only if the input bar is empty. This avoid the obnoxious issue
453 // where you start trying to do a search, and the index loads, and
454 // suddenly your search is gone!
455 if (search_input.value === "") {
456 search_input.value = params.search || "";
460 * Executes the query and builds an index of results
461 * @param {[Object]} query [The user query]
462 * @param {[type]} searchWords [The list of search words to query
464 * @param {[type]} filterCrates [Crate to search in if defined]
465 * @return {[type]} [A search index of results]
467 function execQuery(query, searchWords, filterCrates) {
468 function itemTypeFromName(typename) {
469 var length = itemTypes.length;
470 for (var i = 0; i < length; ++i) {
471 if (itemTypes[i] === typename) {
478 var valLower = query.query.toLowerCase(),
480 typeFilter = itemTypeFromName(query.type),
481 results = {}, results_in_args = {}, results_returned = {},
482 split = valLower.split("::");
484 var length = split.length;
485 for (var z = 0; z < length; ++z) {
486 if (split[z] === "") {
492 function transformResults(results, isType) {
494 var length = results.length;
495 for (var i = 0; i < length; ++i) {
496 if (results[i].id > -1) {
497 var obj = searchIndex[results[i].id];
498 obj.lev = results[i].lev;
499 if (isType !== true || obj.type) {
500 var res = buildHrefAndPath(obj);
501 obj.displayPath = pathSplitter(res[0]);
502 obj.fullPath = obj.displayPath + obj.name;
503 // To be sure than it some items aren't considered as duplicate.
504 obj.fullPath += "|" + obj.ty;
507 if (out.length >= MAX_RESULTS) {
516 function sortResults(results, isType) {
518 for (var entry in results) {
519 if (results.hasOwnProperty(entry)) {
520 ar.push(results[entry]);
525 var nresults = results.length;
526 for (i = 0; i < nresults; ++i) {
527 results[i].word = searchWords[results[i].id];
528 results[i].item = searchIndex[results[i].id] || {};
530 // if there are no results then return to default and fail
531 if (results.length === 0) {
535 results.sort(function(aaa, bbb) {
538 // Sort by non levenshtein results and then levenshtein results by the distance
539 // (less changes required to match means higher rankings)
542 if (a !== b) { return a - b; }
544 // sort by crate (non-current crate goes later)
545 a = (aaa.item.crate !== window.currentCrate);
546 b = (bbb.item.crate !== window.currentCrate);
547 if (a !== b) { return a - b; }
549 // sort by exact match (mismatch goes later)
550 a = (aaa.word !== valLower);
551 b = (bbb.word !== valLower);
552 if (a !== b) { return a - b; }
554 // sort by item name length (longer goes later)
557 if (a !== b) { return a - b; }
559 // sort by item name (lexicographically larger goes later)
562 if (a !== b) { return (a > b ? +1 : -1); }
564 // sort by index of keyword in item name (no literal occurrence goes later)
567 if (a !== b) { return a - b; }
568 // (later literal occurrence, if any, goes later)
571 if (a !== b) { return a - b; }
573 // special precedence for primitive and keyword pages
574 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
575 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
578 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
579 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
583 // sort by description (no description goes later)
584 a = (aaa.item.desc === "");
585 b = (bbb.item.desc === "");
586 if (a !== b) { return a - b; }
588 // sort by type (later occurrence in `itemTypes` goes later)
591 if (a !== b) { return a - b; }
593 // sort by path (lexicographically larger goes later)
596 if (a !== b) { return (a > b ? +1 : -1); }
602 var length = results.length;
603 for (i = 0; i < length; ++i) {
604 var result = results[i];
606 // this validation does not make sense when searching by types
607 if (result.dontValidate) {
610 var name = result.item.name.toLowerCase(),
611 path = result.item.path.toLowerCase(),
612 parent = result.item.parent;
614 if (isType !== true &&
615 validateResult(name, path, split, parent) === false)
620 return transformResults(results);
623 function extractGenerics(val) {
624 val = val.toLowerCase();
625 if (val.indexOf("<") !== -1) {
626 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
628 name: val.substring(0, val.indexOf("<")),
629 generics: values.split(/\s*,\s*/),
638 function checkGenerics(obj, val) {
639 // The names match, but we need to be sure that all generics kinda
641 var lev_distance = MAX_LEV_DISTANCE + 1;
642 if (val.generics.length > 0) {
643 if (obj.length > GENERICS_DATA &&
644 obj[GENERICS_DATA].length >= val.generics.length) {
645 var elems = obj[GENERICS_DATA].slice(0);
648 // We need to find the type that matches the most to remove it in order
650 var vlength = val.generics.length;
651 for (var y = 0; y < vlength; ++y) {
652 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
653 var elength = elems.length;
654 for (var x = 0; x < elength; ++x) {
655 var tmp_lev = levenshtein(elems[x], val.generics[y]);
656 if (tmp_lev < lev.lev) {
661 if (lev.pos !== -1) {
662 elems.splice(lev.pos, 1);
663 lev_distance = Math.min(lev.lev, lev_distance);
667 return MAX_LEV_DISTANCE + 1;
670 return lev_distance;//Math.ceil(total / done);
673 return MAX_LEV_DISTANCE + 1;
676 // Check for type name and type generics (if any).
677 function checkType(obj, val, literalSearch) {
678 var lev_distance = MAX_LEV_DISTANCE + 1;
680 if (obj[NAME] === val.name) {
681 if (literalSearch === true) {
682 if (val.generics && val.generics.length !== 0) {
683 if (obj.length > GENERICS_DATA &&
684 obj[GENERICS_DATA].length >= val.generics.length) {
685 var elems = obj[GENERICS_DATA].slice(0);
688 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
690 for (x = 0; allFound === false && x < elems.length; ++x) {
691 allFound = elems[x] === val.generics[y];
693 if (allFound === true) {
694 elems.splice(x - 1, 1);
697 if (allFound === true) {
706 // If the type has generics but don't match, then it won't return at this point.
707 // Otherwise, `checkGenerics` will return 0 and it'll return.
708 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
709 var tmp_lev = checkGenerics(obj, val);
710 if (tmp_lev <= MAX_LEV_DISTANCE) {
717 // Names didn't match so let's check if one of the generic types could.
718 if (literalSearch === true) {
719 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
720 var length = obj[GENERICS_DATA].length;
721 for (x = 0; x < length; ++x) {
722 if (obj[GENERICS_DATA][x] === val.name) {
729 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
730 if (lev_distance <= MAX_LEV_DISTANCE) {
731 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
732 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
733 // We can check if the type we're looking for is inside the generics!
734 var olength = obj[GENERICS_DATA].length;
735 for (x = 0; x < olength; ++x) {
736 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
740 // Now whatever happens, the returned distance is "less good" so we should mark it
741 // as such, and so we add 1 to the distance to make it "less good".
742 return lev_distance + 1;
745 function findArg(obj, val, literalSearch) {
746 var lev_distance = MAX_LEV_DISTANCE + 1;
748 if (obj && obj.type && obj.type[INPUTS_DATA] &&
749 obj.type[INPUTS_DATA].length > 0) {
750 var length = obj.type[INPUTS_DATA].length;
751 for (var i = 0; i < length; i++) {
752 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
753 if (literalSearch === true && tmp === true) {
756 lev_distance = Math.min(tmp, lev_distance);
757 if (lev_distance === 0) {
762 return literalSearch === true ? false : lev_distance;
765 function checkReturned(obj, val, literalSearch) {
766 var lev_distance = MAX_LEV_DISTANCE + 1;
768 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
769 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
770 if (literalSearch === true && tmp === true) {
773 lev_distance = Math.min(tmp, lev_distance);
774 if (lev_distance === 0) {
778 return literalSearch === true ? false : lev_distance;
781 function checkPath(contains, lastElem, ty) {
782 if (contains.length === 0) {
785 var ret_lev = MAX_LEV_DISTANCE + 1;
786 var path = ty.path.split("::");
788 if (ty.parent && ty.parent.name) {
789 path.push(ty.parent.name.toLowerCase());
792 var length = path.length;
793 var clength = contains.length;
794 if (clength > length) {
795 return MAX_LEV_DISTANCE + 1;
797 for (var i = 0; i < length; ++i) {
798 if (i + clength > length) {
803 for (var x = 0; x < clength; ++x) {
804 var lev = levenshtein(path[i + x], contains[x]);
805 if (lev > MAX_LEV_DISTANCE) {
811 if (aborted === false) {
812 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
818 function typePassesFilter(filter, type) {
820 if (filter < 0) return true;
823 if (filter === type) return true;
825 // Match related items
826 var name = itemTypes[type];
827 switch (itemTypes[filter]) {
829 return (name == "associatedconstant");
831 return (name == "method" || name == "tymethod");
833 return (name == "primitive" || name == "keyword");
840 function generateId(ty) {
841 if (ty.parent && ty.parent.name) {
842 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
844 return itemTypes[ty.ty] + ty.path + ty.name;
847 // quoted values mean literal search
848 var nSearchWords = searchWords.length;
854 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
855 val.charAt(val.length - 1) === val.charAt(0))
857 val = extractGenerics(val.substr(1, val.length - 2));
858 for (i = 0; i < nSearchWords; ++i) {
859 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
862 in_args = findArg(searchIndex[i], val, true);
863 returned = checkReturned(searchIndex[i], val, true);
865 fullId = generateId(ty);
867 if (searchWords[i] === val.name) {
868 // filter type: ... queries
869 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
870 results[fullId] === undefined)
872 results[fullId] = {id: i, index: -1};
874 } else if ((in_args === true || returned === true) &&
875 typePassesFilter(typeFilter, searchIndex[i].ty)) {
876 if (in_args === true || returned === true) {
877 if (in_args === true) {
878 results_in_args[fullId] = {
884 if (returned === true) {
885 results_returned[fullId] = {
900 query.inputs = [val];
904 } else if (val.search("->") > -1) {
905 var trimmer = function(s) { return s.trim(); };
906 var parts = val.split("->").map(trimmer);
907 var input = parts[0];
908 // sort inputs so that order does not matter
909 var inputs = input.split(",").map(trimmer).sort();
910 for (i = 0; i < inputs.length; ++i) {
911 inputs[i] = extractGenerics(inputs[i]);
913 var output = extractGenerics(parts[1]);
915 for (i = 0; i < nSearchWords; ++i) {
916 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
919 var type = searchIndex[i].type;
924 fullId = generateId(ty);
926 // allow searching for void (no output) functions as well
927 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
928 returned = checkReturned(ty, output, true);
929 if (output.name === "*" || returned === true) {
937 for (var it = 0; allFound === true && it < inputs.length; it++) {
938 allFound = checkType(type, inputs[it], true);
942 if (in_args === true) {
943 results_in_args[fullId] = {
949 if (returned === true) {
950 results_returned[fullId] = {
956 if (module === true) {
965 query.inputs = inputs.map(function(input) {
968 query.output = output.name;
970 query.inputs = [val];
973 // gather matching search results up to a certain maximum
974 val = val.replace(/\_/g, "");
976 var valGenerics = extractGenerics(val);
978 var paths = valLower.split("::");
980 for (j = 0; j < paths.length; ++j) {
981 if (paths[j] === "") {
986 val = paths[paths.length - 1];
987 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
989 for (j = 0; j < nSearchWords; ++j) {
993 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
998 if (paths.length > 1) {
999 lev = checkPath(contains, paths[paths.length - 1], ty);
1000 if (lev > MAX_LEV_DISTANCE) {
1002 } else if (lev > 0) {
1007 returned = MAX_LEV_DISTANCE + 1;
1008 in_args = MAX_LEV_DISTANCE + 1;
1010 // we want lev results to go lower than others
1011 lev = MAX_LEV_DISTANCE + 1;
1012 fullId = generateId(ty);
1014 if (searchWords[j].indexOf(split[i]) > -1 ||
1015 searchWords[j].indexOf(val) > -1 ||
1016 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1018 // filter type: ... queries
1019 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1020 index = searchWords[j].replace(/_/g, "").indexOf(val);
1023 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1024 if (typePassesFilter(typeFilter, ty.ty) === false) {
1025 lev = MAX_LEV_DISTANCE + 1;
1030 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1031 if (typePassesFilter(typeFilter, ty.ty) === false) {
1032 in_args = MAX_LEV_DISTANCE + 1;
1035 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1036 if (typePassesFilter(typeFilter, ty.ty) === false) {
1037 returned = MAX_LEV_DISTANCE + 1;
1042 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1043 if (val.length < 6) {
1049 if (in_args <= MAX_LEV_DISTANCE) {
1050 if (results_in_args[fullId] === undefined) {
1051 results_in_args[fullId] = {
1057 results_in_args[fullId].lev =
1058 Math.min(results_in_args[fullId].lev, in_args);
1060 if (returned <= MAX_LEV_DISTANCE) {
1061 if (results_returned[fullId] === undefined) {
1062 results_returned[fullId] = {
1068 results_returned[fullId].lev =
1069 Math.min(results_returned[fullId].lev, returned);
1071 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1072 if (index !== -1 && paths.length < 2) {
1075 if (results[fullId] === undefined) {
1082 results[fullId].lev = Math.min(results[fullId].lev, lev);
1088 "in_args": sortResults(results_in_args, true),
1089 "returned": sortResults(results_returned, true),
1090 "others": sortResults(results),
1092 if (ALIASES && ALIASES[window.currentCrate] &&
1093 ALIASES[window.currentCrate][query.raw]) {
1094 var aliases = ALIASES[window.currentCrate][query.raw];
1095 for (i = 0; i < aliases.length; ++i) {
1096 aliases[i].is_alias = true;
1097 aliases[i].alias = query.raw;
1098 aliases[i].path = aliases[i].p;
1099 var res = buildHrefAndPath(aliases[i]);
1100 aliases[i].displayPath = pathSplitter(res[0]);
1101 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1102 aliases[i].href = res[1];
1103 ret.others.unshift(aliases[i]);
1104 if (ret.others.length > MAX_RESULTS) {
1113 * Validate performs the following boolean logic. For example:
1114 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1115 * exists in (name || path || parent) OR => ("file" && "open") exists in
1118 * This could be written functionally, but I wanted to minimise
1119 * functions on stack.
1121 * @param {[string]} name [The name of the result]
1122 * @param {[string]} path [The path of the result]
1123 * @param {[string]} keys [The keys to be used (["file", "open"])]
1124 * @param {[object]} parent [The parent of the result]
1125 * @return {[boolean]} [Whether the result is valid or not]
1127 function validateResult(name, path, keys, parent) {
1128 for (var i = 0; i < keys.length; ++i) {
1129 // each check is for validation so we negate the conditions and invalidate
1131 // check for an exact name match
1132 name.indexOf(keys[i]) > -1 ||
1133 // then an exact path match
1134 path.indexOf(keys[i]) > -1 ||
1135 // next if there is a parent, check for exact parent match
1136 (parent !== undefined &&
1137 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1138 // lastly check to see if the name was a levenshtein match
1139 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1146 function getQuery(raw) {
1147 var matches, type, query;
1150 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1152 type = matches[1].replace(/^const$/, "constant");
1153 query = query.substring(matches[0].length);
1164 function initSearchNav() {
1167 var click_func = function(e) {
1169 // to retrieve the real "owner" of the event.
1170 while (el.tagName !== "TR") {
1173 var dst = e.target.getElementsByTagName("a");
1174 if (dst.length < 1) {
1178 if (window.location.pathname === dst.pathname) {
1179 addClass(document.getElementById("search"), "hidden");
1180 removeClass(main, "hidden");
1181 document.location.href = dst.href;
1184 var mouseover_func = function(e) {
1186 // to retrieve the real "owner" of the event.
1187 while (el.tagName !== "TR") {
1190 clearTimeout(hoverTimeout);
1191 hoverTimeout = setTimeout(function() {
1192 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1193 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1194 removeClass(i_e, "highlighted");
1197 addClass(el, "highlighted");
1200 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1201 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1202 i_e.onclick = click_func;
1203 i_e.onmouseover = mouseover_func;
1207 search_input.onkeydown = function(e) {
1208 // "actives" references the currently highlighted item in each search tab.
1209 // Each array in "actives" represents a tab.
1210 var actives = [[], [], []];
1211 // "current" is used to know which tab we're looking into.
1213 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1214 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1215 actives[current].push(e);
1220 if (e.which === 38) { // up
1221 if (!actives[currentTab].length ||
1222 !actives[currentTab][0].previousElementSibling) {
1226 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1227 removeClass(actives[currentTab][0], "highlighted");
1228 } else if (e.which === 40) { // down
1229 if (!actives[currentTab].length) {
1230 var results = document.getElementsByClassName("search-results");
1231 if (results.length > 0) {
1232 var res = results[currentTab].getElementsByClassName("result");
1233 if (res.length > 0) {
1234 addClass(res[0], "highlighted");
1237 } else if (actives[currentTab][0].nextElementSibling) {
1238 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1239 removeClass(actives[currentTab][0], "highlighted");
1241 } else if (e.which === 13) { // return
1242 if (actives[currentTab].length) {
1243 document.location.href =
1244 actives[currentTab][0].getElementsByTagName("a")[0].href;
1246 } else if (e.which === 9) { // tab
1248 printTab(currentTab > 0 ? currentTab - 1 : 2);
1250 printTab(currentTab > 1 ? 0 : currentTab + 1);
1253 } else if (e.which === 16) { // shift
1254 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1255 } else if (e.which === 27) { // escape
1256 removeClass(actives[currentTab][0], "highlighted");
1257 search_input.value = "";
1259 } else if (actives[currentTab].length > 0) {
1260 removeClass(actives[currentTab][0], "highlighted");
1265 function buildHrefAndPath(item) {
1268 var type = itemTypes[item.ty];
1269 var name = item.name;
1271 if (type === "mod") {
1272 displayPath = item.path + "::";
1273 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1274 name + "/index.html";
1275 } else if (type === "primitive" || type === "keyword") {
1277 href = rootPath + item.path.replace(/::/g, "/") +
1278 "/" + type + "." + name + ".html";
1279 } else if (type === "externcrate") {
1281 href = rootPath + name + "/index.html";
1282 } else if (item.parent !== undefined) {
1283 var myparent = item.parent;
1284 var anchor = "#" + type + "." + name;
1285 var parentType = itemTypes[myparent.ty];
1286 if (parentType === "primitive") {
1287 displayPath = myparent.name + "::";
1289 displayPath = item.path + "::" + myparent.name + "::";
1291 href = rootPath + item.path.replace(/::/g, "/") +
1293 "." + myparent.name +
1296 displayPath = item.path + "::";
1297 href = rootPath + item.path.replace(/::/g, "/") +
1298 "/" + type + "." + name + ".html";
1300 return [displayPath, href];
1303 function escape(content) {
1304 var h1 = document.createElement("h1");
1305 h1.textContent = content;
1306 return h1.innerHTML;
1309 function pathSplitter(path) {
1310 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1311 if (tmp.endsWith("<span>")) {
1312 return tmp.slice(0, tmp.length - 6);
1317 function addTab(array, query, display) {
1318 var extraStyle = "";
1319 if (display === false) {
1320 extraStyle = " style=\"display: none;\"";
1324 var duplicates = {};
1326 if (array.length > 0) {
1327 output = "<table class=\"search-results\"" + extraStyle + ">";
1329 array.forEach(function(item) {
1333 type = itemTypes[item.ty];
1335 if (item.is_alias !== true) {
1336 if (duplicates[item.fullPath]) {
1339 duplicates[item.fullPath] = true;
1343 output += "<tr class=\"" + type + " result\"><td>" +
1344 "<a href=\"" + item.href + "\">" +
1345 (item.is_alias === true ?
1346 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1347 "class=\"grey\"><i> - see </i></span>") : "") +
1348 item.displayPath + "<span class=\"" + type + "\">" +
1349 name + "</span></a></td><td>" +
1350 "<a href=\"" + item.href + "\">" +
1351 "<span class=\"desc\">" + escape(item.desc) +
1352 " </span></a></td></tr>";
1354 output += "</table>";
1356 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1357 "Try on <a href=\"https://duckduckgo.com/?q=" +
1358 encodeURIComponent("rust " + query.query) +
1359 "\">DuckDuckGo</a>?<br/><br/>" +
1360 "Or try looking in one of these:<ul><li>The <a " +
1361 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1362 " for technical details about the language.</li><li><a " +
1363 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1364 "Example</a> for expository code examples.</a></li><li>The <a " +
1365 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1366 "introductions to language features and the language itself.</li><li><a " +
1367 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1368 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1370 return [output, length];
1373 function makeTabHeader(tabNb, text, nbElems) {
1374 if (currentTab === tabNb) {
1375 return "<div class=\"selected\">" + text +
1376 " <div class=\"count\">(" + nbElems + ")</div></div>";
1378 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1381 function showResults(results) {
1382 if (results.others.length === 1 &&
1383 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1384 var elem = document.createElement("a");
1385 elem.href = results.others[0].href;
1386 elem.style.display = "none";
1387 // For firefox, we need the element to be in the DOM so it can be clicked.
1388 document.body.appendChild(elem);
1391 var query = getQuery(search_input.value);
1393 currentResults = query.id;
1395 var ret_others = addTab(results.others, query);
1396 var ret_in_args = addTab(results.in_args, query, false);
1397 var ret_returned = addTab(results.returned, query, false);
1399 var output = "<h1>Results for " + escape(query.query) +
1400 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1401 "<div id=\"titles\">" +
1402 makeTabHeader(0, "In Names", ret_others[1]) +
1403 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1404 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1405 "</div><div id=\"results\">" +
1406 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1408 addClass(main, "hidden");
1409 var search = document.getElementById("search");
1410 removeClass(search, "hidden");
1411 search.innerHTML = output;
1412 var tds = search.getElementsByTagName("td");
1414 if (tds.length > 0) {
1415 td_width = tds[0].offsetWidth;
1417 var width = search.offsetWidth - 40 - td_width;
1418 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1419 e.style.width = width + "px";
1422 var elems = document.getElementById("titles").childNodes;
1423 elems[0].onclick = function() { printTab(0); };
1424 elems[1].onclick = function() { printTab(1); };
1425 elems[2].onclick = function() { printTab(2); };
1426 printTab(currentTab);
1429 function execSearch(query, searchWords, filterCrates) {
1430 function getSmallest(arrays, positions, notDuplicates) {
1433 for (var it = 0; it < positions.length; ++it) {
1434 if (arrays[it].length > positions[it] &&
1435 (start === null || start > arrays[it][positions[it]].lev) &&
1436 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1437 start = arrays[it][positions[it]].lev;
1443 function mergeArrays(arrays) {
1446 var notDuplicates = {};
1448 for (var x = 0; x < arrays.length; ++x) {
1451 while (ret.length < MAX_RESULTS) {
1452 var smallest = getSmallest(arrays, positions, notDuplicates);
1454 if (smallest === null) {
1457 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1458 if (arrays[x].length > positions[x] &&
1459 arrays[x][positions[x]].lev === smallest &&
1460 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1461 ret.push(arrays[x][positions[x]]);
1462 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1470 var queries = query.raw.split(",");
1477 for (var i = 0; i < queries.length; ++i) {
1478 query = queries[i].trim();
1479 if (query.length !== 0) {
1480 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1482 results.in_args.push(tmp.in_args);
1483 results.returned.push(tmp.returned);
1484 results.others.push(tmp.others);
1487 if (queries.length > 1) {
1489 "in_args": mergeArrays(results.in_args),
1490 "returned": mergeArrays(results.returned),
1491 "others": mergeArrays(results.others),
1495 "in_args": results.in_args[0],
1496 "returned": results.returned[0],
1497 "others": results.others[0],
1502 function getFilterCrates() {
1503 var elem = document.getElementById("crate-search");
1505 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1511 function search(e, forced) {
1512 var params = getQueryStringParams();
1513 var query = getQuery(search_input.value.trim());
1519 if (query.query.length === 0) {
1522 if (forced !== true && query.id === currentResults) {
1523 if (query.query.length > 0) {
1524 putBackSearch(search_input);
1529 // Update document title to maintain a meaningful browser history
1530 document.title = "Results for " + query.query + " - Rust";
1532 // Because searching is incremental by character, only the most
1533 // recent search query is added to the browser history.
1534 if (browserSupportsHistoryApi()) {
1535 if (!history.state && !params.search) {
1536 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1538 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1542 var filterCrates = getFilterCrates();
1543 showResults(execSearch(query, index, filterCrates), filterCrates);
1546 function buildIndex(rawSearchIndex) {
1548 var searchWords = [];
1551 for (var crate in rawSearchIndex) {
1552 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1554 searchWords.push(crate);
1557 ty: 1, // == ExternCrate
1560 desc: rawSearchIndex[crate].doc,
1564 // an array of [(Number) item type,
1566 // (String) full path or empty string for previous path,
1567 // (String) description,
1568 // (Number | null) the parent path index to `paths`]
1569 // (Object | null) the type of the function (if any)
1570 var items = rawSearchIndex[crate].items;
1571 // an array of [(Number) item type,
1573 var paths = rawSearchIndex[crate].paths;
1575 // convert `paths` into an object form
1576 var len = paths.length;
1577 for (i = 0; i < len; ++i) {
1578 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1581 // convert `items` into an object form, and construct word indices.
1583 // before any analysis is performed lets gather the search terms to
1584 // search against apart from the rest of the data. This is a quick
1585 // operation that is cached for the life of the page state so that
1586 // all other search operations have access to this cached data for
1587 // faster analysis operations
1590 for (i = 0; i < len; ++i) {
1591 var rawRow = items[i];
1592 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1593 path: rawRow[2] || lastPath, desc: rawRow[3],
1594 parent: paths[rawRow[4]], type: rawRow[5]};
1595 searchIndex.push(row);
1596 if (typeof row.name === "string") {
1597 var word = row.name.toLowerCase();
1598 searchWords.push(word);
1600 searchWords.push("");
1602 lastPath = row.path;
1608 function startSearch() {
1610 var callback = function() {
1611 clearTimeout(searchTimeout);
1612 if (search_input.value.length === 0) {
1613 if (browserSupportsHistoryApi()) {
1614 history.replaceState("", "std - Rust", "?search=");
1616 if (hasClass(main, "content")) {
1617 removeClass(main, "hidden");
1619 var search_c = document.getElementById("search");
1620 if (hasClass(search_c, "content")) {
1621 addClass(search_c, "hidden");
1624 searchTimeout = setTimeout(search, 500);
1627 search_input.onkeyup = callback;
1628 search_input.oninput = callback;
1629 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1631 clearTimeout(searchTimeout);
1634 search_input.onchange = function(e) {
1635 // Do NOT e.preventDefault() here. It will prevent pasting.
1636 clearTimeout(searchTimeout);
1637 // zero-timeout necessary here because at the time of event handler execution the
1638 // pasted content is not in the input field yet. Shouldn’t make any difference for
1640 setTimeout(search, 0);
1642 search_input.onpaste = search_input.onchange;
1644 var selectCrate = document.getElementById('crate-search');
1646 selectCrate.onchange = function() {
1647 search(undefined, true);
1651 // Push and pop states are used to add search results to the browser
1653 if (browserSupportsHistoryApi()) {
1654 // Store the previous <title> so we can revert back to it later.
1655 var previousTitle = document.title;
1657 window.onpopstate = function(e) {
1658 var params = getQueryStringParams();
1659 // When browsing back from search results the main page
1660 // visibility must be reset.
1661 if (!params.search) {
1662 if (hasClass(main, "content")) {
1663 removeClass(main, "hidden");
1665 var search_c = document.getElementById("search");
1666 if (hasClass(search_c, "content")) {
1667 addClass(search_c, "hidden");
1670 // Revert to the previous title manually since the History
1671 // API ignores the title parameter.
1672 document.title = previousTitle;
1673 // When browsing forward to search results the previous
1674 // search will be repeated, so the currentResults are
1675 // cleared to ensure the search is successful.
1676 currentResults = null;
1677 // Synchronize search bar with query string state and
1678 // perform the search. This will empty the bar if there's
1679 // nothing there, which lets you really go back to a
1680 // previous state with nothing in the bar.
1681 if (params.search) {
1682 search_input.value = params.search;
1684 search_input.value = "";
1686 // Some browsers fire "onpopstate" for every page load
1687 // (Chrome), while others fire the event only when actually
1688 // popping a state (Firefox), which is why search() is
1689 // called both here and at the end of the startSearch()
1697 index = buildIndex(rawSearchIndex);
1700 // Draw a convenient sidebar of known crates if we have a listing
1701 if (rootPath === "../" || rootPath === "./") {
1702 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1704 var div = document.createElement("div");
1705 div.className = "block crate";
1706 div.innerHTML = "<h3>Crates</h3>";
1707 var ul = document.createElement("ul");
1708 div.appendChild(ul);
1711 for (var crate in rawSearchIndex) {
1712 if (!rawSearchIndex.hasOwnProperty(crate)) {
1718 for (var i = 0; i < crates.length; ++i) {
1719 var klass = "crate";
1720 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1721 klass += " current";
1723 var link = document.createElement("a");
1724 link.href = rootPath + crates[i] + "/index.html";
1725 link.title = rawSearchIndex[crates[i]].doc;
1726 link.className = klass;
1727 link.textContent = crates[i];
1729 var li = document.createElement("li");
1730 li.appendChild(link);
1733 sidebar.appendChild(div);
1738 window.initSearch = initSearch;
1740 // delayed sidebar rendering.
1741 function initSidebarItems(items) {
1742 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1743 var current = window.sidebarCurrent;
1745 function block(shortty, longty) {
1746 var filtered = items[shortty];
1751 var div = document.createElement("div");
1752 div.className = "block " + shortty;
1753 var h3 = document.createElement("h3");
1754 h3.textContent = longty;
1755 div.appendChild(h3);
1756 var ul = document.createElement("ul");
1758 var length = filtered.length;
1759 for (var i = 0; i < length; ++i) {
1760 var item = filtered[i];
1762 var desc = item[1]; // can be null
1764 var klass = shortty;
1765 if (name === current.name && shortty === current.ty) {
1766 klass += " current";
1769 if (shortty === "mod") {
1770 path = name + "/index.html";
1772 path = shortty + "." + name + ".html";
1774 var link = document.createElement("a");
1775 link.href = current.relpath + path;
1777 link.className = klass;
1778 link.textContent = name;
1779 var li = document.createElement("li");
1780 li.appendChild(link);
1783 div.appendChild(ul);
1785 sidebar.appendChild(div);
1789 block("primitive", "Primitive Types");
1790 block("mod", "Modules");
1791 block("macro", "Macros");
1792 block("struct", "Structs");
1793 block("enum", "Enums");
1794 block("union", "Unions");
1795 block("constant", "Constants");
1796 block("static", "Statics");
1797 block("trait", "Traits");
1798 block("fn", "Functions");
1799 block("type", "Type Definitions");
1800 block("foreigntype", "Foreign Types");
1801 block("keyword", "Keywords");
1804 window.initSidebarItems = initSidebarItems;
1806 window.register_implementors = function(imp) {
1807 var implementors = document.getElementById("implementors-list");
1808 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1810 var libs = Object.getOwnPropertyNames(imp);
1811 var llength = libs.length;
1812 for (var i = 0; i < llength; ++i) {
1813 if (libs[i] === currentCrate) { continue; }
1814 var structs = imp[libs[i]];
1816 var slength = structs.length;
1818 for (var j = 0; j < slength; ++j) {
1819 var struct = structs[j];
1821 var list = struct.synthetic ? synthetic_implementors : implementors;
1823 if (struct.synthetic) {
1824 var stlength = struct.types.length;
1825 for (var k = 0; k < stlength; k++) {
1826 if (window.inlined_types.has(struct.types[k])) {
1827 continue struct_loop;
1829 window.inlined_types.add(struct.types[k]);
1833 var code = document.createElement("code");
1834 code.innerHTML = struct.text;
1836 var x = code.getElementsByTagName("a");
1837 var xlength = x.length;
1838 for (var it = 0; it < xlength; it++) {
1839 var href = x[it].getAttribute("href");
1840 if (href && href.indexOf("http") !== 0) {
1841 x[it].setAttribute("href", rootPath + href);
1844 var display = document.createElement("h3");
1845 addClass(display, "impl");
1846 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1847 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1848 "</tbody></table></span>";
1849 list.appendChild(display);
1853 if (window.pending_implementors) {
1854 window.register_implementors(window.pending_implementors);
1857 function labelForToggleButton(sectionIsCollapsed) {
1858 if (sectionIsCollapsed) {
1859 // button will expand the section
1862 // button will collapse the section
1863 // note that this text is also set in the HTML template in render.rs
1864 return "\u2212"; // "\u2212" is "−" minus sign
1867 function onEveryMatchingChild(elem, className, func) {
1868 if (elem && className && func) {
1869 var length = elem.childNodes.length;
1870 var nodes = elem.childNodes;
1871 for (var i = 0; i < length; ++i) {
1872 if (hasClass(nodes[i], className)) {
1875 onEveryMatchingChild(nodes[i], className, func);
1881 function toggleAllDocs(pageId, fromAutoCollapse) {
1882 var innerToggle = document.getElementById("toggle-all-docs");
1886 if (hasClass(innerToggle, "will-expand")) {
1887 updateLocalStorage("rustdoc-collapse", "false");
1888 removeClass(innerToggle, "will-expand");
1889 onEveryMatchingChild(innerToggle, "inner", function(e) {
1890 e.innerHTML = labelForToggleButton(false);
1892 innerToggle.title = "collapse all docs";
1893 if (fromAutoCollapse !== true) {
1894 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1895 collapseDocs(e, "show");
1899 updateLocalStorage("rustdoc-collapse", "true");
1900 addClass(innerToggle, "will-expand");
1901 onEveryMatchingChild(innerToggle, "inner", function(e) {
1902 e.innerHTML = labelForToggleButton(true);
1904 innerToggle.title = "expand all docs";
1905 if (fromAutoCollapse !== true) {
1906 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1907 collapseDocs(e, "hide", pageId);
1913 function collapseDocs(toggle, mode, pageId) {
1914 if (!toggle || !toggle.parentNode) {
1918 function adjustToggle(arg) {
1919 return function(e) {
1920 if (hasClass(e, "toggle-label")) {
1922 e.style.display = "inline-block";
1924 e.style.display = "none";
1927 if (hasClass(e, "inner")) {
1928 e.innerHTML = labelForToggleButton(arg);
1933 function implHider(addOrRemove) {
1934 return function(n) {
1935 var is_method = hasClass(n, "method");
1936 if (is_method || hasClass(n, "type")) {
1937 if (is_method === true) {
1939 addClass(n, "hidden-by-impl-hider");
1941 removeClass(n, "hidden-by-impl-hider");
1944 var ns = n.nextElementSibling;
1947 hasClass(ns, "docblock") ||
1948 hasClass(ns, "stability"))) {
1950 addClass(ns, "hidden-by-impl-hider");
1952 removeClass(ns, "hidden-by-impl-hider");
1954 ns = ns.nextElementSibling;
1965 if (hasClass(toggle.parentNode, "impl") === false) {
1966 relatedDoc = toggle.parentNode.nextElementSibling;
1967 if (hasClass(relatedDoc, "stability")) {
1968 relatedDoc = relatedDoc.nextElementSibling;
1970 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1971 if (mode === "toggle") {
1972 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1978 if (action === "hide") {
1979 addClass(relatedDoc, "hidden-by-usual-hider");
1980 onEachLazy(toggle.childNodes, adjustToggle(true));
1981 addClass(toggle.parentNode, "collapsed");
1982 } else if (action === "show") {
1983 removeClass(relatedDoc, "hidden-by-usual-hider");
1984 removeClass(toggle.parentNode, "collapsed");
1985 onEachLazy(toggle.childNodes, adjustToggle(false));
1989 // we are collapsing the impl block
1991 var parentElem = toggle.parentNode;
1992 relatedDoc = parentElem;
1993 var docblock = relatedDoc.nextElementSibling;
1995 while (hasClass(relatedDoc, "impl-items") === false) {
1996 relatedDoc = relatedDoc.nextElementSibling;
1999 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2000 (pageId && document.getElementById(pageId))) {
2004 // Hide all functions, but not associated types/consts
2006 if (mode === "toggle") {
2007 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2008 hasClass(docblock, "hidden-by-impl-hider")) {
2015 if (action === "show") {
2016 removeClass(relatedDoc, "fns-now-collapsed");
2017 removeClass(docblock, "hidden-by-usual-hider");
2018 onEachLazy(toggle.childNodes, adjustToggle(false));
2019 onEachLazy(relatedDoc.childNodes, implHider(false));
2020 } else if (action === "hide") {
2021 addClass(relatedDoc, "fns-now-collapsed");
2022 addClass(docblock, "hidden-by-usual-hider");
2023 onEachLazy(toggle.childNodes, adjustToggle(true));
2024 onEachLazy(relatedDoc.childNodes, implHider(true));
2029 function collapser(e, collapse) {
2030 // inherent impl ids are like "impl" or impl-<number>'.
2031 // they will never be hidden by default.
2032 var n = e.parentElement;
2033 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2034 // Automatically minimize all non-inherent impls
2035 if (collapse || hasClass(n, "impl")) {
2036 collapseDocs(e, "hide", pageId);
2041 function autoCollapse(pageId, collapse) {
2043 toggleAllDocs(pageId, true);
2044 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2045 var impl_list = document.getElementById("implementations-list");
2047 if (impl_list !== null) {
2048 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2049 collapser(e, collapse);
2055 var toggles = document.getElementById("toggle-all-docs");
2057 toggles.onclick = toggleAllDocs;
2060 function insertAfter(newNode, referenceNode) {
2061 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2064 function createSimpleToggle(sectionIsCollapsed) {
2065 var toggle = document.createElement("a");
2066 toggle.href = "javascript:void(0)";
2067 toggle.className = "collapse-toggle";
2068 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2073 var toggle = createSimpleToggle(false);
2075 var func = function(e) {
2076 var next = e.nextElementSibling;
2080 if (hasClass(next, "docblock") ||
2081 (hasClass(next, "stability") &&
2082 hasClass(next.nextElementSibling, "docblock"))) {
2083 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2087 var funcImpl = function(e) {
2088 var next = e.nextElementSibling;
2089 if (next && hasClass(next, "docblock")) {
2090 next = next.nextElementSibling;
2095 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2096 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2100 onEachLazy(document.getElementsByClassName("method"), func);
2101 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2102 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2103 var impl_call = function() {};
2104 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2105 impl_call = function(e, newToggle, pageId) {
2106 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2107 // Automatically minimize all non-inherent impls
2108 if (hasClass(e, "impl")) {
2109 collapseDocs(newToggle, "hide", pageId);
2114 var pageId = getPageId();
2115 var newToggle = document.createElement("a");
2116 newToggle.href = "javascript:void(0)";
2117 newToggle.className = "collapse-toggle hidden-default collapsed";
2118 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2119 "</span>] Show hidden undocumented items";
2120 function toggleClicked() {
2121 if (hasClass(this, "collapsed")) {
2122 removeClass(this, "collapsed");
2123 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2124 if (hasClass(x, "content") === false) {
2125 removeClass(x, "hidden");
2129 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2130 "</span>] Hide undocumented items";
2132 addClass(this, "collapsed");
2133 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2134 if (hasClass(x, "content") === false) {
2135 addClass(x, "hidden");
2136 removeClass(x, "x");
2139 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2140 "</span>] Show hidden undocumented items";
2143 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2144 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2145 var hiddenElems = e.getElementsByClassName("hidden");
2146 var needToggle = false;
2148 var hlength = hiddenElems.length;
2149 for (var i = 0; i < hlength; ++i) {
2150 if (hasClass(hiddenElems[i], "content") === false &&
2151 hasClass(hiddenElems[i], "docblock") === false) {
2156 if (needToggle === true) {
2157 var inner_toggle = newToggle.cloneNode(true);
2158 inner_toggle.onclick = toggleClicked;
2159 e.insertBefore(inner_toggle, e.firstChild);
2160 impl_call(e, inner_toggle, pageId);
2164 function createToggle(otherMessage, fontSize, extraClass, show) {
2165 var span = document.createElement("span");
2166 span.className = "toggle-label";
2168 span.style.display = "none";
2170 if (!otherMessage) {
2171 span.innerHTML = " Expand description";
2173 span.innerHTML = otherMessage;
2177 span.style.fontSize = fontSize;
2180 var mainToggle = toggle.cloneNode(true);
2181 mainToggle.appendChild(span);
2183 var wrapper = document.createElement("div");
2184 wrapper.className = "toggle-wrapper";
2186 addClass(wrapper, "collapsed");
2187 var inner = mainToggle.getElementsByClassName("inner");
2188 if (inner && inner.length > 0) {
2189 inner[0].innerHTML = "+";
2193 addClass(wrapper, extraClass);
2195 wrapper.appendChild(mainToggle);
2199 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2200 function buildToggleWrapper(e) {
2201 if (hasClass(e, "autohide")) {
2202 var wrap = e.previousElementSibling;
2203 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2204 var inner_toggle = wrap.childNodes[0];
2205 var extra = e.childNodes[0].tagName === "H3";
2207 e.style.display = "none";
2208 addClass(wrap, "collapsed");
2209 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2210 e.innerHTML = labelForToggleButton(true);
2212 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2213 e.style.display = "inline-block";
2214 if (extra === true) {
2215 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2220 if (e.parentNode.id === "main") {
2221 var otherMessage = "";
2225 if (hasClass(e, "type-decl")) {
2227 otherMessage = " Show declaration";
2228 if (showItemDeclarations === false) {
2229 extraClass = "collapsed";
2231 } else if (hasClass(e, "sub-variant")) {
2232 otherMessage = " Show fields";
2233 } else if (hasClass(e, "non-exhaustive")) {
2234 otherMessage = " This ";
2235 if (hasClass(e, "non-exhaustive-struct")) {
2236 otherMessage += "struct";
2237 } else if (hasClass(e, "non-exhaustive-enum")) {
2238 otherMessage += "enum";
2239 } else if (hasClass(e, "non-exhaustive-type")) {
2240 otherMessage += "type";
2242 otherMessage += " is marked as non-exhaustive";
2243 } else if (hasClass(e.childNodes[0], "impl-items")) {
2244 extraClass = "marg-left";
2247 e.parentNode.insertBefore(
2248 createToggle(otherMessage,
2251 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2253 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2254 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2259 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2260 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2262 // In the search display, allows to switch between tabs.
2263 function printTab(nb) {
2264 if (nb === 0 || nb === 1 || nb === 2) {
2268 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2269 if (nb_copy === 0) {
2270 addClass(elem, "selected");
2272 removeClass(elem, "selected");
2276 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2278 elem.style.display = "";
2280 elem.style.display = "none";
2286 function createToggleWrapper(tog) {
2287 var span = document.createElement("span");
2288 span.className = "toggle-label";
2289 span.style.display = "none";
2290 span.innerHTML = " Expand attributes";
2291 tog.appendChild(span);
2293 var wrapper = document.createElement("div");
2294 wrapper.className = "toggle-wrapper toggle-attributes";
2295 wrapper.appendChild(tog);
2299 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2300 var itemAttributesFunc = function() {};
2301 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2302 itemAttributesFunc = function(x) {
2303 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2306 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2307 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2308 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2309 itemAttributesFunc(i_e);
2312 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2313 var lineNumbersFunc = function() {};
2314 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2315 lineNumbersFunc = function(x) {
2316 var count = x.textContent.split("\n").length;
2318 for (var i = 0; i < count; ++i) {
2321 var node = document.createElement("pre");
2322 addClass(node, "line-number");
2323 node.innerHTML = elems.join("\n");
2324 x.parentNode.insertBefore(node, x);
2327 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2328 if (hasClass(e, "compile_fail")) {
2329 e.addEventListener("mouseover", function(event) {
2330 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2332 e.addEventListener("mouseout", function(event) {
2333 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2335 } else if (hasClass(e, "ignore")) {
2336 e.addEventListener("mouseover", function(event) {
2337 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2339 e.addEventListener("mouseout", function(event) {
2340 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2346 function showModal(content) {
2347 var modal = document.createElement("div");
2348 modal.id = "important";
2349 addClass(modal, "modal");
2350 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2351 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2353 document.getElementsByTagName("body")[0].appendChild(modal);
2354 document.getElementById("modal-close").onclick = hideModal;
2355 modal.onclick = hideModal;
2358 function hideModal() {
2359 var modal = document.getElementById("important");
2361 modal.parentNode.removeChild(modal);
2365 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2366 e.onclick = function() {
2367 showModal(e.lastElementChild.innerHTML);
2371 function putBackSearch(search_input) {
2372 if (search_input.value !== "") {
2373 addClass(main, "hidden");
2374 removeClass(document.getElementById("search"), "hidden");
2375 if (browserSupportsHistoryApi()) {
2376 history.replaceState(search_input.value,
2378 "?search=" + encodeURIComponent(search_input.value));
2384 search_input.onfocus = function() {
2385 putBackSearch(this);
2389 var params = getQueryStringParams();
2390 if (params && params.search) {
2391 addClass(main, "hidden");
2392 var search = document.getElementById("search");
2393 removeClass(search, "hidden");
2394 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2397 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2399 sidebar_menu.onclick = function() {
2400 var sidebar = document.getElementsByClassName("sidebar")[0];
2401 if (hasClass(sidebar, "mobile") === true) {
2409 window.onresize = function() {
2413 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2415 if (window.location.hash && window.location.hash.length > 0) {
2416 expandSection(window.location.hash.replace(/^#/, ""));
2420 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2423 onEachLazy(main.childNodes, function(e) {
2424 if (e.tagName === "H2" || e.tagName === "H3") {
2425 e.nextElementSibling.style.display = "block";
2430 function addSearchOptions(crates) {
2431 var elem = document.getElementById('crate-search');
2436 var crates_text = [];
2437 for (var crate in crates) {
2438 if (crates.hasOwnProperty(crate)) {
2439 crates_text.push(crate);
2442 crates_text.sort(function(a, b) {
2443 var lower_a = a.toLowerCase();
2444 var lower_b = b.toLowerCase();
2446 if (lower_a < lower_b) {
2448 } else if (lower_a > lower_b) {
2453 for (var i = 0; i < crates_text.length; ++i) {
2454 var option = document.createElement("option");
2455 option.value = crates_text[i];
2456 option.innerText = crates_text[i];
2457 elem.appendChild(option);
2461 window.addSearchOptions = addSearchOptions;
2464 // Sets the focus on the search bar at the top of the page
2465 function focusSearchBar() {
2466 document.getElementsByClassName("search-input")[0].focus();
2469 // Removes the focus from the search bar
2470 function defocusSearchBar() {
2471 document.getElementsByClassName("search-input")[0].blur();