2 /* global ALIASES, currentCrate, rootPath */
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global isHidden onEach, removeClass, updateLocalStorage */
8 if (!String.prototype.startsWith) {
9 String.prototype.startsWith = function(searchString, position) {
10 position = position || 0;
11 return this.indexOf(searchString, position) === position;
14 if (!String.prototype.endsWith) {
15 String.prototype.endsWith = function(suffix, length) {
16 var l = length || this.length;
17 return this.indexOf(suffix, l - suffix.length) !== -1;
21 if (!DOMTokenList.prototype.add) {
22 DOMTokenList.prototype.add = function(className) {
23 if (className && !hasClass(this, className)) {
24 if (this.className && this.className.length > 0) {
25 this.className += " " + className;
27 this.className = className;
33 if (!DOMTokenList.prototype.remove) {
34 DOMTokenList.prototype.remove = function(className) {
35 if (className && this.className) {
36 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
45 // This mapping table should match the discriminants of
46 // `rustdoc::html::item_type::ItemType` type in Rust.
47 var itemTypes = ["mod",
73 var search_input = document.getElementsByClassName("search-input")[0];
75 // On the search screen, so you remain on the last tab you opened.
78 // 1 for "In Parameters"
79 // 2 for "In Return Types"
82 var themesWidth = null;
84 var titleBeforeSearch = document.title;
86 function getPageId() {
87 var id = document.location.href.split("#")[1];
89 return id.split("?")[0].split("&")[0];
94 function showSidebar() {
95 var elems = document.getElementsByClassName("sidebar-elems")[0];
97 addClass(elems, "show-it");
99 var sidebar = document.getElementsByClassName("sidebar")[0];
101 addClass(sidebar, "mobile");
102 var filler = document.getElementById("sidebar-filler");
104 var div = document.createElement("div");
105 div.id = "sidebar-filler";
106 sidebar.appendChild(div);
109 var themePicker = document.getElementsByClassName("theme-picker");
110 if (themePicker && themePicker.length > 0) {
111 themePicker[0].style.display = "none";
115 function hideSidebar() {
116 var elems = document.getElementsByClassName("sidebar-elems")[0];
118 removeClass(elems, "show-it");
120 var sidebar = document.getElementsByClassName("sidebar")[0];
121 removeClass(sidebar, "mobile");
122 var filler = document.getElementById("sidebar-filler");
126 document.getElementsByTagName("body")[0].style.marginTop = "";
127 var themePicker = document.getElementsByClassName("theme-picker");
128 if (themePicker && themePicker.length > 0) {
129 themePicker[0].style.display = null;
133 // used for special search precedence
134 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
135 var TY_KEYWORD = itemTypes.indexOf("keyword");
137 onEachLazy(document.getElementsByClassName("js-only"), function(e) {
138 removeClass(e, "js-only");
141 function getQueryStringParams() {
143 window.location.search.substring(1).split("&").
145 var pair = s.split("=");
146 params[decodeURIComponent(pair[0])] =
147 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
152 function browserSupportsHistoryApi() {
153 return window.history && typeof window.history.pushState === "function";
156 var main = document.getElementById("main");
158 function highlightSourceLines(ev) {
159 // If we're in mobile mode, we should add the sidebar in any case.
162 var search = document.getElementById("search");
163 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
165 from = parseInt(match[1], 10);
166 to = Math.min(50000, parseInt(match[2] || match[1], 10));
167 from = Math.min(from, to);
168 elem = document.getElementById(from);
173 var x = document.getElementById(from);
178 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
179 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
180 removeClass(i_e, "line-highlighted");
183 for (i = from; i <= to; ++i) {
184 addClass(document.getElementById(i), "line-highlighted");
186 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
187 addClass(search, "hidden");
188 removeClass(main, "hidden");
189 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
190 if (browserSupportsHistoryApi()) {
191 history.replaceState(hash, "", "?search=#" + hash);
193 elem = document.getElementById(hash);
195 elem.scrollIntoView();
200 function expandSection(id) {
201 var elem = document.getElementById(id);
202 if (elem && isHidden(elem)) {
203 var h3 = elem.parentNode.previousElementSibling;
204 if (h3 && h3.tagName !== "H3") {
205 h3 = h3.previousElementSibling; // skip div.docblock
209 var collapses = h3.getElementsByClassName("collapse-toggle");
210 if (collapses.length > 0) {
211 // The element is not visible, we need to make it appear!
212 collapseDocs(collapses[0], "show");
218 highlightSourceLines(null);
219 window.onhashchange = highlightSourceLines;
221 // Gets the human-readable string for the virtual-key code of the
222 // given KeyboardEvent, ev.
224 // This function is meant as a polyfill for KeyboardEvent#key,
225 // since it is not supported in Trident. We also test for
226 // KeyboardEvent#keyCode because the handleShortcut handler is
227 // also registered for the keydown event, because Blink doesn't fire
228 // keypress on hitting the Escape key.
230 // So I guess you could say things are getting pretty interoperable.
231 function getVirtualKey(ev) {
232 if ("key" in ev && typeof ev.key != "undefined") {
236 var c = ev.charCode || ev.keyCode;
240 return String.fromCharCode(c);
243 function displayHelp(display, ev) {
244 if (display === true) {
245 if (hasClass(help, "hidden")) {
247 removeClass(help, "hidden");
248 addClass(document.body, "blur");
250 } else if (hasClass(help, "hidden") === false) {
252 addClass(help, "hidden");
253 removeClass(document.body, "blur");
257 function handleEscape(ev, help) {
259 var search = document.getElementById("search");
260 if (hasClass(help, "hidden") === false) {
261 displayHelp(false, ev);
262 } else if (hasClass(search, "hidden") === false) {
264 addClass(search, "hidden");
265 removeClass(main, "hidden");
266 document.title = titleBeforeSearch;
271 function handleShortcut(ev) {
272 // Don't interfere with browser shortcuts
273 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
277 var help = document.getElementById("help");
278 if (document.activeElement.tagName === "INPUT") {
279 switch (getVirtualKey(ev)) {
281 handleEscape(ev, help);
285 switch (getVirtualKey(ev)) {
287 handleEscape(ev, help);
292 displayHelp(false, ev);
307 displayHelp(true, ev);
314 function findParentElement(elem, tagName) {
316 if (elem && elem.tagName === tagName) {
319 elem = elem.parentNode;
324 document.onkeypress = handleShortcut;
325 document.onkeydown = handleShortcut;
326 document.onclick = function(ev) {
327 if (hasClass(ev.target, "collapse-toggle")) {
328 collapseDocs(ev.target, "toggle");
329 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
330 collapseDocs(ev.target.parentNode, "toggle");
331 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
334 var set_fragment = function(name) {
335 if (browserSupportsHistoryApi()) {
336 history.replaceState(null, null, "#" + name);
339 location.replace("#" + name);
343 var cur_id = parseInt(ev.target.id, 10);
345 if (ev.shiftKey && prev_id) {
346 if (prev_id > cur_id) {
352 set_fragment(prev_id + "-" + cur_id);
356 set_fragment(cur_id);
358 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
359 addClass(document.getElementById("help"), "hidden");
360 removeClass(document.body, "blur");
362 // Making a collapsed element visible on onhashchange seems
364 var a = findParentElement(ev.target, "A");
366 expandSection(a.hash.replace(/^#/, ""));
371 var x = document.getElementsByClassName("version-selector");
373 x[0].onchange = function() {
375 url = document.location.href,
377 len = rootPath.match(/\.\.\//g).length + 1;
379 for (i = 0; i < len; ++i) {
380 match = url.match(/\/[^\/]*$/);
382 stripped = match[0] + stripped;
384 url = url.substring(0, url.length - match[0].length);
387 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
389 document.location.href = url;
394 * A function to compute the Levenshtein distance between two strings
395 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
396 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
397 * This code is an unmodified version of the code written by Marco de Wit
398 * and was found at http://stackoverflow.com/a/18514751/745719
400 var levenshtein_row2 = [];
401 function levenshtein(s1, s2) {
405 var s1_len = s1.length, s2_len = s2.length;
406 if (s1_len && s2_len) {
407 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
408 while (i1 < s1_len) {
411 while (i2 < s2_len) {
412 c2 = s2.charCodeAt(i2);
416 for (i1 = 0; i1 < s1_len; ++i1) {
417 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
419 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
425 return s1_len + s2_len;
428 function initSearch(rawSearchIndex) {
429 var currentResults, index, searchIndex;
430 var MAX_LEV_DISTANCE = 3;
431 var MAX_RESULTS = 200;
432 var GENERICS_DATA = 1;
436 var params = getQueryStringParams();
438 // Populate search bar with query string search term when provided,
439 // but only if the input bar is empty. This avoid the obnoxious issue
440 // where you start trying to do a search, and the index loads, and
441 // suddenly your search is gone!
442 if (search_input.value === "") {
443 search_input.value = params.search || "";
447 * Executes the query and builds an index of results
448 * @param {[Object]} query [The user query]
449 * @param {[type]} searchWords [The list of search words to query
451 * @param {[type]} filterCrates [Crate to search in if defined]
452 * @return {[type]} [A search index of results]
454 function execQuery(query, searchWords, filterCrates) {
455 function itemTypeFromName(typename) {
456 var length = itemTypes.length;
457 for (var i = 0; i < length; ++i) {
458 if (itemTypes[i] === typename) {
465 var valLower = query.query.toLowerCase(),
467 typeFilter = itemTypeFromName(query.type),
468 results = {}, results_in_args = {}, results_returned = {},
469 split = valLower.split("::");
471 var length = split.length;
472 for (var z = 0; z < length; ++z) {
473 if (split[z] === "") {
479 function transformResults(results, isType) {
481 var length = results.length;
482 for (var i = 0; i < length; ++i) {
483 if (results[i].id > -1) {
484 var obj = searchIndex[results[i].id];
485 obj.lev = results[i].lev;
486 if (isType !== true || obj.type) {
487 var res = buildHrefAndPath(obj);
488 obj.displayPath = pathSplitter(res[0]);
489 obj.fullPath = obj.displayPath + obj.name;
490 // To be sure than it some items aren't considered as duplicate.
491 obj.fullPath += "|" + obj.ty;
494 if (out.length >= MAX_RESULTS) {
503 function sortResults(results, isType) {
505 for (var entry in results) {
506 if (results.hasOwnProperty(entry)) {
507 ar.push(results[entry]);
512 var nresults = results.length;
513 for (i = 0; i < nresults; ++i) {
514 results[i].word = searchWords[results[i].id];
515 results[i].item = searchIndex[results[i].id] || {};
517 // if there are no results then return to default and fail
518 if (results.length === 0) {
522 results.sort(function(aaa, bbb) {
525 // Sort by non levenshtein results and then levenshtein results by the distance
526 // (less changes required to match means higher rankings)
529 if (a !== b) { return a - b; }
531 // sort by crate (non-current crate goes later)
532 a = (aaa.item.crate !== window.currentCrate);
533 b = (bbb.item.crate !== window.currentCrate);
534 if (a !== b) { return a - b; }
536 // sort by exact match (mismatch goes later)
537 a = (aaa.word !== valLower);
538 b = (bbb.word !== valLower);
539 if (a !== b) { return a - b; }
541 // sort by item name length (longer goes later)
544 if (a !== b) { return a - b; }
546 // sort by item name (lexicographically larger goes later)
549 if (a !== b) { return (a > b ? +1 : -1); }
551 // sort by index of keyword in item name (no literal occurrence goes later)
554 if (a !== b) { return a - b; }
555 // (later literal occurrence, if any, goes later)
558 if (a !== b) { return a - b; }
560 // special precedence for primitive and keyword pages
561 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
562 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
565 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
566 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
570 // sort by description (no description goes later)
571 a = (aaa.item.desc === "");
572 b = (bbb.item.desc === "");
573 if (a !== b) { return a - b; }
575 // sort by type (later occurrence in `itemTypes` goes later)
578 if (a !== b) { return a - b; }
580 // sort by path (lexicographically larger goes later)
583 if (a !== b) { return (a > b ? +1 : -1); }
589 var length = results.length;
590 for (i = 0; i < length; ++i) {
591 var result = results[i];
593 // this validation does not make sense when searching by types
594 if (result.dontValidate) {
597 var name = result.item.name.toLowerCase(),
598 path = result.item.path.toLowerCase(),
599 parent = result.item.parent;
601 if (isType !== true &&
602 validateResult(name, path, split, parent) === false)
607 return transformResults(results);
610 function extractGenerics(val) {
611 val = val.toLowerCase();
612 if (val.indexOf("<") !== -1) {
613 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
615 name: val.substring(0, val.indexOf("<")),
616 generics: values.split(/\s*,\s*/),
625 function checkGenerics(obj, val) {
626 // The names match, but we need to be sure that all generics kinda
628 var lev_distance = MAX_LEV_DISTANCE + 1;
629 if (val.generics.length > 0) {
630 if (obj.length > GENERICS_DATA &&
631 obj[GENERICS_DATA].length >= val.generics.length) {
632 var elems = obj[GENERICS_DATA].slice(0);
635 // We need to find the type that matches the most to remove it in order
637 var vlength = val.generics.length;
638 for (var y = 0; y < vlength; ++y) {
639 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
640 var elength = elems.length;
641 for (var x = 0; x < elength; ++x) {
642 var tmp_lev = levenshtein(elems[x], val.generics[y]);
643 if (tmp_lev < lev.lev) {
648 if (lev.pos !== -1) {
649 elems.splice(lev.pos, 1);
650 lev_distance = Math.min(lev.lev, lev_distance);
654 return MAX_LEV_DISTANCE + 1;
657 return lev_distance;//Math.ceil(total / done);
660 return MAX_LEV_DISTANCE + 1;
663 // Check for type name and type generics (if any).
664 function checkType(obj, val, literalSearch) {
665 var lev_distance = MAX_LEV_DISTANCE + 1;
667 if (obj[NAME] === val.name) {
668 if (literalSearch === true) {
669 if (val.generics && val.generics.length !== 0) {
670 if (obj.length > GENERICS_DATA &&
671 obj[GENERICS_DATA].length >= val.generics.length) {
672 var elems = obj[GENERICS_DATA].slice(0);
675 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
677 for (x = 0; allFound === false && x < elems.length; ++x) {
678 allFound = elems[x] === val.generics[y];
680 if (allFound === true) {
681 elems.splice(x - 1, 1);
684 if (allFound === true) {
693 // If the type has generics but don't match, then it won't return at this point.
694 // Otherwise, `checkGenerics` will return 0 and it'll return.
695 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
696 var tmp_lev = checkGenerics(obj, val);
697 if (tmp_lev <= MAX_LEV_DISTANCE) {
704 // Names didn't match so let's check if one of the generic types could.
705 if (literalSearch === true) {
706 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
707 var length = obj[GENERICS_DATA].length;
708 for (x = 0; x < length; ++x) {
709 if (obj[GENERICS_DATA][x] === val.name) {
716 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
717 if (lev_distance <= MAX_LEV_DISTANCE) {
718 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
719 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
720 // We can check if the type we're looking for is inside the generics!
721 var olength = obj[GENERICS_DATA].length;
722 for (x = 0; x < olength; ++x) {
723 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
727 // Now whatever happens, the returned distance is "less good" so we should mark it
728 // as such, and so we add 1 to the distance to make it "less good".
729 return lev_distance + 1;
732 function findArg(obj, val, literalSearch) {
733 var lev_distance = MAX_LEV_DISTANCE + 1;
735 if (obj && obj.type && obj.type[INPUTS_DATA] &&
736 obj.type[INPUTS_DATA].length > 0) {
737 var length = obj.type[INPUTS_DATA].length;
738 for (var i = 0; i < length; i++) {
739 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
740 if (literalSearch === true && tmp === true) {
743 lev_distance = Math.min(tmp, lev_distance);
744 if (lev_distance === 0) {
749 return literalSearch === true ? false : lev_distance;
752 function checkReturned(obj, val, literalSearch) {
753 var lev_distance = MAX_LEV_DISTANCE + 1;
755 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
756 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
757 if (literalSearch === true && tmp === true) {
760 lev_distance = Math.min(tmp, lev_distance);
761 if (lev_distance === 0) {
765 return literalSearch === true ? false : lev_distance;
768 function checkPath(contains, lastElem, ty) {
769 if (contains.length === 0) {
772 var ret_lev = MAX_LEV_DISTANCE + 1;
773 var path = ty.path.split("::");
775 if (ty.parent && ty.parent.name) {
776 path.push(ty.parent.name.toLowerCase());
779 var length = path.length;
780 var clength = contains.length;
781 if (clength > length) {
782 return MAX_LEV_DISTANCE + 1;
784 for (var i = 0; i < length; ++i) {
785 if (i + clength > length) {
790 for (var x = 0; x < clength; ++x) {
791 var lev = levenshtein(path[i + x], contains[x]);
792 if (lev > MAX_LEV_DISTANCE) {
798 if (aborted === false) {
799 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
805 function typePassesFilter(filter, type) {
807 if (filter < 0) return true;
810 if (filter === type) return true;
812 // Match related items
813 var name = itemTypes[type];
814 switch (itemTypes[filter]) {
816 return (name == "associatedconstant");
818 return (name == "method" || name == "tymethod");
820 return (name == "primitive" || name == "keyword");
827 function generateId(ty) {
828 if (ty.parent && ty.parent.name) {
829 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
831 return itemTypes[ty.ty] + ty.path + ty.name;
834 // quoted values mean literal search
835 var nSearchWords = searchWords.length;
841 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
842 val.charAt(val.length - 1) === val.charAt(0))
844 val = extractGenerics(val.substr(1, val.length - 2));
845 for (i = 0; i < nSearchWords; ++i) {
846 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
849 in_args = findArg(searchIndex[i], val, true);
850 returned = checkReturned(searchIndex[i], val, true);
852 fullId = generateId(ty);
854 if (searchWords[i] === val.name) {
855 // filter type: ... queries
856 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
857 results[fullId] === undefined)
859 results[fullId] = {id: i, index: -1};
861 } else if ((in_args === true || returned === true) &&
862 typePassesFilter(typeFilter, searchIndex[i].ty)) {
863 if (in_args === true || returned === true) {
864 if (in_args === true) {
865 results_in_args[fullId] = {
871 if (returned === true) {
872 results_returned[fullId] = {
887 query.inputs = [val];
891 } else if (val.search("->") > -1) {
892 var trimmer = function(s) { return s.trim(); };
893 var parts = val.split("->").map(trimmer);
894 var input = parts[0];
895 // sort inputs so that order does not matter
896 var inputs = input.split(",").map(trimmer).sort();
897 for (i = 0; i < inputs.length; ++i) {
898 inputs[i] = extractGenerics(inputs[i]);
900 var output = extractGenerics(parts[1]);
902 for (i = 0; i < nSearchWords; ++i) {
903 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
906 var type = searchIndex[i].type;
911 fullId = generateId(ty);
913 // allow searching for void (no output) functions as well
914 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
915 returned = checkReturned(ty, output, true);
916 if (output.name === "*" || returned === true) {
924 for (var it = 0; allFound === true && it < inputs.length; it++) {
925 allFound = checkType(type, inputs[it], true);
929 if (in_args === true) {
930 results_in_args[fullId] = {
936 if (returned === true) {
937 results_returned[fullId] = {
943 if (module === true) {
952 query.inputs = inputs.map(function(input) {
955 query.output = output.name;
957 query.inputs = [val];
960 // gather matching search results up to a certain maximum
961 val = val.replace(/\_/g, "");
963 var valGenerics = extractGenerics(val);
965 var paths = valLower.split("::");
967 for (j = 0; j < paths.length; ++j) {
968 if (paths[j] === "") {
973 val = paths[paths.length - 1];
974 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
976 for (j = 0; j < nSearchWords; ++j) {
980 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
985 if (paths.length > 1) {
986 lev = checkPath(contains, paths[paths.length - 1], ty);
987 if (lev > MAX_LEV_DISTANCE) {
989 } else if (lev > 0) {
994 returned = MAX_LEV_DISTANCE + 1;
995 in_args = MAX_LEV_DISTANCE + 1;
997 // we want lev results to go lower than others
998 lev = MAX_LEV_DISTANCE + 1;
999 fullId = generateId(ty);
1001 if (searchWords[j].indexOf(split[i]) > -1 ||
1002 searchWords[j].indexOf(val) > -1 ||
1003 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1005 // filter type: ... queries
1006 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1007 index = searchWords[j].replace(/_/g, "").indexOf(val);
1010 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1011 if (typePassesFilter(typeFilter, ty.ty) === false) {
1012 lev = MAX_LEV_DISTANCE + 1;
1017 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1018 if (typePassesFilter(typeFilter, ty.ty) === false) {
1019 in_args = MAX_LEV_DISTANCE + 1;
1022 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1023 if (typePassesFilter(typeFilter, ty.ty) === false) {
1024 returned = MAX_LEV_DISTANCE + 1;
1029 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1030 if (val.length < 6) {
1036 if (in_args <= MAX_LEV_DISTANCE) {
1037 if (results_in_args[fullId] === undefined) {
1038 results_in_args[fullId] = {
1044 results_in_args[fullId].lev =
1045 Math.min(results_in_args[fullId].lev, in_args);
1047 if (returned <= MAX_LEV_DISTANCE) {
1048 if (results_returned[fullId] === undefined) {
1049 results_returned[fullId] = {
1055 results_returned[fullId].lev =
1056 Math.min(results_returned[fullId].lev, returned);
1058 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1059 if (index !== -1 && paths.length < 2) {
1062 if (results[fullId] === undefined) {
1069 results[fullId].lev = Math.min(results[fullId].lev, lev);
1075 "in_args": sortResults(results_in_args, true),
1076 "returned": sortResults(results_returned, true),
1077 "others": sortResults(results),
1079 if (ALIASES && ALIASES[window.currentCrate] &&
1080 ALIASES[window.currentCrate][query.raw]) {
1081 var aliases = ALIASES[window.currentCrate][query.raw];
1082 for (i = 0; i < aliases.length; ++i) {
1083 aliases[i].is_alias = true;
1084 aliases[i].alias = query.raw;
1085 aliases[i].path = aliases[i].p;
1086 var res = buildHrefAndPath(aliases[i]);
1087 aliases[i].displayPath = pathSplitter(res[0]);
1088 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1089 aliases[i].href = res[1];
1090 ret.others.unshift(aliases[i]);
1091 if (ret.others.length > MAX_RESULTS) {
1100 * Validate performs the following boolean logic. For example:
1101 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1102 * exists in (name || path || parent) OR => ("file" && "open") exists in
1105 * This could be written functionally, but I wanted to minimise
1106 * functions on stack.
1108 * @param {[string]} name [The name of the result]
1109 * @param {[string]} path [The path of the result]
1110 * @param {[string]} keys [The keys to be used (["file", "open"])]
1111 * @param {[object]} parent [The parent of the result]
1112 * @return {[boolean]} [Whether the result is valid or not]
1114 function validateResult(name, path, keys, parent) {
1115 for (var i = 0; i < keys.length; ++i) {
1116 // each check is for validation so we negate the conditions and invalidate
1118 // check for an exact name match
1119 name.indexOf(keys[i]) > -1 ||
1120 // then an exact path match
1121 path.indexOf(keys[i]) > -1 ||
1122 // next if there is a parent, check for exact parent match
1123 (parent !== undefined &&
1124 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1125 // lastly check to see if the name was a levenshtein match
1126 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1133 function getQuery(raw) {
1134 var matches, type, query;
1137 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1139 type = matches[1].replace(/^const$/, "constant");
1140 query = query.substring(matches[0].length);
1151 function initSearchNav() {
1154 var click_func = function(e) {
1156 // to retrieve the real "owner" of the event.
1157 while (el.tagName !== "TR") {
1160 var dst = e.target.getElementsByTagName("a");
1161 if (dst.length < 1) {
1165 if (window.location.pathname === dst.pathname) {
1166 addClass(document.getElementById("search"), "hidden");
1167 removeClass(main, "hidden");
1168 document.location.href = dst.href;
1171 var mouseover_func = function(e) {
1173 // to retrieve the real "owner" of the event.
1174 while (el.tagName !== "TR") {
1177 clearTimeout(hoverTimeout);
1178 hoverTimeout = setTimeout(function() {
1179 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1180 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1181 removeClass(i_e, "highlighted");
1184 addClass(el, "highlighted");
1187 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1188 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1189 i_e.onclick = click_func;
1190 i_e.onmouseover = mouseover_func;
1194 search_input.onkeydown = function(e) {
1195 // "actives" references the currently highlighted item in each search tab.
1196 // Each array in "actives" represents a tab.
1197 var actives = [[], [], []];
1198 // "current" is used to know which tab we're looking into.
1200 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1201 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1202 actives[current].push(e);
1207 if (e.which === 38) { // up
1208 if (!actives[currentTab].length ||
1209 !actives[currentTab][0].previousElementSibling) {
1213 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1214 removeClass(actives[currentTab][0], "highlighted");
1215 } else if (e.which === 40) { // down
1216 if (!actives[currentTab].length) {
1217 var results = document.getElementsByClassName("search-results");
1218 if (results.length > 0) {
1219 var res = results[currentTab].getElementsByClassName("result");
1220 if (res.length > 0) {
1221 addClass(res[0], "highlighted");
1224 } else if (actives[currentTab][0].nextElementSibling) {
1225 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1226 removeClass(actives[currentTab][0], "highlighted");
1228 } else if (e.which === 13) { // return
1229 if (actives[currentTab].length) {
1230 document.location.href =
1231 actives[currentTab][0].getElementsByTagName("a")[0].href;
1233 } else if (e.which === 9) { // tab
1235 printTab(currentTab > 0 ? currentTab - 1 : 2);
1237 printTab(currentTab > 1 ? 0 : currentTab + 1);
1240 } else if (e.which === 16) { // shift
1241 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1242 } else if (e.which === 27) { // escape
1243 removeClass(actives[currentTab][0], "highlighted");
1244 search_input.value = "";
1246 } else if (actives[currentTab].length > 0) {
1247 removeClass(actives[currentTab][0], "highlighted");
1252 function buildHrefAndPath(item) {
1255 var type = itemTypes[item.ty];
1256 var name = item.name;
1258 if (type === "mod") {
1259 displayPath = item.path + "::";
1260 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1261 name + "/index.html";
1262 } else if (type === "primitive" || type === "keyword") {
1264 href = rootPath + item.path.replace(/::/g, "/") +
1265 "/" + type + "." + name + ".html";
1266 } else if (type === "externcrate") {
1268 href = rootPath + name + "/index.html";
1269 } else if (item.parent !== undefined) {
1270 var myparent = item.parent;
1271 var anchor = "#" + type + "." + name;
1272 var parentType = itemTypes[myparent.ty];
1273 if (parentType === "primitive") {
1274 displayPath = myparent.name + "::";
1276 displayPath = item.path + "::" + myparent.name + "::";
1278 href = rootPath + item.path.replace(/::/g, "/") +
1280 "." + myparent.name +
1283 displayPath = item.path + "::";
1284 href = rootPath + item.path.replace(/::/g, "/") +
1285 "/" + type + "." + name + ".html";
1287 return [displayPath, href];
1290 function escape(content) {
1291 var h1 = document.createElement("h1");
1292 h1.textContent = content;
1293 return h1.innerHTML;
1296 function pathSplitter(path) {
1297 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1298 if (tmp.endsWith("<span>")) {
1299 return tmp.slice(0, tmp.length - 6);
1304 function addTab(array, query, display) {
1305 var extraStyle = "";
1306 if (display === false) {
1307 extraStyle = " style=\"display: none;\"";
1311 var duplicates = {};
1313 if (array.length > 0) {
1314 output = "<table class=\"search-results\"" + extraStyle + ">";
1316 array.forEach(function(item) {
1320 type = itemTypes[item.ty];
1322 if (item.is_alias !== true) {
1323 if (duplicates[item.fullPath]) {
1326 duplicates[item.fullPath] = true;
1330 output += "<tr class=\"" + type + " result\"><td>" +
1331 "<a href=\"" + item.href + "\">" +
1332 (item.is_alias === true ?
1333 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1334 "class=\"grey\"><i> - see </i></span>") : "") +
1335 item.displayPath + "<span class=\"" + type + "\">" +
1336 name + "</span></a></td><td>" +
1337 "<a href=\"" + item.href + "\">" +
1338 "<span class=\"desc\">" + escape(item.desc) +
1339 " </span></a></td></tr>";
1341 output += "</table>";
1343 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1344 "Try on <a href=\"https://duckduckgo.com/?q=" +
1345 encodeURIComponent("rust " + query.query) +
1346 "\">DuckDuckGo</a>?<br/><br/>" +
1347 "Or try looking in one of these:<ul><li>The <a " +
1348 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1349 " for technical details about the language.</li><li><a " +
1350 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1351 "Example</a> for expository code examples.</a></li><li>The <a " +
1352 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1353 "introductions to language features and the language itself.</li><li><a " +
1354 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1355 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1357 return [output, length];
1360 function makeTabHeader(tabNb, text, nbElems) {
1361 if (currentTab === tabNb) {
1362 return "<div class=\"selected\">" + text +
1363 " <div class=\"count\">(" + nbElems + ")</div></div>";
1365 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1368 function showResults(results) {
1369 if (results.others.length === 1 &&
1370 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1371 var elem = document.createElement("a");
1372 elem.href = results.others[0].href;
1373 elem.style.display = "none";
1374 // For firefox, we need the element to be in the DOM so it can be clicked.
1375 document.body.appendChild(elem);
1378 var query = getQuery(search_input.value);
1380 currentResults = query.id;
1382 var ret_others = addTab(results.others, query);
1383 var ret_in_args = addTab(results.in_args, query, false);
1384 var ret_returned = addTab(results.returned, query, false);
1386 var output = "<h1>Results for " + escape(query.query) +
1387 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1388 "<div id=\"titles\">" +
1389 makeTabHeader(0, "In Names", ret_others[1]) +
1390 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1391 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1392 "</div><div id=\"results\">" +
1393 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1395 addClass(main, "hidden");
1396 var search = document.getElementById("search");
1397 removeClass(search, "hidden");
1398 search.innerHTML = output;
1399 var tds = search.getElementsByTagName("td");
1401 if (tds.length > 0) {
1402 td_width = tds[0].offsetWidth;
1404 var width = search.offsetWidth - 40 - td_width;
1405 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1406 e.style.width = width + "px";
1409 var elems = document.getElementById("titles").childNodes;
1410 elems[0].onclick = function() { printTab(0); };
1411 elems[1].onclick = function() { printTab(1); };
1412 elems[2].onclick = function() { printTab(2); };
1413 printTab(currentTab);
1416 function execSearch(query, searchWords, filterCrates) {
1417 function getSmallest(arrays, positions, notDuplicates) {
1420 for (var it = 0; it < positions.length; ++it) {
1421 if (arrays[it].length > positions[it] &&
1422 (start === null || start > arrays[it][positions[it]].lev) &&
1423 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1424 start = arrays[it][positions[it]].lev;
1430 function mergeArrays(arrays) {
1433 var notDuplicates = {};
1435 for (var x = 0; x < arrays.length; ++x) {
1438 while (ret.length < MAX_RESULTS) {
1439 var smallest = getSmallest(arrays, positions, notDuplicates);
1441 if (smallest === null) {
1444 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1445 if (arrays[x].length > positions[x] &&
1446 arrays[x][positions[x]].lev === smallest &&
1447 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1448 ret.push(arrays[x][positions[x]]);
1449 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1457 var queries = query.raw.split(",");
1464 for (var i = 0; i < queries.length; ++i) {
1465 query = queries[i].trim();
1466 if (query.length !== 0) {
1467 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1469 results.in_args.push(tmp.in_args);
1470 results.returned.push(tmp.returned);
1471 results.others.push(tmp.others);
1474 if (queries.length > 1) {
1476 "in_args": mergeArrays(results.in_args),
1477 "returned": mergeArrays(results.returned),
1478 "others": mergeArrays(results.others),
1482 "in_args": results.in_args[0],
1483 "returned": results.returned[0],
1484 "others": results.others[0],
1489 function getFilterCrates() {
1490 var elem = document.getElementById("crate-search");
1492 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1498 function search(e, forced) {
1499 var params = getQueryStringParams();
1500 var query = getQuery(search_input.value.trim());
1506 if (query.query.length === 0) {
1509 if (forced !== true && query.id === currentResults) {
1510 if (query.query.length > 0) {
1511 putBackSearch(search_input);
1516 // Update document title to maintain a meaningful browser history
1517 document.title = "Results for " + query.query + " - Rust";
1519 // Because searching is incremental by character, only the most
1520 // recent search query is added to the browser history.
1521 if (browserSupportsHistoryApi()) {
1522 if (!history.state && !params.search) {
1523 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1525 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1529 var filterCrates = getFilterCrates();
1530 showResults(execSearch(query, index, filterCrates), filterCrates);
1533 function buildIndex(rawSearchIndex) {
1535 var searchWords = [];
1538 for (var crate in rawSearchIndex) {
1539 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1541 searchWords.push(crate);
1544 ty: 1, // == ExternCrate
1547 desc: rawSearchIndex[crate].doc,
1551 // an array of [(Number) item type,
1553 // (String) full path or empty string for previous path,
1554 // (String) description,
1555 // (Number | null) the parent path index to `paths`]
1556 // (Object | null) the type of the function (if any)
1557 var items = rawSearchIndex[crate].i;
1558 // an array of [(Number) item type,
1560 var paths = rawSearchIndex[crate].p;
1562 // convert `paths` into an object form
1563 var len = paths.length;
1564 for (i = 0; i < len; ++i) {
1565 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1568 // convert `items` into an object form, and construct word indices.
1570 // before any analysis is performed lets gather the search terms to
1571 // search against apart from the rest of the data. This is a quick
1572 // operation that is cached for the life of the page state so that
1573 // all other search operations have access to this cached data for
1574 // faster analysis operations
1577 for (i = 0; i < len; ++i) {
1578 var rawRow = items[i];
1579 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1580 path: rawRow[2] || lastPath, desc: rawRow[3],
1581 parent: paths[rawRow[4]], type: rawRow[5]};
1582 searchIndex.push(row);
1583 if (typeof row.name === "string") {
1584 var word = row.name.toLowerCase();
1585 searchWords.push(word);
1587 searchWords.push("");
1589 lastPath = row.path;
1595 function startSearch() {
1597 var callback = function() {
1598 clearTimeout(searchTimeout);
1599 if (search_input.value.length === 0) {
1600 if (browserSupportsHistoryApi()) {
1601 history.replaceState("", "std - Rust", "?search=");
1603 if (hasClass(main, "content")) {
1604 removeClass(main, "hidden");
1606 var search_c = document.getElementById("search");
1607 if (hasClass(search_c, "content")) {
1608 addClass(search_c, "hidden");
1611 searchTimeout = setTimeout(search, 500);
1614 search_input.onkeyup = callback;
1615 search_input.oninput = callback;
1616 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1618 clearTimeout(searchTimeout);
1621 search_input.onchange = function(e) {
1622 // Do NOT e.preventDefault() here. It will prevent pasting.
1623 clearTimeout(searchTimeout);
1624 // zero-timeout necessary here because at the time of event handler execution the
1625 // pasted content is not in the input field yet. Shouldn’t make any difference for
1627 setTimeout(search, 0);
1629 search_input.onpaste = search_input.onchange;
1631 var selectCrate = document.getElementById('crate-search');
1633 selectCrate.onchange = function() {
1634 search(undefined, true);
1638 // Push and pop states are used to add search results to the browser
1640 if (browserSupportsHistoryApi()) {
1641 // Store the previous <title> so we can revert back to it later.
1642 var previousTitle = document.title;
1644 window.onpopstate = function(e) {
1645 var params = getQueryStringParams();
1646 // When browsing back from search results the main page
1647 // visibility must be reset.
1648 if (!params.search) {
1649 if (hasClass(main, "content")) {
1650 removeClass(main, "hidden");
1652 var search_c = document.getElementById("search");
1653 if (hasClass(search_c, "content")) {
1654 addClass(search_c, "hidden");
1657 // Revert to the previous title manually since the History
1658 // API ignores the title parameter.
1659 document.title = previousTitle;
1660 // When browsing forward to search results the previous
1661 // search will be repeated, so the currentResults are
1662 // cleared to ensure the search is successful.
1663 currentResults = null;
1664 // Synchronize search bar with query string state and
1665 // perform the search. This will empty the bar if there's
1666 // nothing there, which lets you really go back to a
1667 // previous state with nothing in the bar.
1668 if (params.search) {
1669 search_input.value = params.search;
1671 search_input.value = "";
1673 // Some browsers fire "onpopstate" for every page load
1674 // (Chrome), while others fire the event only when actually
1675 // popping a state (Firefox), which is why search() is
1676 // called both here and at the end of the startSearch()
1684 index = buildIndex(rawSearchIndex);
1687 // Draw a convenient sidebar of known crates if we have a listing
1688 if (rootPath === "../" || rootPath === "./") {
1689 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1691 var div = document.createElement("div");
1692 div.className = "block crate";
1693 div.innerHTML = "<h3>Crates</h3>";
1694 var ul = document.createElement("ul");
1695 div.appendChild(ul);
1698 for (var crate in rawSearchIndex) {
1699 if (!rawSearchIndex.hasOwnProperty(crate)) {
1705 for (var i = 0; i < crates.length; ++i) {
1706 var klass = "crate";
1707 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1708 klass += " current";
1710 var link = document.createElement("a");
1711 link.href = rootPath + crates[i] + "/index.html";
1712 link.title = rawSearchIndex[crates[i]].doc;
1713 link.className = klass;
1714 link.textContent = crates[i];
1716 var li = document.createElement("li");
1717 li.appendChild(link);
1720 sidebar.appendChild(div);
1725 window.initSearch = initSearch;
1727 // delayed sidebar rendering.
1728 function initSidebarItems(items) {
1729 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1730 var current = window.sidebarCurrent;
1732 function block(shortty, longty) {
1733 var filtered = items[shortty];
1738 var div = document.createElement("div");
1739 div.className = "block " + shortty;
1740 var h3 = document.createElement("h3");
1741 h3.textContent = longty;
1742 div.appendChild(h3);
1743 var ul = document.createElement("ul");
1745 var length = filtered.length;
1746 for (var i = 0; i < length; ++i) {
1747 var item = filtered[i];
1749 var desc = item[1]; // can be null
1751 var klass = shortty;
1752 if (name === current.name && shortty === current.ty) {
1753 klass += " current";
1756 if (shortty === "mod") {
1757 path = name + "/index.html";
1759 path = shortty + "." + name + ".html";
1761 var link = document.createElement("a");
1762 link.href = current.relpath + path;
1764 link.className = klass;
1765 link.textContent = name;
1766 var li = document.createElement("li");
1767 li.appendChild(link);
1770 div.appendChild(ul);
1772 sidebar.appendChild(div);
1776 block("primitive", "Primitive Types");
1777 block("mod", "Modules");
1778 block("macro", "Macros");
1779 block("struct", "Structs");
1780 block("enum", "Enums");
1781 block("union", "Unions");
1782 block("constant", "Constants");
1783 block("static", "Statics");
1784 block("trait", "Traits");
1785 block("fn", "Functions");
1786 block("type", "Type Definitions");
1787 block("foreigntype", "Foreign Types");
1788 block("keyword", "Keywords");
1791 window.initSidebarItems = initSidebarItems;
1793 window.register_implementors = function(imp) {
1794 var implementors = document.getElementById("implementors-list");
1795 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1797 var libs = Object.getOwnPropertyNames(imp);
1798 var llength = libs.length;
1799 for (var i = 0; i < llength; ++i) {
1800 if (libs[i] === currentCrate) { continue; }
1801 var structs = imp[libs[i]];
1803 var slength = structs.length;
1805 for (var j = 0; j < slength; ++j) {
1806 var struct = structs[j];
1808 var list = struct.synthetic ? synthetic_implementors : implementors;
1810 if (struct.synthetic) {
1811 var stlength = struct.types.length;
1812 for (var k = 0; k < stlength; k++) {
1813 if (window.inlined_types.has(struct.types[k])) {
1814 continue struct_loop;
1816 window.inlined_types.add(struct.types[k]);
1820 var code = document.createElement("code");
1821 code.innerHTML = struct.text;
1823 var x = code.getElementsByTagName("a");
1824 var xlength = x.length;
1825 for (var it = 0; it < xlength; it++) {
1826 var href = x[it].getAttribute("href");
1827 if (href && href.indexOf("http") !== 0) {
1828 x[it].setAttribute("href", rootPath + href);
1831 var display = document.createElement("h3");
1832 addClass(display, "impl");
1833 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1834 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1835 "</tbody></table></span>";
1836 list.appendChild(display);
1840 if (window.pending_implementors) {
1841 window.register_implementors(window.pending_implementors);
1844 function labelForToggleButton(sectionIsCollapsed) {
1845 if (sectionIsCollapsed) {
1846 // button will expand the section
1849 // button will collapse the section
1850 // note that this text is also set in the HTML template in render.rs
1851 return "\u2212"; // "\u2212" is "−" minus sign
1854 function onEveryMatchingChild(elem, className, func) {
1855 if (elem && className && func) {
1856 var length = elem.childNodes.length;
1857 var nodes = elem.childNodes;
1858 for (var i = 0; i < length; ++i) {
1859 if (hasClass(nodes[i], className)) {
1862 onEveryMatchingChild(nodes[i], className, func);
1868 function toggleAllDocs(pageId, fromAutoCollapse) {
1869 var innerToggle = document.getElementById("toggle-all-docs");
1873 if (hasClass(innerToggle, "will-expand")) {
1874 updateLocalStorage("rustdoc-collapse", "false");
1875 removeClass(innerToggle, "will-expand");
1876 onEveryMatchingChild(innerToggle, "inner", function(e) {
1877 e.innerHTML = labelForToggleButton(false);
1879 innerToggle.title = "collapse all docs";
1880 if (fromAutoCollapse !== true) {
1881 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1882 collapseDocs(e, "show");
1886 updateLocalStorage("rustdoc-collapse", "true");
1887 addClass(innerToggle, "will-expand");
1888 onEveryMatchingChild(innerToggle, "inner", function(e) {
1889 e.innerHTML = labelForToggleButton(true);
1891 innerToggle.title = "expand all docs";
1892 if (fromAutoCollapse !== true) {
1893 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1894 collapseDocs(e, "hide", pageId);
1900 function collapseDocs(toggle, mode, pageId) {
1901 if (!toggle || !toggle.parentNode) {
1905 function adjustToggle(arg) {
1906 return function(e) {
1907 if (hasClass(e, "toggle-label")) {
1909 e.style.display = "inline-block";
1911 e.style.display = "none";
1914 if (hasClass(e, "inner")) {
1915 e.innerHTML = labelForToggleButton(arg);
1920 function implHider(addOrRemove) {
1921 return function(n) {
1922 var is_method = hasClass(n, "method");
1923 if (is_method || hasClass(n, "type")) {
1924 if (is_method === true) {
1926 addClass(n, "hidden-by-impl-hider");
1928 removeClass(n, "hidden-by-impl-hider");
1931 var ns = n.nextElementSibling;
1934 hasClass(ns, "docblock") ||
1935 hasClass(ns, "stability"))) {
1937 addClass(ns, "hidden-by-impl-hider");
1939 removeClass(ns, "hidden-by-impl-hider");
1941 ns = ns.nextElementSibling;
1952 if (hasClass(toggle.parentNode, "impl") === false) {
1953 relatedDoc = toggle.parentNode.nextElementSibling;
1954 if (hasClass(relatedDoc, "stability")) {
1955 relatedDoc = relatedDoc.nextElementSibling;
1957 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1958 if (mode === "toggle") {
1959 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1965 if (action === "hide") {
1966 addClass(relatedDoc, "hidden-by-usual-hider");
1967 onEachLazy(toggle.childNodes, adjustToggle(true));
1968 addClass(toggle.parentNode, "collapsed");
1969 } else if (action === "show") {
1970 removeClass(relatedDoc, "hidden-by-usual-hider");
1971 removeClass(toggle.parentNode, "collapsed");
1972 onEachLazy(toggle.childNodes, adjustToggle(false));
1976 // we are collapsing the impl block
1978 var parentElem = toggle.parentNode;
1979 relatedDoc = parentElem;
1980 var docblock = relatedDoc.nextElementSibling;
1982 while (hasClass(relatedDoc, "impl-items") === false) {
1983 relatedDoc = relatedDoc.nextElementSibling;
1986 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
1987 (pageId && document.getElementById(pageId))) {
1991 // Hide all functions, but not associated types/consts
1993 if (mode === "toggle") {
1994 if (hasClass(relatedDoc, "fns-now-collapsed") ||
1995 hasClass(docblock, "hidden-by-impl-hider")) {
2002 if (action === "show") {
2003 removeClass(relatedDoc, "fns-now-collapsed");
2004 removeClass(docblock, "hidden-by-usual-hider");
2005 onEachLazy(toggle.childNodes, adjustToggle(false));
2006 onEachLazy(relatedDoc.childNodes, implHider(false));
2007 } else if (action === "hide") {
2008 addClass(relatedDoc, "fns-now-collapsed");
2009 addClass(docblock, "hidden-by-usual-hider");
2010 onEachLazy(toggle.childNodes, adjustToggle(true));
2011 onEachLazy(relatedDoc.childNodes, implHider(true));
2016 function collapser(e, collapse) {
2017 // inherent impl ids are like "impl" or impl-<number>'.
2018 // they will never be hidden by default.
2019 var n = e.parentElement;
2020 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2021 // Automatically minimize all non-inherent impls
2022 if (collapse || hasClass(n, "impl")) {
2023 collapseDocs(e, "hide", pageId);
2028 function autoCollapse(pageId, collapse) {
2030 toggleAllDocs(pageId, true);
2031 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2032 var impl_list = document.getElementById("implementations-list");
2034 if (impl_list !== null) {
2035 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2036 collapser(e, collapse);
2042 var toggles = document.getElementById("toggle-all-docs");
2044 toggles.onclick = toggleAllDocs;
2047 function insertAfter(newNode, referenceNode) {
2048 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2051 function createSimpleToggle(sectionIsCollapsed) {
2052 var toggle = document.createElement("a");
2053 toggle.href = "javascript:void(0)";
2054 toggle.className = "collapse-toggle";
2055 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2060 var toggle = createSimpleToggle(false);
2062 var func = function(e) {
2063 var next = e.nextElementSibling;
2067 if (hasClass(next, "docblock") ||
2068 (hasClass(next, "stability") &&
2069 hasClass(next.nextElementSibling, "docblock"))) {
2070 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2074 var funcImpl = function(e) {
2075 var next = e.nextElementSibling;
2076 if (next && hasClass(next, "docblock")) {
2077 next = next.nextElementSibling;
2082 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2083 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2087 onEachLazy(document.getElementsByClassName("method"), func);
2088 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2089 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2090 var impl_call = function() {};
2091 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2092 impl_call = function(e, newToggle, pageId) {
2093 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2094 // Automatically minimize all non-inherent impls
2095 if (hasClass(e, "impl")) {
2096 collapseDocs(newToggle, "hide", pageId);
2101 var pageId = getPageId();
2102 var newToggle = document.createElement("a");
2103 newToggle.href = "javascript:void(0)";
2104 newToggle.className = "collapse-toggle hidden-default collapsed";
2105 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2106 "</span>] Show hidden undocumented items";
2107 function toggleClicked() {
2108 if (hasClass(this, "collapsed")) {
2109 removeClass(this, "collapsed");
2110 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2111 if (hasClass(x, "content") === false) {
2112 removeClass(x, "hidden");
2116 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2117 "</span>] Hide undocumented items";
2119 addClass(this, "collapsed");
2120 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2121 if (hasClass(x, "content") === false) {
2122 addClass(x, "hidden");
2123 removeClass(x, "x");
2126 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2127 "</span>] Show hidden undocumented items";
2130 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2131 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2132 var hiddenElems = e.getElementsByClassName("hidden");
2133 var needToggle = false;
2135 var hlength = hiddenElems.length;
2136 for (var i = 0; i < hlength; ++i) {
2137 if (hasClass(hiddenElems[i], "content") === false &&
2138 hasClass(hiddenElems[i], "docblock") === false) {
2143 if (needToggle === true) {
2144 var inner_toggle = newToggle.cloneNode(true);
2145 inner_toggle.onclick = toggleClicked;
2146 e.insertBefore(inner_toggle, e.firstChild);
2147 impl_call(e, inner_toggle, pageId);
2151 function createToggle(otherMessage, fontSize, extraClass, show) {
2152 var span = document.createElement("span");
2153 span.className = "toggle-label";
2155 span.style.display = "none";
2157 if (!otherMessage) {
2158 span.innerHTML = " Expand description";
2160 span.innerHTML = otherMessage;
2164 span.style.fontSize = fontSize;
2167 var mainToggle = toggle.cloneNode(true);
2168 mainToggle.appendChild(span);
2170 var wrapper = document.createElement("div");
2171 wrapper.className = "toggle-wrapper";
2173 addClass(wrapper, "collapsed");
2174 var inner = mainToggle.getElementsByClassName("inner");
2175 if (inner && inner.length > 0) {
2176 inner[0].innerHTML = "+";
2180 addClass(wrapper, extraClass);
2182 wrapper.appendChild(mainToggle);
2186 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2187 function buildToggleWrapper(e) {
2188 if (hasClass(e, "autohide")) {
2189 var wrap = e.previousElementSibling;
2190 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2191 var inner_toggle = wrap.childNodes[0];
2192 var extra = e.childNodes[0].tagName === "H3";
2194 e.style.display = "none";
2195 addClass(wrap, "collapsed");
2196 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2197 e.innerHTML = labelForToggleButton(true);
2199 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2200 e.style.display = "inline-block";
2201 if (extra === true) {
2202 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2207 if (e.parentNode.id === "main") {
2208 var otherMessage = "";
2212 if (hasClass(e, "type-decl")) {
2214 otherMessage = " Show declaration";
2215 if (showItemDeclarations === false) {
2216 extraClass = "collapsed";
2218 } else if (hasClass(e, "sub-variant")) {
2219 otherMessage = " Show fields";
2220 } else if (hasClass(e, "non-exhaustive")) {
2221 otherMessage = " This ";
2222 if (hasClass(e, "non-exhaustive-struct")) {
2223 otherMessage += "struct";
2224 } else if (hasClass(e, "non-exhaustive-enum")) {
2225 otherMessage += "enum";
2226 } else if (hasClass(e, "non-exhaustive-type")) {
2227 otherMessage += "type";
2229 otherMessage += " is marked as non-exhaustive";
2230 } else if (hasClass(e.childNodes[0], "impl-items")) {
2231 extraClass = "marg-left";
2234 e.parentNode.insertBefore(
2235 createToggle(otherMessage,
2238 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2240 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2241 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2246 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2247 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2249 // In the search display, allows to switch between tabs.
2250 function printTab(nb) {
2251 if (nb === 0 || nb === 1 || nb === 2) {
2255 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2256 if (nb_copy === 0) {
2257 addClass(elem, "selected");
2259 removeClass(elem, "selected");
2263 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2265 elem.style.display = "";
2267 elem.style.display = "none";
2273 function createToggleWrapper(tog) {
2274 var span = document.createElement("span");
2275 span.className = "toggle-label";
2276 span.style.display = "none";
2277 span.innerHTML = " Expand attributes";
2278 tog.appendChild(span);
2280 var wrapper = document.createElement("div");
2281 wrapper.className = "toggle-wrapper toggle-attributes";
2282 wrapper.appendChild(tog);
2286 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2287 var itemAttributesFunc = function() {};
2288 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2289 itemAttributesFunc = function(x) {
2290 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2293 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2294 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2295 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2296 itemAttributesFunc(i_e);
2299 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2300 var lineNumbersFunc = function() {};
2301 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2302 lineNumbersFunc = function(x) {
2303 var count = x.textContent.split("\n").length;
2305 for (var i = 0; i < count; ++i) {
2308 var node = document.createElement("pre");
2309 addClass(node, "line-number");
2310 node.innerHTML = elems.join("\n");
2311 x.parentNode.insertBefore(node, x);
2314 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2315 if (hasClass(e, "compile_fail")) {
2316 e.addEventListener("mouseover", function(event) {
2317 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2319 e.addEventListener("mouseout", function(event) {
2320 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2322 } else if (hasClass(e, "ignore")) {
2323 e.addEventListener("mouseover", function(event) {
2324 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2326 e.addEventListener("mouseout", function(event) {
2327 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2333 function showModal(content) {
2334 var modal = document.createElement("div");
2335 modal.id = "important";
2336 addClass(modal, "modal");
2337 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2338 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2340 document.getElementsByTagName("body")[0].appendChild(modal);
2341 document.getElementById("modal-close").onclick = hideModal;
2342 modal.onclick = hideModal;
2345 function hideModal() {
2346 var modal = document.getElementById("important");
2348 modal.parentNode.removeChild(modal);
2352 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2353 e.onclick = function() {
2354 showModal(e.lastElementChild.innerHTML);
2358 function putBackSearch(search_input) {
2359 if (search_input.value !== "") {
2360 addClass(main, "hidden");
2361 removeClass(document.getElementById("search"), "hidden");
2362 if (browserSupportsHistoryApi()) {
2363 history.replaceState(search_input.value,
2365 "?search=" + encodeURIComponent(search_input.value));
2371 search_input.onfocus = function() {
2372 putBackSearch(this);
2376 var params = getQueryStringParams();
2377 if (params && params.search) {
2378 addClass(main, "hidden");
2379 var search = document.getElementById("search");
2380 removeClass(search, "hidden");
2381 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2384 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2386 sidebar_menu.onclick = function() {
2387 var sidebar = document.getElementsByClassName("sidebar")[0];
2388 if (hasClass(sidebar, "mobile") === true) {
2396 window.onresize = function() {
2400 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2402 if (window.location.hash && window.location.hash.length > 0) {
2403 expandSection(window.location.hash.replace(/^#/, ""));
2407 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2410 onEachLazy(main.childNodes, function(e) {
2411 // Unhide the actual content once loading is complete. Headers get
2412 // flex treatment for their horizontal layout, divs get block treatment
2413 // for vertical layout (column-oriented flex layout for divs caused
2414 // errors in mobile browsers).
2415 if (e.tagName === "H2" || e.tagName === "H3") {
2416 let nextTagName = e.nextElementSibling.tagName;
2417 if (nextTagName == "H2" || nextTagName == "H3") {
2418 e.nextElementSibling.style.display = "flex";
2420 e.nextElementSibling.style.display = "block";
2426 function addSearchOptions(crates) {
2427 var elem = document.getElementById('crate-search');
2432 var crates_text = [];
2433 if (Object.keys(crates).length > 1) {
2434 for (var crate in crates) {
2435 if (crates.hasOwnProperty(crate)) {
2436 crates_text.push(crate);
2440 crates_text.sort(function(a, b) {
2441 var lower_a = a.toLowerCase();
2442 var lower_b = b.toLowerCase();
2444 if (lower_a < lower_b) {
2446 } else if (lower_a > lower_b) {
2451 for (var i = 0; i < crates_text.length; ++i) {
2452 var option = document.createElement("option");
2453 option.value = crates_text[i];
2454 option.innerText = crates_text[i];
2455 elem.appendChild(option);
2459 window.addSearchOptions = addSearchOptions;
2462 // Sets the focus on the search bar at the top of the page
2463 function focusSearchBar() {
2464 document.getElementsByClassName("search-input")[0].focus();
2467 // Removes the focus from the search bar
2468 function defocusSearchBar() {
2469 document.getElementsByClassName("search-input")[0].blur();