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",
74 var search_input = document.getElementsByClassName("search-input")[0];
76 // On the search screen, so you remain on the last tab you opened.
79 // 1 for "In Parameters"
80 // 2 for "In Return Types"
83 var titleBeforeSearch = document.title;
85 function getPageId() {
86 var id = document.location.href.split("#")[1];
88 return id.split("?")[0].split("&")[0];
93 function showSidebar() {
94 var elems = document.getElementsByClassName("sidebar-elems")[0];
96 addClass(elems, "show-it");
98 var sidebar = document.getElementsByClassName("sidebar")[0];
100 addClass(sidebar, "mobile");
101 var filler = document.getElementById("sidebar-filler");
103 var div = document.createElement("div");
104 div.id = "sidebar-filler";
105 sidebar.appendChild(div);
108 var themePicker = document.getElementsByClassName("theme-picker");
109 if (themePicker && themePicker.length > 0) {
110 themePicker[0].style.display = "none";
114 function hideSidebar() {
115 var elems = document.getElementsByClassName("sidebar-elems")[0];
117 removeClass(elems, "show-it");
119 var sidebar = document.getElementsByClassName("sidebar")[0];
120 removeClass(sidebar, "mobile");
121 var filler = document.getElementById("sidebar-filler");
125 document.getElementsByTagName("body")[0].style.marginTop = "";
126 var themePicker = document.getElementsByClassName("theme-picker");
127 if (themePicker && themePicker.length > 0) {
128 themePicker[0].style.display = null;
132 // used for special search precedence
133 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
134 var TY_KEYWORD = itemTypes.indexOf("keyword");
136 onEachLazy(document.getElementsByClassName("js-only"), function(e) {
137 removeClass(e, "js-only");
140 function getQueryStringParams() {
142 window.location.search.substring(1).split("&").
144 var pair = s.split("=");
145 params[decodeURIComponent(pair[0])] =
146 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
151 function browserSupportsHistoryApi() {
152 return window.history && typeof window.history.pushState === "function";
155 var main = document.getElementById("main");
157 function highlightSourceLines(ev) {
158 // If we're in mobile mode, we should add the sidebar in any case.
161 var search = document.getElementById("search");
162 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
164 from = parseInt(match[1], 10);
165 to = Math.min(50000, parseInt(match[2] || match[1], 10));
166 from = Math.min(from, to);
167 elem = document.getElementById(from);
172 var x = document.getElementById(from);
177 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
178 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
179 removeClass(i_e, "line-highlighted");
182 for (i = from; i <= to; ++i) {
183 addClass(document.getElementById(i), "line-highlighted");
185 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
186 addClass(search, "hidden");
187 removeClass(main, "hidden");
188 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
189 if (browserSupportsHistoryApi()) {
190 history.replaceState(hash, "", "?search=#" + hash);
192 elem = document.getElementById(hash);
194 elem.scrollIntoView();
199 function expandSection(id) {
200 var elem = document.getElementById(id);
201 if (elem && isHidden(elem)) {
202 var h3 = elem.parentNode.previousElementSibling;
203 if (h3 && h3.tagName !== "H3") {
204 h3 = h3.previousElementSibling; // skip div.docblock
208 var collapses = h3.getElementsByClassName("collapse-toggle");
209 if (collapses.length > 0) {
210 // The element is not visible, we need to make it appear!
211 collapseDocs(collapses[0], "show");
217 highlightSourceLines(null);
218 window.onhashchange = highlightSourceLines;
220 // Gets the human-readable string for the virtual-key code of the
221 // given KeyboardEvent, ev.
223 // This function is meant as a polyfill for KeyboardEvent#key,
224 // since it is not supported in Trident. We also test for
225 // KeyboardEvent#keyCode because the handleShortcut handler is
226 // also registered for the keydown event, because Blink doesn't fire
227 // keypress on hitting the Escape key.
229 // So I guess you could say things are getting pretty interoperable.
230 function getVirtualKey(ev) {
231 if ("key" in ev && typeof ev.key != "undefined") {
235 var c = ev.charCode || ev.keyCode;
239 return String.fromCharCode(c);
242 function displayHelp(display, ev, help) {
243 if (display === true) {
244 if (hasClass(help, "hidden")) {
246 removeClass(help, "hidden");
247 addClass(document.body, "blur");
249 } else if (hasClass(help, "hidden") === false) {
251 addClass(help, "hidden");
252 removeClass(document.body, "blur");
256 function handleEscape(ev, help) {
258 var search = document.getElementById("search");
259 if (hasClass(help, "hidden") === false) {
260 displayHelp(false, ev, help);
261 } else if (hasClass(search, "hidden") === false) {
263 addClass(search, "hidden");
264 removeClass(main, "hidden");
265 document.title = titleBeforeSearch;
270 function handleShortcut(ev) {
271 // Don't interfere with browser shortcuts
272 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
276 var help = document.getElementById("help");
277 if (document.activeElement.tagName === "INPUT") {
278 switch (getVirtualKey(ev)) {
280 handleEscape(ev, help);
284 switch (getVirtualKey(ev)) {
286 handleEscape(ev, help);
291 displayHelp(false, ev, help);
306 displayHelp(true, ev, help);
313 function findParentElement(elem, tagName) {
315 if (elem && elem.tagName === tagName) {
318 elem = elem.parentNode;
323 document.onkeypress = handleShortcut;
324 document.onkeydown = handleShortcut;
325 document.onclick = function(ev) {
326 if (hasClass(ev.target, "collapse-toggle")) {
327 collapseDocs(ev.target, "toggle");
328 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
329 collapseDocs(ev.target.parentNode, "toggle");
330 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
333 var set_fragment = function(name) {
334 if (browserSupportsHistoryApi()) {
335 history.replaceState(null, null, "#" + name);
338 location.replace("#" + name);
342 var cur_id = parseInt(ev.target.id, 10);
344 if (ev.shiftKey && prev_id) {
345 if (prev_id > cur_id) {
351 set_fragment(prev_id + "-" + cur_id);
355 set_fragment(cur_id);
357 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
358 addClass(document.getElementById("help"), "hidden");
359 removeClass(document.body, "blur");
361 // Making a collapsed element visible on onhashchange seems
363 var a = findParentElement(ev.target, "A");
365 expandSection(a.hash.replace(/^#/, ""));
370 var x = document.getElementsByClassName("version-selector");
372 x[0].onchange = function() {
374 url = document.location.href,
376 len = rootPath.match(/\.\.\//g).length + 1;
378 for (i = 0; i < len; ++i) {
379 match = url.match(/\/[^\/]*$/);
381 stripped = match[0] + stripped;
383 url = url.substring(0, url.length - match[0].length);
386 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
388 document.location.href = url;
393 * A function to compute the Levenshtein distance between two strings
394 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
395 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
396 * This code is an unmodified version of the code written by Marco de Wit
397 * and was found at http://stackoverflow.com/a/18514751/745719
399 var levenshtein_row2 = [];
400 function levenshtein(s1, s2) {
404 var s1_len = s1.length, s2_len = s2.length;
405 if (s1_len && s2_len) {
406 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
407 while (i1 < s1_len) {
410 while (i2 < s2_len) {
411 c2 = s2.charCodeAt(i2);
415 for (i1 = 0; i1 < s1_len; ++i1) {
416 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
418 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
424 return s1_len + s2_len;
427 function initSearch(rawSearchIndex) {
428 var currentResults, index, searchIndex;
429 var MAX_LEV_DISTANCE = 3;
430 var MAX_RESULTS = 200;
431 var GENERICS_DATA = 1;
435 var params = getQueryStringParams();
437 // Populate search bar with query string search term when provided,
438 // but only if the input bar is empty. This avoid the obnoxious issue
439 // where you start trying to do a search, and the index loads, and
440 // suddenly your search is gone!
441 if (search_input.value === "") {
442 search_input.value = params.search || "";
446 * Executes the query and builds an index of results
447 * @param {[Object]} query [The user query]
448 * @param {[type]} searchWords [The list of search words to query
450 * @param {[type]} filterCrates [Crate to search in if defined]
451 * @return {[type]} [A search index of results]
453 function execQuery(query, searchWords, filterCrates) {
454 function itemTypeFromName(typename) {
455 var length = itemTypes.length;
456 for (var i = 0; i < length; ++i) {
457 if (itemTypes[i] === typename) {
464 var valLower = query.query.toLowerCase(),
466 typeFilter = itemTypeFromName(query.type),
467 results = {}, results_in_args = {}, results_returned = {},
468 split = valLower.split("::");
470 var length = split.length;
471 for (var z = 0; z < length; ++z) {
472 if (split[z] === "") {
478 function transformResults(results, isType) {
480 var length = results.length;
481 for (var i = 0; i < length; ++i) {
482 if (results[i].id > -1) {
483 var obj = searchIndex[results[i].id];
484 obj.lev = results[i].lev;
485 if (isType !== true || obj.type) {
486 var res = buildHrefAndPath(obj);
487 obj.displayPath = pathSplitter(res[0]);
488 obj.fullPath = obj.displayPath + obj.name;
489 // To be sure than it some items aren't considered as duplicate.
490 obj.fullPath += "|" + obj.ty;
493 if (out.length >= MAX_RESULTS) {
502 function sortResults(results, isType) {
504 for (var entry in results) {
505 if (results.hasOwnProperty(entry)) {
506 ar.push(results[entry]);
511 var nresults = results.length;
512 for (i = 0; i < nresults; ++i) {
513 results[i].word = searchWords[results[i].id];
514 results[i].item = searchIndex[results[i].id] || {};
516 // if there are no results then return to default and fail
517 if (results.length === 0) {
521 results.sort(function(aaa, bbb) {
524 // Sort by non levenshtein results and then levenshtein results by the distance
525 // (less changes required to match means higher rankings)
528 if (a !== b) { return a - b; }
530 // sort by crate (non-current crate goes later)
531 a = (aaa.item.crate !== window.currentCrate);
532 b = (bbb.item.crate !== window.currentCrate);
533 if (a !== b) { return a - b; }
535 // sort by exact match (mismatch goes later)
536 a = (aaa.word !== valLower);
537 b = (bbb.word !== valLower);
538 if (a !== b) { return a - b; }
540 // sort by item name length (longer goes later)
543 if (a !== b) { return a - b; }
545 // sort by item name (lexicographically larger goes later)
548 if (a !== b) { return (a > b ? +1 : -1); }
550 // sort by index of keyword in item name (no literal occurrence goes later)
553 if (a !== b) { return a - b; }
554 // (later literal occurrence, if any, goes later)
557 if (a !== b) { return a - b; }
559 // special precedence for primitive and keyword pages
560 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
561 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
564 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
565 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
569 // sort by description (no description goes later)
570 a = (aaa.item.desc === "");
571 b = (bbb.item.desc === "");
572 if (a !== b) { return a - b; }
574 // sort by type (later occurrence in `itemTypes` goes later)
577 if (a !== b) { return a - b; }
579 // sort by path (lexicographically larger goes later)
582 if (a !== b) { return (a > b ? +1 : -1); }
588 var length = results.length;
589 for (i = 0; i < length; ++i) {
590 var result = results[i];
592 // this validation does not make sense when searching by types
593 if (result.dontValidate) {
596 var name = result.item.name.toLowerCase(),
597 path = result.item.path.toLowerCase(),
598 parent = result.item.parent;
600 if (isType !== true &&
601 validateResult(name, path, split, parent) === false)
606 return transformResults(results);
609 function extractGenerics(val) {
610 val = val.toLowerCase();
611 if (val.indexOf("<") !== -1) {
612 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
614 name: val.substring(0, val.indexOf("<")),
615 generics: values.split(/\s*,\s*/),
624 function checkGenerics(obj, val) {
625 // The names match, but we need to be sure that all generics kinda
627 var lev_distance = MAX_LEV_DISTANCE + 1;
628 if (val.generics.length > 0) {
629 if (obj.length > GENERICS_DATA &&
630 obj[GENERICS_DATA].length >= val.generics.length) {
631 var elems = obj[GENERICS_DATA].slice(0);
634 // We need to find the type that matches the most to remove it in order
636 var vlength = val.generics.length;
637 for (var y = 0; y < vlength; ++y) {
638 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
639 var elength = elems.length;
640 for (var x = 0; x < elength; ++x) {
641 var tmp_lev = levenshtein(elems[x], val.generics[y]);
642 if (tmp_lev < lev.lev) {
647 if (lev.pos !== -1) {
648 elems.splice(lev.pos, 1);
649 lev_distance = Math.min(lev.lev, lev_distance);
653 return MAX_LEV_DISTANCE + 1;
656 return Math.ceil(total / done);
659 return MAX_LEV_DISTANCE + 1;
662 // Check for type name and type generics (if any).
663 function checkType(obj, val, literalSearch) {
664 var lev_distance = MAX_LEV_DISTANCE + 1;
666 if (obj[NAME] === val.name) {
667 if (literalSearch === true) {
668 if (val.generics && val.generics.length !== 0) {
669 if (obj.length > GENERICS_DATA &&
670 obj[GENERICS_DATA].length >= val.generics.length) {
671 var elems = obj[GENERICS_DATA].slice(0);
674 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
676 for (x = 0; allFound === false && x < elems.length; ++x) {
677 allFound = elems[x] === val.generics[y];
679 if (allFound === true) {
680 elems.splice(x - 1, 1);
683 if (allFound === true) {
692 // If the type has generics but don't match, then it won't return at this point.
693 // Otherwise, `checkGenerics` will return 0 and it'll return.
694 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
695 var tmp_lev = checkGenerics(obj, val);
696 if (tmp_lev <= MAX_LEV_DISTANCE) {
703 // Names didn't match so let's check if one of the generic types could.
704 if (literalSearch === true) {
705 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
706 var length = obj[GENERICS_DATA].length;
707 for (x = 0; x < length; ++x) {
708 if (obj[GENERICS_DATA][x] === val.name) {
715 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
716 if (lev_distance <= MAX_LEV_DISTANCE) {
717 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
718 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
719 // We can check if the type we're looking for is inside the generics!
720 var olength = obj[GENERICS_DATA].length;
721 for (x = 0; x < olength; ++x) {
722 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
726 // Now whatever happens, the returned distance is "less good" so we should mark it
727 // as such, and so we add 1 to the distance to make it "less good".
728 return lev_distance + 1;
731 function findArg(obj, val, literalSearch) {
732 var lev_distance = MAX_LEV_DISTANCE + 1;
734 if (obj && obj.type && obj.type[INPUTS_DATA] &&
735 obj.type[INPUTS_DATA].length > 0) {
736 var length = obj.type[INPUTS_DATA].length;
737 for (var i = 0; i < length; i++) {
738 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
739 if (literalSearch === true && tmp === true) {
742 lev_distance = Math.min(tmp, lev_distance);
743 if (lev_distance === 0) {
748 return literalSearch === true ? false : lev_distance;
751 function checkReturned(obj, val, literalSearch) {
752 var lev_distance = MAX_LEV_DISTANCE + 1;
754 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
755 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
756 if (literalSearch === true && tmp === true) {
759 lev_distance = Math.min(tmp, lev_distance);
760 if (lev_distance === 0) {
764 return literalSearch === true ? false : lev_distance;
767 function checkPath(contains, lastElem, ty) {
768 if (contains.length === 0) {
771 var ret_lev = MAX_LEV_DISTANCE + 1;
772 var path = ty.path.split("::");
774 if (ty.parent && ty.parent.name) {
775 path.push(ty.parent.name.toLowerCase());
778 var length = path.length;
779 var clength = contains.length;
780 if (clength > length) {
781 return MAX_LEV_DISTANCE + 1;
783 for (var i = 0; i < length; ++i) {
784 if (i + clength > length) {
789 for (var x = 0; x < clength; ++x) {
790 var lev = levenshtein(path[i + x], contains[x]);
791 if (lev > MAX_LEV_DISTANCE) {
797 if (aborted === false) {
798 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
804 function typePassesFilter(filter, type) {
806 if (filter < 0) return true;
809 if (filter === type) return true;
811 // Match related items
812 var name = itemTypes[type];
813 switch (itemTypes[filter]) {
815 return (name == "associatedconstant");
817 return (name == "method" || name == "tymethod");
819 return (name == "primitive" || name == "keyword");
826 function generateId(ty) {
827 if (ty.parent && ty.parent.name) {
828 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
830 return itemTypes[ty.ty] + ty.path + ty.name;
833 // quoted values mean literal search
834 var nSearchWords = searchWords.length;
840 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
841 val.charAt(val.length - 1) === val.charAt(0))
843 val = extractGenerics(val.substr(1, val.length - 2));
844 for (i = 0; i < nSearchWords; ++i) {
845 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
848 in_args = findArg(searchIndex[i], val, true);
849 returned = checkReturned(searchIndex[i], val, true);
851 fullId = generateId(ty);
853 if (searchWords[i] === val.name) {
854 // filter type: ... queries
855 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
856 results[fullId] === undefined)
858 results[fullId] = {id: i, index: -1};
860 } else if ((in_args === true || returned === true) &&
861 typePassesFilter(typeFilter, searchIndex[i].ty)) {
862 if (in_args === true || returned === true) {
863 if (in_args === true) {
864 results_in_args[fullId] = {
870 if (returned === true) {
871 results_returned[fullId] = {
886 query.inputs = [val];
890 } else if (val.search("->") > -1) {
891 var trimmer = function(s) { return s.trim(); };
892 var parts = val.split("->").map(trimmer);
893 var input = parts[0];
894 // sort inputs so that order does not matter
895 var inputs = input.split(",").map(trimmer).sort();
896 for (i = 0; i < inputs.length; ++i) {
897 inputs[i] = extractGenerics(inputs[i]);
899 var output = extractGenerics(parts[1]);
901 for (i = 0; i < nSearchWords; ++i) {
902 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
905 var type = searchIndex[i].type;
910 fullId = generateId(ty);
912 // allow searching for void (no output) functions as well
913 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
914 returned = checkReturned(ty, output, true);
915 if (output.name === "*" || returned === true) {
923 for (var it = 0; allFound === true && it < inputs.length; it++) {
924 allFound = checkType(type, inputs[it], true);
928 if (in_args === true) {
929 results_in_args[fullId] = {
935 if (returned === true) {
936 results_returned[fullId] = {
942 if (module === true) {
951 query.inputs = inputs.map(function(input) {
954 query.output = output.name;
956 query.inputs = [val];
959 // gather matching search results up to a certain maximum
960 val = val.replace(/\_/g, "");
962 var valGenerics = extractGenerics(val);
964 var paths = valLower.split("::");
966 for (j = 0; j < paths.length; ++j) {
967 if (paths[j] === "") {
972 val = paths[paths.length - 1];
973 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
975 for (j = 0; j < nSearchWords; ++j) {
979 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
984 if (paths.length > 1) {
985 lev = checkPath(contains, paths[paths.length - 1], ty);
986 if (lev > MAX_LEV_DISTANCE) {
988 } else if (lev > 0) {
993 returned = MAX_LEV_DISTANCE + 1;
994 in_args = MAX_LEV_DISTANCE + 1;
996 // we want lev results to go lower than others
997 lev = MAX_LEV_DISTANCE + 1;
998 fullId = generateId(ty);
1000 if (searchWords[j].indexOf(split[i]) > -1 ||
1001 searchWords[j].indexOf(val) > -1 ||
1002 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1004 // filter type: ... queries
1005 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1006 index = searchWords[j].replace(/_/g, "").indexOf(val);
1009 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1010 if (typePassesFilter(typeFilter, ty.ty) === false) {
1011 lev = MAX_LEV_DISTANCE + 1;
1016 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1017 if (typePassesFilter(typeFilter, ty.ty) === false) {
1018 in_args = MAX_LEV_DISTANCE + 1;
1021 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1022 if (typePassesFilter(typeFilter, ty.ty) === false) {
1023 returned = MAX_LEV_DISTANCE + 1;
1028 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1029 if (val.length < 6) {
1035 if (in_args <= MAX_LEV_DISTANCE) {
1036 if (results_in_args[fullId] === undefined) {
1037 results_in_args[fullId] = {
1043 results_in_args[fullId].lev =
1044 Math.min(results_in_args[fullId].lev, in_args);
1046 if (returned <= MAX_LEV_DISTANCE) {
1047 if (results_returned[fullId] === undefined) {
1048 results_returned[fullId] = {
1054 results_returned[fullId].lev =
1055 Math.min(results_returned[fullId].lev, returned);
1057 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1058 if (index !== -1 && paths.length < 2) {
1061 if (results[fullId] === undefined) {
1068 results[fullId].lev = Math.min(results[fullId].lev, lev);
1074 "in_args": sortResults(results_in_args, true),
1075 "returned": sortResults(results_returned, true),
1076 "others": sortResults(results),
1078 if (ALIASES && ALIASES[window.currentCrate] &&
1079 ALIASES[window.currentCrate][query.raw]) {
1080 var aliases = ALIASES[window.currentCrate][query.raw];
1081 for (i = 0; i < aliases.length; ++i) {
1082 aliases[i].is_alias = true;
1083 aliases[i].alias = query.raw;
1084 aliases[i].path = aliases[i].p;
1085 var res = buildHrefAndPath(aliases[i]);
1086 aliases[i].displayPath = pathSplitter(res[0]);
1087 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1088 aliases[i].href = res[1];
1089 ret.others.unshift(aliases[i]);
1090 if (ret.others.length > MAX_RESULTS) {
1099 * Validate performs the following boolean logic. For example:
1100 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1101 * exists in (name || path || parent) OR => ("file" && "open") exists in
1104 * This could be written functionally, but I wanted to minimise
1105 * functions on stack.
1107 * @param {[string]} name [The name of the result]
1108 * @param {[string]} path [The path of the result]
1109 * @param {[string]} keys [The keys to be used (["file", "open"])]
1110 * @param {[object]} parent [The parent of the result]
1111 * @return {[boolean]} [Whether the result is valid or not]
1113 function validateResult(name, path, keys, parent) {
1114 for (var i = 0; i < keys.length; ++i) {
1115 // each check is for validation so we negate the conditions and invalidate
1117 // check for an exact name match
1118 name.indexOf(keys[i]) > -1 ||
1119 // then an exact path match
1120 path.indexOf(keys[i]) > -1 ||
1121 // next if there is a parent, check for exact parent match
1122 (parent !== undefined &&
1123 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1124 // lastly check to see if the name was a levenshtein match
1125 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1132 function getQuery(raw) {
1133 var matches, type, query;
1136 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1138 type = matches[1].replace(/^const$/, "constant");
1139 query = query.substring(matches[0].length);
1150 function initSearchNav() {
1153 var click_func = function(e) {
1155 // to retrieve the real "owner" of the event.
1156 while (el.tagName !== "TR") {
1159 var dst = e.target.getElementsByTagName("a");
1160 if (dst.length < 1) {
1164 if (window.location.pathname === dst.pathname) {
1165 addClass(document.getElementById("search"), "hidden");
1166 removeClass(main, "hidden");
1167 document.location.href = dst.href;
1170 var mouseover_func = function(e) {
1172 // to retrieve the real "owner" of the event.
1173 while (el.tagName !== "TR") {
1176 clearTimeout(hoverTimeout);
1177 hoverTimeout = setTimeout(function() {
1178 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1179 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1180 removeClass(i_e, "highlighted");
1183 addClass(el, "highlighted");
1186 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1187 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1188 i_e.onclick = click_func;
1189 i_e.onmouseover = mouseover_func;
1193 search_input.onkeydown = function(e) {
1194 // "actives" references the currently highlighted item in each search tab.
1195 // Each array in "actives" represents a tab.
1196 var actives = [[], [], []];
1197 // "current" is used to know which tab we're looking into.
1199 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1200 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1201 actives[current].push(e);
1206 if (e.which === 38) { // up
1207 if (!actives[currentTab].length ||
1208 !actives[currentTab][0].previousElementSibling) {
1212 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1213 removeClass(actives[currentTab][0], "highlighted");
1214 } else if (e.which === 40) { // down
1215 if (!actives[currentTab].length) {
1216 var results = document.getElementsByClassName("search-results");
1217 if (results.length > 0) {
1218 var res = results[currentTab].getElementsByClassName("result");
1219 if (res.length > 0) {
1220 addClass(res[0], "highlighted");
1223 } else if (actives[currentTab][0].nextElementSibling) {
1224 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1225 removeClass(actives[currentTab][0], "highlighted");
1227 } else if (e.which === 13) { // return
1228 if (actives[currentTab].length) {
1229 document.location.href =
1230 actives[currentTab][0].getElementsByTagName("a")[0].href;
1232 } else if (e.which === 9) { // tab
1234 printTab(currentTab > 0 ? currentTab - 1 : 2);
1236 printTab(currentTab > 1 ? 0 : currentTab + 1);
1239 } else if (e.which === 16) { // shift
1240 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1241 } else if (e.which === 27) { // escape
1242 removeClass(actives[currentTab][0], "highlighted");
1243 search_input.value = "";
1245 } else if (actives[currentTab].length > 0) {
1246 removeClass(actives[currentTab][0], "highlighted");
1251 function buildHrefAndPath(item) {
1254 var type = itemTypes[item.ty];
1255 var name = item.name;
1257 if (type === "mod") {
1258 displayPath = item.path + "::";
1259 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1260 name + "/index.html";
1261 } else if (type === "primitive" || type === "keyword") {
1263 href = rootPath + item.path.replace(/::/g, "/") +
1264 "/" + type + "." + name + ".html";
1265 } else if (type === "externcrate") {
1267 href = rootPath + name + "/index.html";
1268 } else if (item.parent !== undefined) {
1269 var myparent = item.parent;
1270 var anchor = "#" + type + "." + name;
1271 var parentType = itemTypes[myparent.ty];
1272 if (parentType === "primitive") {
1273 displayPath = myparent.name + "::";
1275 displayPath = item.path + "::" + myparent.name + "::";
1277 href = rootPath + item.path.replace(/::/g, "/") +
1279 "." + myparent.name +
1282 displayPath = item.path + "::";
1283 href = rootPath + item.path.replace(/::/g, "/") +
1284 "/" + type + "." + name + ".html";
1286 return [displayPath, href];
1289 function escape(content) {
1290 var h1 = document.createElement("h1");
1291 h1.textContent = content;
1292 return h1.innerHTML;
1295 function pathSplitter(path) {
1296 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1297 if (tmp.endsWith("<span>")) {
1298 return tmp.slice(0, tmp.length - 6);
1303 function addTab(array, query, display) {
1304 var extraStyle = "";
1305 if (display === false) {
1306 extraStyle = " style=\"display: none;\"";
1310 var duplicates = {};
1312 if (array.length > 0) {
1313 output = "<table class=\"search-results\"" + extraStyle + ">";
1315 array.forEach(function(item) {
1319 type = itemTypes[item.ty];
1321 if (item.is_alias !== true) {
1322 if (duplicates[item.fullPath]) {
1325 duplicates[item.fullPath] = true;
1329 output += "<tr class=\"" + type + " result\"><td>" +
1330 "<a href=\"" + item.href + "\">" +
1331 (item.is_alias === true ?
1332 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1333 "class=\"grey\"><i> - see </i></span>") : "") +
1334 item.displayPath + "<span class=\"" + type + "\">" +
1335 name + "</span></a></td><td>" +
1336 "<a href=\"" + item.href + "\">" +
1337 "<span class=\"desc\">" + escape(item.desc) +
1338 " </span></a></td></tr>";
1340 output += "</table>";
1342 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1343 "Try on <a href=\"https://duckduckgo.com/?q=" +
1344 encodeURIComponent("rust " + query.query) +
1345 "\">DuckDuckGo</a>?<br/><br/>" +
1346 "Or try looking in one of these:<ul><li>The <a " +
1347 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1348 " for technical details about the language.</li><li><a " +
1349 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1350 "Example</a> for expository code examples.</a></li><li>The <a " +
1351 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1352 "introductions to language features and the language itself.</li><li><a " +
1353 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1354 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1356 return [output, length];
1359 function makeTabHeader(tabNb, text, nbElems) {
1360 if (currentTab === tabNb) {
1361 return "<div class=\"selected\">" + text +
1362 " <div class=\"count\">(" + nbElems + ")</div></div>";
1364 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1367 function showResults(results) {
1368 if (results.others.length === 1 &&
1369 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1370 var elem = document.createElement("a");
1371 elem.href = results.others[0].href;
1372 elem.style.display = "none";
1373 // For firefox, we need the element to be in the DOM so it can be clicked.
1374 document.body.appendChild(elem);
1377 var query = getQuery(search_input.value);
1379 currentResults = query.id;
1381 var ret_others = addTab(results.others, query);
1382 var ret_in_args = addTab(results.in_args, query, false);
1383 var ret_returned = addTab(results.returned, query, false);
1385 var output = "<h1>Results for " + escape(query.query) +
1386 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1387 "<div id=\"titles\">" +
1388 makeTabHeader(0, "In Names", ret_others[1]) +
1389 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1390 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1391 "</div><div id=\"results\">" +
1392 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1394 addClass(main, "hidden");
1395 var search = document.getElementById("search");
1396 removeClass(search, "hidden");
1397 search.innerHTML = output;
1398 var tds = search.getElementsByTagName("td");
1400 if (tds.length > 0) {
1401 td_width = tds[0].offsetWidth;
1403 var width = search.offsetWidth - 40 - td_width;
1404 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1405 e.style.width = width + "px";
1408 var elems = document.getElementById("titles").childNodes;
1409 elems[0].onclick = function() { printTab(0); };
1410 elems[1].onclick = function() { printTab(1); };
1411 elems[2].onclick = function() { printTab(2); };
1412 printTab(currentTab);
1415 function execSearch(query, searchWords, filterCrates) {
1416 function getSmallest(arrays, positions, notDuplicates) {
1419 for (var it = 0; it < positions.length; ++it) {
1420 if (arrays[it].length > positions[it] &&
1421 (start === null || start > arrays[it][positions[it]].lev) &&
1422 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1423 start = arrays[it][positions[it]].lev;
1429 function mergeArrays(arrays) {
1432 var notDuplicates = {};
1434 for (var x = 0; x < arrays.length; ++x) {
1437 while (ret.length < MAX_RESULTS) {
1438 var smallest = getSmallest(arrays, positions, notDuplicates);
1440 if (smallest === null) {
1443 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1444 if (arrays[x].length > positions[x] &&
1445 arrays[x][positions[x]].lev === smallest &&
1446 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1447 ret.push(arrays[x][positions[x]]);
1448 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1456 var queries = query.raw.split(",");
1463 for (var i = 0; i < queries.length; ++i) {
1464 query = queries[i].trim();
1465 if (query.length !== 0) {
1466 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1468 results.in_args.push(tmp.in_args);
1469 results.returned.push(tmp.returned);
1470 results.others.push(tmp.others);
1473 if (queries.length > 1) {
1475 "in_args": mergeArrays(results.in_args),
1476 "returned": mergeArrays(results.returned),
1477 "others": mergeArrays(results.others),
1481 "in_args": results.in_args[0],
1482 "returned": results.returned[0],
1483 "others": results.others[0],
1488 function getFilterCrates() {
1489 var elem = document.getElementById("crate-search");
1491 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1497 function search(e, forced) {
1498 var params = getQueryStringParams();
1499 var query = getQuery(search_input.value.trim());
1505 if (query.query.length === 0) {
1508 if (forced !== true && query.id === currentResults) {
1509 if (query.query.length > 0) {
1510 putBackSearch(search_input);
1515 // Update document title to maintain a meaningful browser history
1516 document.title = "Results for " + query.query + " - Rust";
1518 // Because searching is incremental by character, only the most
1519 // recent search query is added to the browser history.
1520 if (browserSupportsHistoryApi()) {
1521 if (!history.state && !params.search) {
1522 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1524 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1528 var filterCrates = getFilterCrates();
1529 showResults(execSearch(query, index, filterCrates), filterCrates);
1532 function buildIndex(rawSearchIndex) {
1534 var searchWords = [];
1537 for (var crate in rawSearchIndex) {
1538 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1540 searchWords.push(crate);
1543 ty: 1, // == ExternCrate
1546 desc: rawSearchIndex[crate].doc,
1550 // an array of [(Number) item type,
1552 // (String) full path or empty string for previous path,
1553 // (String) description,
1554 // (Number | null) the parent path index to `paths`]
1555 // (Object | null) the type of the function (if any)
1556 var items = rawSearchIndex[crate].i;
1557 // an array of [(Number) item type,
1559 var paths = rawSearchIndex[crate].p;
1561 // convert `paths` into an object form
1562 var len = paths.length;
1563 for (i = 0; i < len; ++i) {
1564 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1567 // convert `items` into an object form, and construct word indices.
1569 // before any analysis is performed lets gather the search terms to
1570 // search against apart from the rest of the data. This is a quick
1571 // operation that is cached for the life of the page state so that
1572 // all other search operations have access to this cached data for
1573 // faster analysis operations
1576 for (i = 0; i < len; ++i) {
1577 var rawRow = items[i];
1578 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1579 path: rawRow[2] || lastPath, desc: rawRow[3],
1580 parent: paths[rawRow[4]], type: rawRow[5]};
1581 searchIndex.push(row);
1582 if (typeof row.name === "string") {
1583 var word = row.name.toLowerCase();
1584 searchWords.push(word);
1586 searchWords.push("");
1588 lastPath = row.path;
1594 function startSearch() {
1596 var callback = function() {
1597 clearTimeout(searchTimeout);
1598 if (search_input.value.length === 0) {
1599 if (browserSupportsHistoryApi()) {
1600 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1602 if (hasClass(main, "content")) {
1603 removeClass(main, "hidden");
1605 var search_c = document.getElementById("search");
1606 if (hasClass(search_c, "content")) {
1607 addClass(search_c, "hidden");
1610 searchTimeout = setTimeout(search, 500);
1613 search_input.onkeyup = callback;
1614 search_input.oninput = callback;
1615 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1617 clearTimeout(searchTimeout);
1620 search_input.onchange = function(e) {
1621 // Do NOT e.preventDefault() here. It will prevent pasting.
1622 clearTimeout(searchTimeout);
1623 // zero-timeout necessary here because at the time of event handler execution the
1624 // pasted content is not in the input field yet. Shouldn’t make any difference for
1626 setTimeout(search, 0);
1628 search_input.onpaste = search_input.onchange;
1630 var selectCrate = document.getElementById('crate-search');
1632 selectCrate.onchange = function() {
1633 search(undefined, true);
1637 // Push and pop states are used to add search results to the browser
1639 if (browserSupportsHistoryApi()) {
1640 // Store the previous <title> so we can revert back to it later.
1641 var previousTitle = document.title;
1643 window.onpopstate = function(e) {
1644 var params = getQueryStringParams();
1645 // When browsing back from search results the main page
1646 // visibility must be reset.
1647 if (!params.search) {
1648 if (hasClass(main, "content")) {
1649 removeClass(main, "hidden");
1651 var search_c = document.getElementById("search");
1652 if (hasClass(search_c, "content")) {
1653 addClass(search_c, "hidden");
1656 // Revert to the previous title manually since the History
1657 // API ignores the title parameter.
1658 document.title = previousTitle;
1659 // When browsing forward to search results the previous
1660 // search will be repeated, so the currentResults are
1661 // cleared to ensure the search is successful.
1662 currentResults = null;
1663 // Synchronize search bar with query string state and
1664 // perform the search. This will empty the bar if there's
1665 // nothing there, which lets you really go back to a
1666 // previous state with nothing in the bar.
1667 if (params.search) {
1668 search_input.value = params.search;
1670 search_input.value = "";
1672 // Some browsers fire "onpopstate" for every page load
1673 // (Chrome), while others fire the event only when actually
1674 // popping a state (Firefox), which is why search() is
1675 // called both here and at the end of the startSearch()
1683 index = buildIndex(rawSearchIndex);
1686 // Draw a convenient sidebar of known crates if we have a listing
1687 if (rootPath === "../" || rootPath === "./") {
1688 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1690 var div = document.createElement("div");
1691 div.className = "block crate";
1692 div.innerHTML = "<h3>Crates</h3>";
1693 var ul = document.createElement("ul");
1694 div.appendChild(ul);
1697 for (var crate in rawSearchIndex) {
1698 if (!rawSearchIndex.hasOwnProperty(crate)) {
1704 for (var i = 0; i < crates.length; ++i) {
1705 var klass = "crate";
1706 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1707 klass += " current";
1709 var link = document.createElement("a");
1710 link.href = rootPath + crates[i] + "/index.html";
1711 link.title = rawSearchIndex[crates[i]].doc;
1712 link.className = klass;
1713 link.textContent = crates[i];
1715 var li = document.createElement("li");
1716 li.appendChild(link);
1719 sidebar.appendChild(div);
1724 window.initSearch = initSearch;
1726 // delayed sidebar rendering.
1727 function initSidebarItems(items) {
1728 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1729 var current = window.sidebarCurrent;
1731 function block(shortty, longty) {
1732 var filtered = items[shortty];
1737 var div = document.createElement("div");
1738 div.className = "block " + shortty;
1739 var h3 = document.createElement("h3");
1740 h3.textContent = longty;
1741 div.appendChild(h3);
1742 var ul = document.createElement("ul");
1744 var length = filtered.length;
1745 for (var i = 0; i < length; ++i) {
1746 var item = filtered[i];
1748 var desc = item[1]; // can be null
1750 var klass = shortty;
1751 if (name === current.name && shortty === current.ty) {
1752 klass += " current";
1755 if (shortty === "mod") {
1756 path = name + "/index.html";
1758 path = shortty + "." + name + ".html";
1760 var link = document.createElement("a");
1761 link.href = current.relpath + path;
1763 link.className = klass;
1764 link.textContent = name;
1765 var li = document.createElement("li");
1766 li.appendChild(link);
1769 div.appendChild(ul);
1771 sidebar.appendChild(div);
1775 block("primitive", "Primitive Types");
1776 block("mod", "Modules");
1777 block("macro", "Macros");
1778 block("struct", "Structs");
1779 block("enum", "Enums");
1780 block("union", "Unions");
1781 block("constant", "Constants");
1782 block("static", "Statics");
1783 block("trait", "Traits");
1784 block("fn", "Functions");
1785 block("type", "Type Definitions");
1786 block("foreigntype", "Foreign Types");
1787 block("keyword", "Keywords");
1788 block("traitalias", "Trait Aliases");
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 var parent = e.parentNode;
1890 var superParent = null;
1893 superParent = parent.parentNode;
1895 if (!parent || !superParent || superParent.id !== "main" ||
1896 hasClass(parent, "impl") === false) {
1897 e.innerHTML = labelForToggleButton(true);
1900 innerToggle.title = "expand all docs";
1901 if (fromAutoCollapse !== true) {
1902 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1903 var parent = e.parentNode;
1904 var superParent = null;
1907 superParent = parent.parentNode;
1909 if (!parent || !superParent || superParent.id !== "main" ||
1910 hasClass(parent, "impl") === false) {
1911 collapseDocs(e, "hide", pageId);
1918 function collapseDocs(toggle, mode, pageId) {
1919 if (!toggle || !toggle.parentNode) {
1923 function adjustToggle(arg) {
1924 return function(e) {
1925 if (hasClass(e, "toggle-label")) {
1927 e.style.display = "inline-block";
1929 e.style.display = "none";
1932 if (hasClass(e, "inner")) {
1933 e.innerHTML = labelForToggleButton(arg);
1938 function implHider(addOrRemove, fullHide) {
1939 return function(n) {
1940 var is_method = hasClass(n, "method") || fullHide;
1941 if (is_method || hasClass(n, "type")) {
1942 if (is_method === true) {
1944 addClass(n, "hidden-by-impl-hider");
1946 removeClass(n, "hidden-by-impl-hider");
1949 var ns = n.nextElementSibling;
1952 hasClass(ns, "docblock") ||
1953 hasClass(ns, "stability"))) {
1955 addClass(ns, "hidden-by-impl-hider");
1957 removeClass(ns, "hidden-by-impl-hider");
1959 ns = ns.nextElementSibling;
1970 if (hasClass(toggle.parentNode, "impl") === false) {
1971 relatedDoc = toggle.parentNode.nextElementSibling;
1972 if (hasClass(relatedDoc, "stability")) {
1973 relatedDoc = relatedDoc.nextElementSibling;
1975 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1976 if (mode === "toggle") {
1977 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1983 if (action === "hide") {
1984 addClass(relatedDoc, "hidden-by-usual-hider");
1985 onEachLazy(toggle.childNodes, adjustToggle(true));
1986 addClass(toggle.parentNode, "collapsed");
1987 } else if (action === "show") {
1988 removeClass(relatedDoc, "hidden-by-usual-hider");
1989 removeClass(toggle.parentNode, "collapsed");
1990 onEachLazy(toggle.childNodes, adjustToggle(false));
1994 // we are collapsing the impl block(s).
1996 var parentElem = toggle.parentNode;
1997 relatedDoc = parentElem;
1998 var docblock = relatedDoc.nextElementSibling;
2000 while (hasClass(relatedDoc, "impl-items") === false) {
2001 relatedDoc = relatedDoc.nextElementSibling;
2004 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2005 (pageId && document.getElementById(pageId))) {
2009 // Hide all functions, but not associated types/consts.
2011 if (mode === "toggle") {
2012 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2013 hasClass(docblock, "hidden-by-impl-hider")) {
2020 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2021 if (action === "show") {
2022 removeClass(relatedDoc, "fns-now-collapsed");
2023 removeClass(docblock, "hidden-by-usual-hider");
2024 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2025 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2026 } else if (action === "hide") {
2027 addClass(relatedDoc, "fns-now-collapsed");
2028 addClass(docblock, "hidden-by-usual-hider");
2029 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2030 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2035 function collapser(e, collapse) {
2036 // inherent impl ids are like "impl" or impl-<number>'.
2037 // they will never be hidden by default.
2038 var n = e.parentElement;
2039 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2040 // Automatically minimize all non-inherent impls
2041 if (collapse || hasClass(n, "impl")) {
2042 collapseDocs(e, "hide", pageId);
2047 function autoCollapse(pageId, collapse) {
2049 toggleAllDocs(pageId, true);
2050 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2051 var impl_list = document.getElementById("implementations-list");
2053 if (impl_list !== null) {
2054 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2055 collapser(e, collapse);
2061 var toggles = document.getElementById("toggle-all-docs");
2063 toggles.onclick = toggleAllDocs;
2066 function insertAfter(newNode, referenceNode) {
2067 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2070 function createSimpleToggle(sectionIsCollapsed) {
2071 var toggle = document.createElement("a");
2072 toggle.href = "javascript:void(0)";
2073 toggle.className = "collapse-toggle";
2074 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2079 var toggle = createSimpleToggle(false);
2081 var func = function(e) {
2082 var next = e.nextElementSibling;
2086 if (hasClass(next, "docblock") ||
2087 (hasClass(next, "stability") &&
2088 hasClass(next.nextElementSibling, "docblock"))) {
2089 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2093 var funcImpl = function(e) {
2094 var next = e.nextElementSibling;
2095 if (next && hasClass(next, "docblock")) {
2096 next = next.nextElementSibling;
2101 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2102 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2106 onEachLazy(document.getElementsByClassName("method"), func);
2107 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2108 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2109 var impl_call = function() {};
2110 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2111 impl_call = function(e, newToggle, pageId) {
2112 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2113 // Automatically minimize all non-inherent impls
2114 if (hasClass(e, "impl")) {
2115 collapseDocs(newToggle, "hide", pageId);
2120 var pageId = getPageId();
2121 var newToggle = document.createElement("a");
2122 newToggle.href = "javascript:void(0)";
2123 newToggle.className = "collapse-toggle hidden-default collapsed";
2124 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2125 "</span>] Show hidden undocumented items";
2126 function toggleClicked() {
2127 if (hasClass(this, "collapsed")) {
2128 removeClass(this, "collapsed");
2129 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2130 if (hasClass(x, "content") === false) {
2131 removeClass(x, "hidden");
2135 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2136 "</span>] Hide undocumented items";
2138 addClass(this, "collapsed");
2139 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2140 if (hasClass(x, "content") === false) {
2141 addClass(x, "hidden");
2142 removeClass(x, "x");
2145 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2146 "</span>] Show hidden undocumented items";
2149 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2150 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2151 var hiddenElems = e.getElementsByClassName("hidden");
2152 var needToggle = false;
2154 var hlength = hiddenElems.length;
2155 for (var i = 0; i < hlength; ++i) {
2156 if (hasClass(hiddenElems[i], "content") === false &&
2157 hasClass(hiddenElems[i], "docblock") === false) {
2162 if (needToggle === true) {
2163 var inner_toggle = newToggle.cloneNode(true);
2164 inner_toggle.onclick = toggleClicked;
2165 e.insertBefore(inner_toggle, e.firstChild);
2166 impl_call(e, inner_toggle, pageId);
2170 function createToggle(otherMessage, fontSize, extraClass, show) {
2171 var span = document.createElement("span");
2172 span.className = "toggle-label";
2174 span.style.display = "none";
2176 if (!otherMessage) {
2177 span.innerHTML = " Expand description";
2179 span.innerHTML = otherMessage;
2183 span.style.fontSize = fontSize;
2186 var mainToggle = toggle.cloneNode(true);
2187 mainToggle.appendChild(span);
2189 var wrapper = document.createElement("div");
2190 wrapper.className = "toggle-wrapper";
2192 addClass(wrapper, "collapsed");
2193 var inner = mainToggle.getElementsByClassName("inner");
2194 if (inner && inner.length > 0) {
2195 inner[0].innerHTML = "+";
2199 addClass(wrapper, extraClass);
2201 wrapper.appendChild(mainToggle);
2205 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2206 function buildToggleWrapper(e) {
2207 if (hasClass(e, "autohide")) {
2208 var wrap = e.previousElementSibling;
2209 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2210 var inner_toggle = wrap.childNodes[0];
2211 var extra = e.childNodes[0].tagName === "H3";
2213 e.style.display = "none";
2214 addClass(wrap, "collapsed");
2215 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2216 e.innerHTML = labelForToggleButton(true);
2218 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2219 e.style.display = "inline-block";
2220 if (extra === true) {
2221 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2226 if (e.parentNode.id === "main") {
2227 var otherMessage = "";
2231 if (hasClass(e, "type-decl")) {
2233 otherMessage = " Show declaration";
2234 if (showItemDeclarations === false) {
2235 extraClass = "collapsed";
2237 } else if (hasClass(e, "sub-variant")) {
2238 otherMessage = " Show fields";
2239 } else if (hasClass(e, "non-exhaustive")) {
2240 otherMessage = " This ";
2241 if (hasClass(e, "non-exhaustive-struct")) {
2242 otherMessage += "struct";
2243 } else if (hasClass(e, "non-exhaustive-enum")) {
2244 otherMessage += "enum";
2245 } else if (hasClass(e, "non-exhaustive-type")) {
2246 otherMessage += "type";
2248 otherMessage += " is marked as non-exhaustive";
2249 } else if (hasClass(e.childNodes[0], "impl-items")) {
2250 extraClass = "marg-left";
2253 e.parentNode.insertBefore(
2254 createToggle(otherMessage,
2257 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2259 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2260 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2265 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2266 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2268 // In the search display, allows to switch between tabs.
2269 function printTab(nb) {
2270 if (nb === 0 || nb === 1 || nb === 2) {
2274 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2275 if (nb_copy === 0) {
2276 addClass(elem, "selected");
2278 removeClass(elem, "selected");
2282 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2284 elem.style.display = "";
2286 elem.style.display = "none";
2292 function createToggleWrapper(tog) {
2293 var span = document.createElement("span");
2294 span.className = "toggle-label";
2295 span.style.display = "none";
2296 span.innerHTML = " Expand attributes";
2297 tog.appendChild(span);
2299 var wrapper = document.createElement("div");
2300 wrapper.className = "toggle-wrapper toggle-attributes";
2301 wrapper.appendChild(tog);
2305 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2306 var itemAttributesFunc = function() {};
2307 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2308 itemAttributesFunc = function(x) {
2309 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2312 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2313 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2314 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2315 itemAttributesFunc(i_e);
2318 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2319 var lineNumbersFunc = function() {};
2320 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2321 lineNumbersFunc = function(x) {
2322 var count = x.textContent.split("\n").length;
2324 for (var i = 0; i < count; ++i) {
2327 var node = document.createElement("pre");
2328 addClass(node, "line-number");
2329 node.innerHTML = elems.join("\n");
2330 x.parentNode.insertBefore(node, x);
2333 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2334 if (hasClass(e, "compile_fail")) {
2335 e.addEventListener("mouseover", function(event) {
2336 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2338 e.addEventListener("mouseout", function(event) {
2339 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2341 } else if (hasClass(e, "ignore")) {
2342 e.addEventListener("mouseover", function(event) {
2343 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2345 e.addEventListener("mouseout", function(event) {
2346 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2352 function showModal(content) {
2353 var modal = document.createElement("div");
2354 modal.id = "important";
2355 addClass(modal, "modal");
2356 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2357 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2359 document.getElementsByTagName("body")[0].appendChild(modal);
2360 document.getElementById("modal-close").onclick = hideModal;
2361 modal.onclick = hideModal;
2364 function hideModal() {
2365 var modal = document.getElementById("important");
2367 modal.parentNode.removeChild(modal);
2371 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2372 e.onclick = function() {
2373 showModal(e.lastElementChild.innerHTML);
2377 function putBackSearch(search_input) {
2378 if (search_input.value !== "") {
2379 addClass(main, "hidden");
2380 removeClass(document.getElementById("search"), "hidden");
2381 if (browserSupportsHistoryApi()) {
2382 history.replaceState(search_input.value,
2384 "?search=" + encodeURIComponent(search_input.value));
2390 search_input.onfocus = function() {
2391 putBackSearch(this);
2395 var params = getQueryStringParams();
2396 if (params && params.search) {
2397 addClass(main, "hidden");
2398 var search = document.getElementById("search");
2399 removeClass(search, "hidden");
2400 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2403 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2405 sidebar_menu.onclick = function() {
2406 var sidebar = document.getElementsByClassName("sidebar")[0];
2407 if (hasClass(sidebar, "mobile") === true) {
2415 window.onresize = function() {
2419 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2421 if (window.location.hash && window.location.hash.length > 0) {
2422 expandSection(window.location.hash.replace(/^#/, ""));
2426 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2429 onEachLazy(main.childNodes, function(e) {
2430 // Unhide the actual content once loading is complete. Headers get
2431 // flex treatment for their horizontal layout, divs get block treatment
2432 // for vertical layout (column-oriented flex layout for divs caused
2433 // errors in mobile browsers).
2434 if (e.tagName === "H2" || e.tagName === "H3") {
2435 var nextTagName = e.nextElementSibling.tagName;
2436 if (nextTagName == "H2" || nextTagName == "H3") {
2437 e.nextElementSibling.style.display = "flex";
2439 e.nextElementSibling.style.display = "block";
2445 function addSearchOptions(crates) {
2446 var elem = document.getElementById('crate-search');
2451 var crates_text = [];
2452 if (Object.keys(crates).length > 1) {
2453 for (var crate in crates) {
2454 if (crates.hasOwnProperty(crate)) {
2455 crates_text.push(crate);
2459 crates_text.sort(function(a, b) {
2460 var lower_a = a.toLowerCase();
2461 var lower_b = b.toLowerCase();
2463 if (lower_a < lower_b) {
2465 } else if (lower_a > lower_b) {
2470 for (var i = 0; i < crates_text.length; ++i) {
2471 var option = document.createElement("option");
2472 option.value = crates_text[i];
2473 option.innerText = crates_text[i];
2474 elem.appendChild(option);
2478 window.addSearchOptions = addSearchOptions;
2481 // Sets the focus on the search bar at the top of the page
2482 function focusSearchBar() {
2483 document.getElementsByClassName("search-input")[0].focus();
2486 // Removes the focus from the search bar
2487 function defocusSearchBar() {
2488 document.getElementsByClassName("search-input")[0].blur();