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 document.location.protocol != "file:" &&
154 window.history && typeof window.history.pushState === "function";
157 var main = document.getElementById("main");
159 function highlightSourceLines(ev) {
160 // If we're in mobile mode, we should add the sidebar in any case.
163 var search = document.getElementById("search");
164 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
166 from = parseInt(match[1], 10);
167 to = Math.min(50000, parseInt(match[2] || match[1], 10));
168 from = Math.min(from, to);
169 elem = document.getElementById(from);
174 var x = document.getElementById(from);
179 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
180 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
181 removeClass(i_e, "line-highlighted");
184 for (i = from; i <= to; ++i) {
185 addClass(document.getElementById(i), "line-highlighted");
187 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
188 addClass(search, "hidden");
189 removeClass(main, "hidden");
190 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
191 if (browserSupportsHistoryApi()) {
192 history.replaceState(hash, "", "?search=#" + hash);
194 elem = document.getElementById(hash);
196 elem.scrollIntoView();
201 function expandSection(id) {
202 var elem = document.getElementById(id);
203 if (elem && isHidden(elem)) {
204 var h3 = elem.parentNode.previousElementSibling;
205 if (h3 && h3.tagName !== "H3") {
206 h3 = h3.previousElementSibling; // skip div.docblock
210 var collapses = h3.getElementsByClassName("collapse-toggle");
211 if (collapses.length > 0) {
212 // The element is not visible, we need to make it appear!
213 collapseDocs(collapses[0], "show");
219 highlightSourceLines(null);
220 window.onhashchange = highlightSourceLines;
222 // Gets the human-readable string for the virtual-key code of the
223 // given KeyboardEvent, ev.
225 // This function is meant as a polyfill for KeyboardEvent#key,
226 // since it is not supported in Trident. We also test for
227 // KeyboardEvent#keyCode because the handleShortcut handler is
228 // also registered for the keydown event, because Blink doesn't fire
229 // keypress on hitting the Escape key.
231 // So I guess you could say things are getting pretty interoperable.
232 function getVirtualKey(ev) {
233 if ("key" in ev && typeof ev.key != "undefined") {
237 var c = ev.charCode || ev.keyCode;
241 return String.fromCharCode(c);
244 function displayHelp(display, ev) {
245 if (display === true) {
246 if (hasClass(help, "hidden")) {
248 removeClass(help, "hidden");
249 addClass(document.body, "blur");
251 } else if (hasClass(help, "hidden") === false) {
253 addClass(help, "hidden");
254 removeClass(document.body, "blur");
258 function handleEscape(ev, help) {
260 var search = document.getElementById("search");
261 if (hasClass(help, "hidden") === false) {
262 displayHelp(false, ev);
263 } else if (hasClass(search, "hidden") === false) {
265 addClass(search, "hidden");
266 removeClass(main, "hidden");
267 document.title = titleBeforeSearch;
272 function handleShortcut(ev) {
273 // Don't interfere with browser shortcuts
274 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
278 var help = document.getElementById("help");
279 if (document.activeElement.tagName === "INPUT") {
280 switch (getVirtualKey(ev)) {
282 handleEscape(ev, help);
286 switch (getVirtualKey(ev)) {
288 handleEscape(ev, help);
293 displayHelp(false, ev);
308 displayHelp(true, ev);
315 function findParentElement(elem, tagName) {
317 if (elem && elem.tagName === tagName) {
320 elem = elem.parentNode;
325 document.onkeypress = handleShortcut;
326 document.onkeydown = handleShortcut;
327 document.onclick = function(ev) {
328 if (hasClass(ev.target, "collapse-toggle")) {
329 collapseDocs(ev.target, "toggle");
330 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
331 collapseDocs(ev.target.parentNode, "toggle");
332 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
335 var set_fragment = function(name) {
336 if (browserSupportsHistoryApi()) {
337 history.replaceState(null, null, "#" + name);
340 location.replace("#" + name);
344 var cur_id = parseInt(ev.target.id, 10);
346 if (ev.shiftKey && prev_id) {
347 if (prev_id > cur_id) {
353 set_fragment(prev_id + "-" + cur_id);
357 set_fragment(cur_id);
359 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
360 addClass(document.getElementById("help"), "hidden");
361 removeClass(document.body, "blur");
363 // Making a collapsed element visible on onhashchange seems
365 var a = findParentElement(ev.target, "A");
367 expandSection(a.hash.replace(/^#/, ""));
372 var x = document.getElementsByClassName("version-selector");
374 x[0].onchange = function() {
376 url = document.location.href,
378 len = rootPath.match(/\.\.\//g).length + 1;
380 for (i = 0; i < len; ++i) {
381 match = url.match(/\/[^\/]*$/);
383 stripped = match[0] + stripped;
385 url = url.substring(0, url.length - match[0].length);
388 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
390 document.location.href = url;
395 * A function to compute the Levenshtein distance between two strings
396 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
397 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
398 * This code is an unmodified version of the code written by Marco de Wit
399 * and was found at http://stackoverflow.com/a/18514751/745719
401 var levenshtein_row2 = [];
402 function levenshtein(s1, s2) {
406 var s1_len = s1.length, s2_len = s2.length;
407 if (s1_len && s2_len) {
408 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
409 while (i1 < s1_len) {
412 while (i2 < s2_len) {
413 c2 = s2.charCodeAt(i2);
417 for (i1 = 0; i1 < s1_len; ++i1) {
418 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
420 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
426 return s1_len + s2_len;
429 function initSearch(rawSearchIndex) {
430 var currentResults, index, searchIndex;
431 var MAX_LEV_DISTANCE = 3;
432 var MAX_RESULTS = 200;
433 var GENERICS_DATA = 1;
437 var params = getQueryStringParams();
439 // Populate search bar with query string search term when provided,
440 // but only if the input bar is empty. This avoid the obnoxious issue
441 // where you start trying to do a search, and the index loads, and
442 // suddenly your search is gone!
443 if (search_input.value === "") {
444 search_input.value = params.search || "";
448 * Executes the query and builds an index of results
449 * @param {[Object]} query [The user query]
450 * @param {[type]} searchWords [The list of search words to query
452 * @param {[type]} filterCrates [Crate to search in if defined]
453 * @return {[type]} [A search index of results]
455 function execQuery(query, searchWords, filterCrates) {
456 function itemTypeFromName(typename) {
457 var length = itemTypes.length;
458 for (var i = 0; i < length; ++i) {
459 if (itemTypes[i] === typename) {
466 var valLower = query.query.toLowerCase(),
468 typeFilter = itemTypeFromName(query.type),
469 results = {}, results_in_args = {}, results_returned = {},
470 split = valLower.split("::");
472 var length = split.length;
473 for (var z = 0; z < length; ++z) {
474 if (split[z] === "") {
480 function transformResults(results, isType) {
482 var length = results.length;
483 for (var i = 0; i < length; ++i) {
484 if (results[i].id > -1) {
485 var obj = searchIndex[results[i].id];
486 obj.lev = results[i].lev;
487 if (isType !== true || obj.type) {
488 var res = buildHrefAndPath(obj);
489 obj.displayPath = pathSplitter(res[0]);
490 obj.fullPath = obj.displayPath + obj.name;
491 // To be sure than it some items aren't considered as duplicate.
492 obj.fullPath += "|" + obj.ty;
495 if (out.length >= MAX_RESULTS) {
504 function sortResults(results, isType) {
506 for (var entry in results) {
507 if (results.hasOwnProperty(entry)) {
508 ar.push(results[entry]);
513 var nresults = results.length;
514 for (i = 0; i < nresults; ++i) {
515 results[i].word = searchWords[results[i].id];
516 results[i].item = searchIndex[results[i].id] || {};
518 // if there are no results then return to default and fail
519 if (results.length === 0) {
523 results.sort(function(aaa, bbb) {
526 // Sort by non levenshtein results and then levenshtein results by the distance
527 // (less changes required to match means higher rankings)
530 if (a !== b) { return a - b; }
532 // sort by crate (non-current crate goes later)
533 a = (aaa.item.crate !== window.currentCrate);
534 b = (bbb.item.crate !== window.currentCrate);
535 if (a !== b) { return a - b; }
537 // sort by exact match (mismatch goes later)
538 a = (aaa.word !== valLower);
539 b = (bbb.word !== valLower);
540 if (a !== b) { return a - b; }
542 // sort by item name length (longer goes later)
545 if (a !== b) { return a - b; }
547 // sort by item name (lexicographically larger goes later)
550 if (a !== b) { return (a > b ? +1 : -1); }
552 // sort by index of keyword in item name (no literal occurrence goes later)
555 if (a !== b) { return a - b; }
556 // (later literal occurrence, if any, goes later)
559 if (a !== b) { return a - b; }
561 // special precedence for primitive and keyword pages
562 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
563 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
566 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
567 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
571 // sort by description (no description goes later)
572 a = (aaa.item.desc === "");
573 b = (bbb.item.desc === "");
574 if (a !== b) { return a - b; }
576 // sort by type (later occurrence in `itemTypes` goes later)
579 if (a !== b) { return a - b; }
581 // sort by path (lexicographically larger goes later)
584 if (a !== b) { return (a > b ? +1 : -1); }
590 var length = results.length;
591 for (i = 0; i < length; ++i) {
592 var result = results[i];
594 // this validation does not make sense when searching by types
595 if (result.dontValidate) {
598 var name = result.item.name.toLowerCase(),
599 path = result.item.path.toLowerCase(),
600 parent = result.item.parent;
602 if (isType !== true &&
603 validateResult(name, path, split, parent) === false)
608 return transformResults(results);
611 function extractGenerics(val) {
612 val = val.toLowerCase();
613 if (val.indexOf("<") !== -1) {
614 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
616 name: val.substring(0, val.indexOf("<")),
617 generics: values.split(/\s*,\s*/),
626 function checkGenerics(obj, val) {
627 // The names match, but we need to be sure that all generics kinda
629 var lev_distance = MAX_LEV_DISTANCE + 1;
630 if (val.generics.length > 0) {
631 if (obj.length > GENERICS_DATA &&
632 obj[GENERICS_DATA].length >= val.generics.length) {
633 var elems = obj[GENERICS_DATA].slice(0);
636 // We need to find the type that matches the most to remove it in order
638 var vlength = val.generics.length;
639 for (var y = 0; y < vlength; ++y) {
640 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
641 var elength = elems.length;
642 for (var x = 0; x < elength; ++x) {
643 var tmp_lev = levenshtein(elems[x], val.generics[y]);
644 if (tmp_lev < lev.lev) {
649 if (lev.pos !== -1) {
650 elems.splice(lev.pos, 1);
651 lev_distance = Math.min(lev.lev, lev_distance);
655 return MAX_LEV_DISTANCE + 1;
658 return lev_distance;//Math.ceil(total / done);
661 return MAX_LEV_DISTANCE + 1;
664 // Check for type name and type generics (if any).
665 function checkType(obj, val, literalSearch) {
666 var lev_distance = MAX_LEV_DISTANCE + 1;
668 if (obj[NAME] === val.name) {
669 if (literalSearch === true) {
670 if (val.generics && val.generics.length !== 0) {
671 if (obj.length > GENERICS_DATA &&
672 obj[GENERICS_DATA].length >= val.generics.length) {
673 var elems = obj[GENERICS_DATA].slice(0);
676 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
678 for (x = 0; allFound === false && x < elems.length; ++x) {
679 allFound = elems[x] === val.generics[y];
681 if (allFound === true) {
682 elems.splice(x - 1, 1);
685 if (allFound === true) {
694 // If the type has generics but don't match, then it won't return at this point.
695 // Otherwise, `checkGenerics` will return 0 and it'll return.
696 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
697 var tmp_lev = checkGenerics(obj, val);
698 if (tmp_lev <= MAX_LEV_DISTANCE) {
705 // Names didn't match so let's check if one of the generic types could.
706 if (literalSearch === true) {
707 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
708 var length = obj[GENERICS_DATA].length;
709 for (x = 0; x < length; ++x) {
710 if (obj[GENERICS_DATA][x] === val.name) {
717 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
718 if (lev_distance <= MAX_LEV_DISTANCE) {
719 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
720 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
721 // We can check if the type we're looking for is inside the generics!
722 var olength = obj[GENERICS_DATA].length;
723 for (x = 0; x < olength; ++x) {
724 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
728 // Now whatever happens, the returned distance is "less good" so we should mark it
729 // as such, and so we add 1 to the distance to make it "less good".
730 return lev_distance + 1;
733 function findArg(obj, val, literalSearch) {
734 var lev_distance = MAX_LEV_DISTANCE + 1;
736 if (obj && obj.type && obj.type[INPUTS_DATA] &&
737 obj.type[INPUTS_DATA].length > 0) {
738 var length = obj.type[INPUTS_DATA].length;
739 for (var i = 0; i < length; i++) {
740 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
741 if (literalSearch === true && tmp === true) {
744 lev_distance = Math.min(tmp, lev_distance);
745 if (lev_distance === 0) {
750 return literalSearch === true ? false : lev_distance;
753 function checkReturned(obj, val, literalSearch) {
754 var lev_distance = MAX_LEV_DISTANCE + 1;
756 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
757 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
758 if (literalSearch === true && tmp === true) {
761 lev_distance = Math.min(tmp, lev_distance);
762 if (lev_distance === 0) {
766 return literalSearch === true ? false : lev_distance;
769 function checkPath(contains, lastElem, ty) {
770 if (contains.length === 0) {
773 var ret_lev = MAX_LEV_DISTANCE + 1;
774 var path = ty.path.split("::");
776 if (ty.parent && ty.parent.name) {
777 path.push(ty.parent.name.toLowerCase());
780 var length = path.length;
781 var clength = contains.length;
782 if (clength > length) {
783 return MAX_LEV_DISTANCE + 1;
785 for (var i = 0; i < length; ++i) {
786 if (i + clength > length) {
791 for (var x = 0; x < clength; ++x) {
792 var lev = levenshtein(path[i + x], contains[x]);
793 if (lev > MAX_LEV_DISTANCE) {
799 if (aborted === false) {
800 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
806 function typePassesFilter(filter, type) {
808 if (filter < 0) return true;
811 if (filter === type) return true;
813 // Match related items
814 var name = itemTypes[type];
815 switch (itemTypes[filter]) {
817 return (name == "associatedconstant");
819 return (name == "method" || name == "tymethod");
821 return (name == "primitive" || name == "keyword");
828 function generateId(ty) {
829 if (ty.parent && ty.parent.name) {
830 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
832 return itemTypes[ty.ty] + ty.path + ty.name;
835 // quoted values mean literal search
836 var nSearchWords = searchWords.length;
842 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
843 val.charAt(val.length - 1) === val.charAt(0))
845 val = extractGenerics(val.substr(1, val.length - 2));
846 for (i = 0; i < nSearchWords; ++i) {
847 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
850 in_args = findArg(searchIndex[i], val, true);
851 returned = checkReturned(searchIndex[i], val, true);
853 fullId = generateId(ty);
855 if (searchWords[i] === val.name) {
856 // filter type: ... queries
857 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
858 results[fullId] === undefined)
860 results[fullId] = {id: i, index: -1};
862 } else if ((in_args === true || returned === true) &&
863 typePassesFilter(typeFilter, searchIndex[i].ty)) {
864 if (in_args === true || returned === true) {
865 if (in_args === true) {
866 results_in_args[fullId] = {
872 if (returned === true) {
873 results_returned[fullId] = {
888 query.inputs = [val];
892 } else if (val.search("->") > -1) {
893 var trimmer = function(s) { return s.trim(); };
894 var parts = val.split("->").map(trimmer);
895 var input = parts[0];
896 // sort inputs so that order does not matter
897 var inputs = input.split(",").map(trimmer).sort();
898 for (i = 0; i < inputs.length; ++i) {
899 inputs[i] = extractGenerics(inputs[i]);
901 var output = extractGenerics(parts[1]);
903 for (i = 0; i < nSearchWords; ++i) {
904 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
907 var type = searchIndex[i].type;
912 fullId = generateId(ty);
914 // allow searching for void (no output) functions as well
915 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
916 returned = checkReturned(ty, output, true);
917 if (output.name === "*" || returned === true) {
925 for (var it = 0; allFound === true && it < inputs.length; it++) {
926 allFound = checkType(type, inputs[it], true);
930 if (in_args === true) {
931 results_in_args[fullId] = {
937 if (returned === true) {
938 results_returned[fullId] = {
944 if (module === true) {
953 query.inputs = inputs.map(function(input) {
956 query.output = output.name;
958 query.inputs = [val];
961 // gather matching search results up to a certain maximum
962 val = val.replace(/\_/g, "");
964 var valGenerics = extractGenerics(val);
966 var paths = valLower.split("::");
968 for (j = 0; j < paths.length; ++j) {
969 if (paths[j] === "") {
974 val = paths[paths.length - 1];
975 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
977 for (j = 0; j < nSearchWords; ++j) {
981 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
986 if (paths.length > 1) {
987 lev = checkPath(contains, paths[paths.length - 1], ty);
988 if (lev > MAX_LEV_DISTANCE) {
990 } else if (lev > 0) {
995 returned = MAX_LEV_DISTANCE + 1;
996 in_args = MAX_LEV_DISTANCE + 1;
998 // we want lev results to go lower than others
999 lev = MAX_LEV_DISTANCE + 1;
1000 fullId = generateId(ty);
1002 if (searchWords[j].indexOf(split[i]) > -1 ||
1003 searchWords[j].indexOf(val) > -1 ||
1004 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1006 // filter type: ... queries
1007 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1008 index = searchWords[j].replace(/_/g, "").indexOf(val);
1011 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1012 if (typePassesFilter(typeFilter, ty.ty) === false) {
1013 lev = MAX_LEV_DISTANCE + 1;
1018 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1019 if (typePassesFilter(typeFilter, ty.ty) === false) {
1020 in_args = MAX_LEV_DISTANCE + 1;
1023 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1024 if (typePassesFilter(typeFilter, ty.ty) === false) {
1025 returned = MAX_LEV_DISTANCE + 1;
1030 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1031 if (val.length < 6) {
1037 if (in_args <= MAX_LEV_DISTANCE) {
1038 if (results_in_args[fullId] === undefined) {
1039 results_in_args[fullId] = {
1045 results_in_args[fullId].lev =
1046 Math.min(results_in_args[fullId].lev, in_args);
1048 if (returned <= MAX_LEV_DISTANCE) {
1049 if (results_returned[fullId] === undefined) {
1050 results_returned[fullId] = {
1056 results_returned[fullId].lev =
1057 Math.min(results_returned[fullId].lev, returned);
1059 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1060 if (index !== -1 && paths.length < 2) {
1063 if (results[fullId] === undefined) {
1070 results[fullId].lev = Math.min(results[fullId].lev, lev);
1076 "in_args": sortResults(results_in_args, true),
1077 "returned": sortResults(results_returned, true),
1078 "others": sortResults(results),
1080 if (ALIASES && ALIASES[window.currentCrate] &&
1081 ALIASES[window.currentCrate][query.raw]) {
1082 var aliases = ALIASES[window.currentCrate][query.raw];
1083 for (i = 0; i < aliases.length; ++i) {
1084 aliases[i].is_alias = true;
1085 aliases[i].alias = query.raw;
1086 aliases[i].path = aliases[i].p;
1087 var res = buildHrefAndPath(aliases[i]);
1088 aliases[i].displayPath = pathSplitter(res[0]);
1089 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1090 aliases[i].href = res[1];
1091 ret.others.unshift(aliases[i]);
1092 if (ret.others.length > MAX_RESULTS) {
1101 * Validate performs the following boolean logic. For example:
1102 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1103 * exists in (name || path || parent) OR => ("file" && "open") exists in
1106 * This could be written functionally, but I wanted to minimise
1107 * functions on stack.
1109 * @param {[string]} name [The name of the result]
1110 * @param {[string]} path [The path of the result]
1111 * @param {[string]} keys [The keys to be used (["file", "open"])]
1112 * @param {[object]} parent [The parent of the result]
1113 * @return {[boolean]} [Whether the result is valid or not]
1115 function validateResult(name, path, keys, parent) {
1116 for (var i = 0; i < keys.length; ++i) {
1117 // each check is for validation so we negate the conditions and invalidate
1119 // check for an exact name match
1120 name.indexOf(keys[i]) > -1 ||
1121 // then an exact path match
1122 path.indexOf(keys[i]) > -1 ||
1123 // next if there is a parent, check for exact parent match
1124 (parent !== undefined &&
1125 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1126 // lastly check to see if the name was a levenshtein match
1127 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1134 function getQuery(raw) {
1135 var matches, type, query;
1138 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1140 type = matches[1].replace(/^const$/, "constant");
1141 query = query.substring(matches[0].length);
1152 function initSearchNav() {
1155 var click_func = function(e) {
1157 // to retrieve the real "owner" of the event.
1158 while (el.tagName !== "TR") {
1161 var dst = e.target.getElementsByTagName("a");
1162 if (dst.length < 1) {
1166 if (window.location.pathname === dst.pathname) {
1167 addClass(document.getElementById("search"), "hidden");
1168 removeClass(main, "hidden");
1169 document.location.href = dst.href;
1172 var mouseover_func = function(e) {
1174 // to retrieve the real "owner" of the event.
1175 while (el.tagName !== "TR") {
1178 clearTimeout(hoverTimeout);
1179 hoverTimeout = setTimeout(function() {
1180 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1181 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1182 removeClass(i_e, "highlighted");
1185 addClass(el, "highlighted");
1188 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1189 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1190 i_e.onclick = click_func;
1191 i_e.onmouseover = mouseover_func;
1195 search_input.onkeydown = function(e) {
1196 // "actives" references the currently highlighted item in each search tab.
1197 // Each array in "actives" represents a tab.
1198 var actives = [[], [], []];
1199 // "current" is used to know which tab we're looking into.
1201 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1202 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1203 actives[current].push(e);
1208 if (e.which === 38) { // up
1209 if (!actives[currentTab].length ||
1210 !actives[currentTab][0].previousElementSibling) {
1214 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1215 removeClass(actives[currentTab][0], "highlighted");
1216 } else if (e.which === 40) { // down
1217 if (!actives[currentTab].length) {
1218 var results = document.getElementsByClassName("search-results");
1219 if (results.length > 0) {
1220 var res = results[currentTab].getElementsByClassName("result");
1221 if (res.length > 0) {
1222 addClass(res[0], "highlighted");
1225 } else if (actives[currentTab][0].nextElementSibling) {
1226 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1227 removeClass(actives[currentTab][0], "highlighted");
1229 } else if (e.which === 13) { // return
1230 if (actives[currentTab].length) {
1231 document.location.href =
1232 actives[currentTab][0].getElementsByTagName("a")[0].href;
1234 } else if (e.which === 9) { // tab
1236 printTab(currentTab > 0 ? currentTab - 1 : 2);
1238 printTab(currentTab > 1 ? 0 : currentTab + 1);
1241 } else if (e.which === 16) { // shift
1242 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1243 } else if (e.which === 27) { // escape
1244 removeClass(actives[currentTab][0], "highlighted");
1245 search_input.value = "";
1247 } else if (actives[currentTab].length > 0) {
1248 removeClass(actives[currentTab][0], "highlighted");
1253 function buildHrefAndPath(item) {
1256 var type = itemTypes[item.ty];
1257 var name = item.name;
1259 if (type === "mod") {
1260 displayPath = item.path + "::";
1261 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1262 name + "/index.html";
1263 } else if (type === "primitive" || type === "keyword") {
1265 href = rootPath + item.path.replace(/::/g, "/") +
1266 "/" + type + "." + name + ".html";
1267 } else if (type === "externcrate") {
1269 href = rootPath + name + "/index.html";
1270 } else if (item.parent !== undefined) {
1271 var myparent = item.parent;
1272 var anchor = "#" + type + "." + name;
1273 var parentType = itemTypes[myparent.ty];
1274 if (parentType === "primitive") {
1275 displayPath = myparent.name + "::";
1277 displayPath = item.path + "::" + myparent.name + "::";
1279 href = rootPath + item.path.replace(/::/g, "/") +
1281 "." + myparent.name +
1284 displayPath = item.path + "::";
1285 href = rootPath + item.path.replace(/::/g, "/") +
1286 "/" + type + "." + name + ".html";
1288 return [displayPath, href];
1291 function escape(content) {
1292 var h1 = document.createElement("h1");
1293 h1.textContent = content;
1294 return h1.innerHTML;
1297 function pathSplitter(path) {
1298 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1299 if (tmp.endsWith("<span>")) {
1300 return tmp.slice(0, tmp.length - 6);
1305 function addTab(array, query, display) {
1306 var extraStyle = "";
1307 if (display === false) {
1308 extraStyle = " style=\"display: none;\"";
1312 var duplicates = {};
1314 if (array.length > 0) {
1315 output = "<table class=\"search-results\"" + extraStyle + ">";
1317 array.forEach(function(item) {
1321 type = itemTypes[item.ty];
1323 if (item.is_alias !== true) {
1324 if (duplicates[item.fullPath]) {
1327 duplicates[item.fullPath] = true;
1331 output += "<tr class=\"" + type + " result\"><td>" +
1332 "<a href=\"" + item.href + "\">" +
1333 (item.is_alias === true ?
1334 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1335 "class=\"grey\"><i> - see </i></span>") : "") +
1336 item.displayPath + "<span class=\"" + type + "\">" +
1337 name + "</span></a></td><td>" +
1338 "<a href=\"" + item.href + "\">" +
1339 "<span class=\"desc\">" + escape(item.desc) +
1340 " </span></a></td></tr>";
1342 output += "</table>";
1344 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1345 "Try on <a href=\"https://duckduckgo.com/?q=" +
1346 encodeURIComponent("rust " + query.query) +
1347 "\">DuckDuckGo</a>?<br/><br/>" +
1348 "Or try looking in one of these:<ul><li>The <a " +
1349 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1350 " for technical details about the language.</li><li><a " +
1351 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1352 "Example</a> for expository code examples.</a></li><li>The <a " +
1353 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1354 "introductions to language features and the language itself.</li><li><a " +
1355 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1356 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1358 return [output, length];
1361 function makeTabHeader(tabNb, text, nbElems) {
1362 if (currentTab === tabNb) {
1363 return "<div class=\"selected\">" + text +
1364 " <div class=\"count\">(" + nbElems + ")</div></div>";
1366 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1369 function showResults(results) {
1370 if (results.others.length === 1 &&
1371 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1372 var elem = document.createElement("a");
1373 elem.href = results.others[0].href;
1374 elem.style.display = "none";
1375 // For firefox, we need the element to be in the DOM so it can be clicked.
1376 document.body.appendChild(elem);
1379 var query = getQuery(search_input.value);
1381 currentResults = query.id;
1383 var ret_others = addTab(results.others, query);
1384 var ret_in_args = addTab(results.in_args, query, false);
1385 var ret_returned = addTab(results.returned, query, false);
1387 var output = "<h1>Results for " + escape(query.query) +
1388 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1389 "<div id=\"titles\">" +
1390 makeTabHeader(0, "In Names", ret_others[1]) +
1391 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1392 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1393 "</div><div id=\"results\">" +
1394 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1396 addClass(main, "hidden");
1397 var search = document.getElementById("search");
1398 removeClass(search, "hidden");
1399 search.innerHTML = output;
1400 var tds = search.getElementsByTagName("td");
1402 if (tds.length > 0) {
1403 td_width = tds[0].offsetWidth;
1405 var width = search.offsetWidth - 40 - td_width;
1406 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1407 e.style.width = width + "px";
1410 var elems = document.getElementById("titles").childNodes;
1411 elems[0].onclick = function() { printTab(0); };
1412 elems[1].onclick = function() { printTab(1); };
1413 elems[2].onclick = function() { printTab(2); };
1414 printTab(currentTab);
1417 function execSearch(query, searchWords, filterCrates) {
1418 function getSmallest(arrays, positions, notDuplicates) {
1421 for (var it = 0; it < positions.length; ++it) {
1422 if (arrays[it].length > positions[it] &&
1423 (start === null || start > arrays[it][positions[it]].lev) &&
1424 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1425 start = arrays[it][positions[it]].lev;
1431 function mergeArrays(arrays) {
1434 var notDuplicates = {};
1436 for (var x = 0; x < arrays.length; ++x) {
1439 while (ret.length < MAX_RESULTS) {
1440 var smallest = getSmallest(arrays, positions, notDuplicates);
1442 if (smallest === null) {
1445 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1446 if (arrays[x].length > positions[x] &&
1447 arrays[x][positions[x]].lev === smallest &&
1448 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1449 ret.push(arrays[x][positions[x]]);
1450 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1458 var queries = query.raw.split(",");
1465 for (var i = 0; i < queries.length; ++i) {
1466 query = queries[i].trim();
1467 if (query.length !== 0) {
1468 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1470 results.in_args.push(tmp.in_args);
1471 results.returned.push(tmp.returned);
1472 results.others.push(tmp.others);
1475 if (queries.length > 1) {
1477 "in_args": mergeArrays(results.in_args),
1478 "returned": mergeArrays(results.returned),
1479 "others": mergeArrays(results.others),
1483 "in_args": results.in_args[0],
1484 "returned": results.returned[0],
1485 "others": results.others[0],
1490 function getFilterCrates() {
1491 var elem = document.getElementById("crate-search");
1493 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1499 function search(e, forced) {
1500 var params = getQueryStringParams();
1501 var query = getQuery(search_input.value.trim());
1507 if (query.query.length === 0) {
1510 if (forced !== true && query.id === currentResults) {
1511 if (query.query.length > 0) {
1512 putBackSearch(search_input);
1517 // Update document title to maintain a meaningful browser history
1518 document.title = "Results for " + query.query + " - Rust";
1520 // Because searching is incremental by character, only the most
1521 // recent search query is added to the browser history.
1522 if (browserSupportsHistoryApi()) {
1523 if (!history.state && !params.search) {
1524 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1526 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1530 var filterCrates = getFilterCrates();
1531 showResults(execSearch(query, index, filterCrates), filterCrates);
1534 function buildIndex(rawSearchIndex) {
1536 var searchWords = [];
1539 for (var crate in rawSearchIndex) {
1540 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1542 searchWords.push(crate);
1545 ty: 1, // == ExternCrate
1548 desc: rawSearchIndex[crate].doc,
1552 // an array of [(Number) item type,
1554 // (String) full path or empty string for previous path,
1555 // (String) description,
1556 // (Number | null) the parent path index to `paths`]
1557 // (Object | null) the type of the function (if any)
1558 var items = rawSearchIndex[crate].i;
1559 // an array of [(Number) item type,
1561 var paths = rawSearchIndex[crate].p;
1563 // convert `paths` into an object form
1564 var len = paths.length;
1565 for (i = 0; i < len; ++i) {
1566 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1569 // convert `items` into an object form, and construct word indices.
1571 // before any analysis is performed lets gather the search terms to
1572 // search against apart from the rest of the data. This is a quick
1573 // operation that is cached for the life of the page state so that
1574 // all other search operations have access to this cached data for
1575 // faster analysis operations
1578 for (i = 0; i < len; ++i) {
1579 var rawRow = items[i];
1580 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1581 path: rawRow[2] || lastPath, desc: rawRow[3],
1582 parent: paths[rawRow[4]], type: rawRow[5]};
1583 searchIndex.push(row);
1584 if (typeof row.name === "string") {
1585 var word = row.name.toLowerCase();
1586 searchWords.push(word);
1588 searchWords.push("");
1590 lastPath = row.path;
1596 function startSearch() {
1598 var callback = function() {
1599 clearTimeout(searchTimeout);
1600 if (search_input.value.length === 0) {
1601 if (browserSupportsHistoryApi()) {
1602 history.replaceState("", "std - Rust", "?search=");
1604 if (hasClass(main, "content")) {
1605 removeClass(main, "hidden");
1607 var search_c = document.getElementById("search");
1608 if (hasClass(search_c, "content")) {
1609 addClass(search_c, "hidden");
1612 searchTimeout = setTimeout(search, 500);
1615 search_input.onkeyup = callback;
1616 search_input.oninput = callback;
1617 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1619 clearTimeout(searchTimeout);
1622 search_input.onchange = function(e) {
1623 // Do NOT e.preventDefault() here. It will prevent pasting.
1624 clearTimeout(searchTimeout);
1625 // zero-timeout necessary here because at the time of event handler execution the
1626 // pasted content is not in the input field yet. Shouldn’t make any difference for
1628 setTimeout(search, 0);
1630 search_input.onpaste = search_input.onchange;
1632 var selectCrate = document.getElementById('crate-search');
1634 selectCrate.onchange = function() {
1635 search(undefined, true);
1639 // Push and pop states are used to add search results to the browser
1641 if (browserSupportsHistoryApi()) {
1642 // Store the previous <title> so we can revert back to it later.
1643 var previousTitle = document.title;
1645 window.onpopstate = function(e) {
1646 var params = getQueryStringParams();
1647 // When browsing back from search results the main page
1648 // visibility must be reset.
1649 if (!params.search) {
1650 if (hasClass(main, "content")) {
1651 removeClass(main, "hidden");
1653 var search_c = document.getElementById("search");
1654 if (hasClass(search_c, "content")) {
1655 addClass(search_c, "hidden");
1658 // Revert to the previous title manually since the History
1659 // API ignores the title parameter.
1660 document.title = previousTitle;
1661 // When browsing forward to search results the previous
1662 // search will be repeated, so the currentResults are
1663 // cleared to ensure the search is successful.
1664 currentResults = null;
1665 // Synchronize search bar with query string state and
1666 // perform the search. This will empty the bar if there's
1667 // nothing there, which lets you really go back to a
1668 // previous state with nothing in the bar.
1669 if (params.search) {
1670 search_input.value = params.search;
1672 search_input.value = "";
1674 // Some browsers fire "onpopstate" for every page load
1675 // (Chrome), while others fire the event only when actually
1676 // popping a state (Firefox), which is why search() is
1677 // called both here and at the end of the startSearch()
1685 index = buildIndex(rawSearchIndex);
1688 // Draw a convenient sidebar of known crates if we have a listing
1689 if (rootPath === "../" || rootPath === "./") {
1690 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1692 var div = document.createElement("div");
1693 div.className = "block crate";
1694 div.innerHTML = "<h3>Crates</h3>";
1695 var ul = document.createElement("ul");
1696 div.appendChild(ul);
1699 for (var crate in rawSearchIndex) {
1700 if (!rawSearchIndex.hasOwnProperty(crate)) {
1706 for (var i = 0; i < crates.length; ++i) {
1707 var klass = "crate";
1708 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1709 klass += " current";
1711 var link = document.createElement("a");
1712 link.href = rootPath + crates[i] + "/index.html";
1713 link.title = rawSearchIndex[crates[i]].doc;
1714 link.className = klass;
1715 link.textContent = crates[i];
1717 var li = document.createElement("li");
1718 li.appendChild(link);
1721 sidebar.appendChild(div);
1726 window.initSearch = initSearch;
1728 // delayed sidebar rendering.
1729 function initSidebarItems(items) {
1730 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1731 var current = window.sidebarCurrent;
1733 function block(shortty, longty) {
1734 var filtered = items[shortty];
1739 var div = document.createElement("div");
1740 div.className = "block " + shortty;
1741 var h3 = document.createElement("h3");
1742 h3.textContent = longty;
1743 div.appendChild(h3);
1744 var ul = document.createElement("ul");
1746 var length = filtered.length;
1747 for (var i = 0; i < length; ++i) {
1748 var item = filtered[i];
1750 var desc = item[1]; // can be null
1752 var klass = shortty;
1753 if (name === current.name && shortty === current.ty) {
1754 klass += " current";
1757 if (shortty === "mod") {
1758 path = name + "/index.html";
1760 path = shortty + "." + name + ".html";
1762 var link = document.createElement("a");
1763 link.href = current.relpath + path;
1765 link.className = klass;
1766 link.textContent = name;
1767 var li = document.createElement("li");
1768 li.appendChild(link);
1771 div.appendChild(ul);
1773 sidebar.appendChild(div);
1777 block("primitive", "Primitive Types");
1778 block("mod", "Modules");
1779 block("macro", "Macros");
1780 block("struct", "Structs");
1781 block("enum", "Enums");
1782 block("union", "Unions");
1783 block("constant", "Constants");
1784 block("static", "Statics");
1785 block("trait", "Traits");
1786 block("fn", "Functions");
1787 block("type", "Type Definitions");
1788 block("foreigntype", "Foreign Types");
1789 block("keyword", "Keywords");
1792 window.initSidebarItems = initSidebarItems;
1794 window.register_implementors = function(imp) {
1795 var implementors = document.getElementById("implementors-list");
1796 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1798 var libs = Object.getOwnPropertyNames(imp);
1799 var llength = libs.length;
1800 for (var i = 0; i < llength; ++i) {
1801 if (libs[i] === currentCrate) { continue; }
1802 var structs = imp[libs[i]];
1804 var slength = structs.length;
1806 for (var j = 0; j < slength; ++j) {
1807 var struct = structs[j];
1809 var list = struct.synthetic ? synthetic_implementors : implementors;
1811 if (struct.synthetic) {
1812 var stlength = struct.types.length;
1813 for (var k = 0; k < stlength; k++) {
1814 if (window.inlined_types.has(struct.types[k])) {
1815 continue struct_loop;
1817 window.inlined_types.add(struct.types[k]);
1821 var code = document.createElement("code");
1822 code.innerHTML = struct.text;
1824 var x = code.getElementsByTagName("a");
1825 var xlength = x.length;
1826 for (var it = 0; it < xlength; it++) {
1827 var href = x[it].getAttribute("href");
1828 if (href && href.indexOf("http") !== 0) {
1829 x[it].setAttribute("href", rootPath + href);
1832 var display = document.createElement("h3");
1833 addClass(display, "impl");
1834 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1835 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1836 "</tbody></table></span>";
1837 list.appendChild(display);
1841 if (window.pending_implementors) {
1842 window.register_implementors(window.pending_implementors);
1845 function labelForToggleButton(sectionIsCollapsed) {
1846 if (sectionIsCollapsed) {
1847 // button will expand the section
1850 // button will collapse the section
1851 // note that this text is also set in the HTML template in render.rs
1852 return "\u2212"; // "\u2212" is "−" minus sign
1855 function onEveryMatchingChild(elem, className, func) {
1856 if (elem && className && func) {
1857 var length = elem.childNodes.length;
1858 var nodes = elem.childNodes;
1859 for (var i = 0; i < length; ++i) {
1860 if (hasClass(nodes[i], className)) {
1863 onEveryMatchingChild(nodes[i], className, func);
1869 function toggleAllDocs(pageId, fromAutoCollapse) {
1870 var innerToggle = document.getElementById("toggle-all-docs");
1874 if (hasClass(innerToggle, "will-expand")) {
1875 updateLocalStorage("rustdoc-collapse", "false");
1876 removeClass(innerToggle, "will-expand");
1877 onEveryMatchingChild(innerToggle, "inner", function(e) {
1878 e.innerHTML = labelForToggleButton(false);
1880 innerToggle.title = "collapse all docs";
1881 if (fromAutoCollapse !== true) {
1882 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1883 collapseDocs(e, "show");
1887 updateLocalStorage("rustdoc-collapse", "true");
1888 addClass(innerToggle, "will-expand");
1889 onEveryMatchingChild(innerToggle, "inner", function(e) {
1890 e.innerHTML = labelForToggleButton(true);
1892 innerToggle.title = "expand all docs";
1893 if (fromAutoCollapse !== true) {
1894 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1895 collapseDocs(e, "hide", pageId);
1901 function collapseDocs(toggle, mode, pageId) {
1902 if (!toggle || !toggle.parentNode) {
1906 function adjustToggle(arg) {
1907 return function(e) {
1908 if (hasClass(e, "toggle-label")) {
1910 e.style.display = "inline-block";
1912 e.style.display = "none";
1915 if (hasClass(e, "inner")) {
1916 e.innerHTML = labelForToggleButton(arg);
1921 function implHider(addOrRemove) {
1922 return function(n) {
1923 var is_method = hasClass(n, "method");
1924 if (is_method || hasClass(n, "type")) {
1925 if (is_method === true) {
1927 addClass(n, "hidden-by-impl-hider");
1929 removeClass(n, "hidden-by-impl-hider");
1932 var ns = n.nextElementSibling;
1935 hasClass(ns, "docblock") ||
1936 hasClass(ns, "stability"))) {
1938 addClass(ns, "hidden-by-impl-hider");
1940 removeClass(ns, "hidden-by-impl-hider");
1942 ns = ns.nextElementSibling;
1953 if (hasClass(toggle.parentNode, "impl") === false) {
1954 relatedDoc = toggle.parentNode.nextElementSibling;
1955 if (hasClass(relatedDoc, "stability")) {
1956 relatedDoc = relatedDoc.nextElementSibling;
1958 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1959 if (mode === "toggle") {
1960 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1966 if (action === "hide") {
1967 addClass(relatedDoc, "hidden-by-usual-hider");
1968 onEachLazy(toggle.childNodes, adjustToggle(true));
1969 addClass(toggle.parentNode, "collapsed");
1970 } else if (action === "show") {
1971 removeClass(relatedDoc, "hidden-by-usual-hider");
1972 removeClass(toggle.parentNode, "collapsed");
1973 onEachLazy(toggle.childNodes, adjustToggle(false));
1977 // we are collapsing the impl block
1979 var parentElem = toggle.parentNode;
1980 relatedDoc = parentElem;
1981 var docblock = relatedDoc.nextElementSibling;
1983 while (hasClass(relatedDoc, "impl-items") === false) {
1984 relatedDoc = relatedDoc.nextElementSibling;
1987 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
1988 (pageId && document.getElementById(pageId))) {
1992 // Hide all functions, but not associated types/consts
1994 if (mode === "toggle") {
1995 if (hasClass(relatedDoc, "fns-now-collapsed") ||
1996 hasClass(docblock, "hidden-by-impl-hider")) {
2003 if (action === "show") {
2004 removeClass(relatedDoc, "fns-now-collapsed");
2005 removeClass(docblock, "hidden-by-usual-hider");
2006 onEachLazy(toggle.childNodes, adjustToggle(false));
2007 onEachLazy(relatedDoc.childNodes, implHider(false));
2008 } else if (action === "hide") {
2009 addClass(relatedDoc, "fns-now-collapsed");
2010 addClass(docblock, "hidden-by-usual-hider");
2011 onEachLazy(toggle.childNodes, adjustToggle(true));
2012 onEachLazy(relatedDoc.childNodes, implHider(true));
2017 function collapser(e, collapse) {
2018 // inherent impl ids are like "impl" or impl-<number>'.
2019 // they will never be hidden by default.
2020 var n = e.parentElement;
2021 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2022 // Automatically minimize all non-inherent impls
2023 if (collapse || hasClass(n, "impl")) {
2024 collapseDocs(e, "hide", pageId);
2029 function autoCollapse(pageId, collapse) {
2031 toggleAllDocs(pageId, true);
2032 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2033 var impl_list = document.getElementById("implementations-list");
2035 if (impl_list !== null) {
2036 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2037 collapser(e, collapse);
2043 var toggles = document.getElementById("toggle-all-docs");
2045 toggles.onclick = toggleAllDocs;
2048 function insertAfter(newNode, referenceNode) {
2049 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2052 function createSimpleToggle(sectionIsCollapsed) {
2053 var toggle = document.createElement("a");
2054 toggle.href = "javascript:void(0)";
2055 toggle.className = "collapse-toggle";
2056 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2061 var toggle = createSimpleToggle(false);
2063 var func = function(e) {
2064 var next = e.nextElementSibling;
2068 if (hasClass(next, "docblock") ||
2069 (hasClass(next, "stability") &&
2070 hasClass(next.nextElementSibling, "docblock"))) {
2071 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2075 var funcImpl = function(e) {
2076 var next = e.nextElementSibling;
2077 if (next && hasClass(next, "docblock")) {
2078 next = next.nextElementSibling;
2083 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2084 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2088 onEachLazy(document.getElementsByClassName("method"), func);
2089 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2090 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2091 var impl_call = function() {};
2092 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2093 impl_call = function(e, newToggle, pageId) {
2094 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2095 // Automatically minimize all non-inherent impls
2096 if (hasClass(e, "impl")) {
2097 collapseDocs(newToggle, "hide", pageId);
2102 var pageId = getPageId();
2103 var newToggle = document.createElement("a");
2104 newToggle.href = "javascript:void(0)";
2105 newToggle.className = "collapse-toggle hidden-default collapsed";
2106 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2107 "</span>] Show hidden undocumented items";
2108 function toggleClicked() {
2109 if (hasClass(this, "collapsed")) {
2110 removeClass(this, "collapsed");
2111 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2112 if (hasClass(x, "content") === false) {
2113 removeClass(x, "hidden");
2117 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2118 "</span>] Hide undocumented items";
2120 addClass(this, "collapsed");
2121 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2122 if (hasClass(x, "content") === false) {
2123 addClass(x, "hidden");
2124 removeClass(x, "x");
2127 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2128 "</span>] Show hidden undocumented items";
2131 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2132 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2133 var hiddenElems = e.getElementsByClassName("hidden");
2134 var needToggle = false;
2136 var hlength = hiddenElems.length;
2137 for (var i = 0; i < hlength; ++i) {
2138 if (hasClass(hiddenElems[i], "content") === false &&
2139 hasClass(hiddenElems[i], "docblock") === false) {
2144 if (needToggle === true) {
2145 var inner_toggle = newToggle.cloneNode(true);
2146 inner_toggle.onclick = toggleClicked;
2147 e.insertBefore(inner_toggle, e.firstChild);
2148 impl_call(e, inner_toggle, pageId);
2152 function createToggle(otherMessage, fontSize, extraClass, show) {
2153 var span = document.createElement("span");
2154 span.className = "toggle-label";
2156 span.style.display = "none";
2158 if (!otherMessage) {
2159 span.innerHTML = " Expand description";
2161 span.innerHTML = otherMessage;
2165 span.style.fontSize = fontSize;
2168 var mainToggle = toggle.cloneNode(true);
2169 mainToggle.appendChild(span);
2171 var wrapper = document.createElement("div");
2172 wrapper.className = "toggle-wrapper";
2174 addClass(wrapper, "collapsed");
2175 var inner = mainToggle.getElementsByClassName("inner");
2176 if (inner && inner.length > 0) {
2177 inner[0].innerHTML = "+";
2181 addClass(wrapper, extraClass);
2183 wrapper.appendChild(mainToggle);
2187 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2188 function buildToggleWrapper(e) {
2189 if (hasClass(e, "autohide")) {
2190 var wrap = e.previousElementSibling;
2191 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2192 var inner_toggle = wrap.childNodes[0];
2193 var extra = e.childNodes[0].tagName === "H3";
2195 e.style.display = "none";
2196 addClass(wrap, "collapsed");
2197 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2198 e.innerHTML = labelForToggleButton(true);
2200 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2201 e.style.display = "inline-block";
2202 if (extra === true) {
2203 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2208 if (e.parentNode.id === "main") {
2209 var otherMessage = "";
2213 if (hasClass(e, "type-decl")) {
2215 otherMessage = " Show declaration";
2216 if (showItemDeclarations === false) {
2217 extraClass = "collapsed";
2219 } else if (hasClass(e, "sub-variant")) {
2220 otherMessage = " Show fields";
2221 } else if (hasClass(e, "non-exhaustive")) {
2222 otherMessage = " This ";
2223 if (hasClass(e, "non-exhaustive-struct")) {
2224 otherMessage += "struct";
2225 } else if (hasClass(e, "non-exhaustive-enum")) {
2226 otherMessage += "enum";
2227 } else if (hasClass(e, "non-exhaustive-type")) {
2228 otherMessage += "type";
2230 otherMessage += " is marked as non-exhaustive";
2231 } else if (hasClass(e.childNodes[0], "impl-items")) {
2232 extraClass = "marg-left";
2235 e.parentNode.insertBefore(
2236 createToggle(otherMessage,
2239 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2241 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2242 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2247 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2248 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2250 // In the search display, allows to switch between tabs.
2251 function printTab(nb) {
2252 if (nb === 0 || nb === 1 || nb === 2) {
2256 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2257 if (nb_copy === 0) {
2258 addClass(elem, "selected");
2260 removeClass(elem, "selected");
2264 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2266 elem.style.display = "";
2268 elem.style.display = "none";
2274 function createToggleWrapper(tog) {
2275 var span = document.createElement("span");
2276 span.className = "toggle-label";
2277 span.style.display = "none";
2278 span.innerHTML = " Expand attributes";
2279 tog.appendChild(span);
2281 var wrapper = document.createElement("div");
2282 wrapper.className = "toggle-wrapper toggle-attributes";
2283 wrapper.appendChild(tog);
2287 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2288 var itemAttributesFunc = function() {};
2289 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2290 itemAttributesFunc = function(x) {
2291 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2294 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2295 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2296 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2297 itemAttributesFunc(i_e);
2300 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2301 var lineNumbersFunc = function() {};
2302 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2303 lineNumbersFunc = function(x) {
2304 var count = x.textContent.split("\n").length;
2306 for (var i = 0; i < count; ++i) {
2309 var node = document.createElement("pre");
2310 addClass(node, "line-number");
2311 node.innerHTML = elems.join("\n");
2312 x.parentNode.insertBefore(node, x);
2315 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2316 if (hasClass(e, "compile_fail")) {
2317 e.addEventListener("mouseover", function(event) {
2318 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2320 e.addEventListener("mouseout", function(event) {
2321 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2323 } else if (hasClass(e, "ignore")) {
2324 e.addEventListener("mouseover", function(event) {
2325 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2327 e.addEventListener("mouseout", function(event) {
2328 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2334 function showModal(content) {
2335 var modal = document.createElement("div");
2336 modal.id = "important";
2337 addClass(modal, "modal");
2338 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2339 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2341 document.getElementsByTagName("body")[0].appendChild(modal);
2342 document.getElementById("modal-close").onclick = hideModal;
2343 modal.onclick = hideModal;
2346 function hideModal() {
2347 var modal = document.getElementById("important");
2349 modal.parentNode.removeChild(modal);
2353 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2354 e.onclick = function() {
2355 showModal(e.lastElementChild.innerHTML);
2359 function putBackSearch(search_input) {
2360 if (search_input.value !== "") {
2361 addClass(main, "hidden");
2362 removeClass(document.getElementById("search"), "hidden");
2363 if (browserSupportsHistoryApi()) {
2364 history.replaceState(search_input.value,
2366 "?search=" + encodeURIComponent(search_input.value));
2372 search_input.onfocus = function() {
2373 putBackSearch(this);
2377 var params = getQueryStringParams();
2378 if (params && params.search) {
2379 addClass(main, "hidden");
2380 var search = document.getElementById("search");
2381 removeClass(search, "hidden");
2382 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2385 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2387 sidebar_menu.onclick = function() {
2388 var sidebar = document.getElementsByClassName("sidebar")[0];
2389 if (hasClass(sidebar, "mobile") === true) {
2397 window.onresize = function() {
2401 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2403 if (window.location.hash && window.location.hash.length > 0) {
2404 expandSection(window.location.hash.replace(/^#/, ""));
2408 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2411 onEachLazy(main.childNodes, function(e) {
2412 // Unhide the actual content once loading is complete. Headers get
2413 // flex treatment for their horizontal layout, divs get block treatment
2414 // for vertical layout (column-oriented flex layout for divs caused
2415 // errors in mobile browsers).
2416 if (e.tagName === "H2" || e.tagName === "H3") {
2417 let nextTagName = e.nextElementSibling.tagName;
2418 if (nextTagName == "H2" || nextTagName == "H3") {
2419 e.nextElementSibling.style.display = "flex";
2421 e.nextElementSibling.style.display = "block";
2427 function addSearchOptions(crates) {
2428 var elem = document.getElementById('crate-search');
2433 var crates_text = [];
2434 if (Object.keys(crates).length > 1) {
2435 for (var crate in crates) {
2436 if (crates.hasOwnProperty(crate)) {
2437 crates_text.push(crate);
2441 crates_text.sort(function(a, b) {
2442 var lower_a = a.toLowerCase();
2443 var lower_b = b.toLowerCase();
2445 if (lower_a < lower_b) {
2447 } else if (lower_a > lower_b) {
2452 for (var i = 0; i < crates_text.length; ++i) {
2453 var option = document.createElement("option");
2454 option.value = crates_text[i];
2455 option.innerText = crates_text[i];
2456 elem.appendChild(option);
2460 window.addSearchOptions = addSearchOptions;
2463 // Sets the focus on the search bar at the top of the page
2464 function focusSearchBar() {
2465 document.getElementsByClassName("search-input")[0].focus();
2468 // Removes the focus from the search bar
2469 function defocusSearchBar() {
2470 document.getElementsByClassName("search-input")[0].blur();