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 themesWidth = null;
85 var titleBeforeSearch = document.title;
87 function getPageId() {
88 var id = document.location.href.split("#")[1];
90 return id.split("?")[0].split("&")[0];
95 function showSidebar() {
96 var elems = document.getElementsByClassName("sidebar-elems")[0];
98 addClass(elems, "show-it");
100 var sidebar = document.getElementsByClassName("sidebar")[0];
102 addClass(sidebar, "mobile");
103 var filler = document.getElementById("sidebar-filler");
105 var div = document.createElement("div");
106 div.id = "sidebar-filler";
107 sidebar.appendChild(div);
110 var themePicker = document.getElementsByClassName("theme-picker");
111 if (themePicker && themePicker.length > 0) {
112 themePicker[0].style.display = "none";
116 function hideSidebar() {
117 var elems = document.getElementsByClassName("sidebar-elems")[0];
119 removeClass(elems, "show-it");
121 var sidebar = document.getElementsByClassName("sidebar")[0];
122 removeClass(sidebar, "mobile");
123 var filler = document.getElementById("sidebar-filler");
127 document.getElementsByTagName("body")[0].style.marginTop = "";
128 var themePicker = document.getElementsByClassName("theme-picker");
129 if (themePicker && themePicker.length > 0) {
130 themePicker[0].style.display = null;
134 // used for special search precedence
135 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
136 var TY_KEYWORD = itemTypes.indexOf("keyword");
138 onEachLazy(document.getElementsByClassName("js-only"), function(e) {
139 removeClass(e, "js-only");
142 function getQueryStringParams() {
144 window.location.search.substring(1).split("&").
146 var pair = s.split("=");
147 params[decodeURIComponent(pair[0])] =
148 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
153 function browserSupportsHistoryApi() {
154 return 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");
1790 block("traitalias", "Trait Aliases");
1793 window.initSidebarItems = initSidebarItems;
1795 window.register_implementors = function(imp) {
1796 var implementors = document.getElementById("implementors-list");
1797 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1799 var libs = Object.getOwnPropertyNames(imp);
1800 var llength = libs.length;
1801 for (var i = 0; i < llength; ++i) {
1802 if (libs[i] === currentCrate) { continue; }
1803 var structs = imp[libs[i]];
1805 var slength = structs.length;
1807 for (var j = 0; j < slength; ++j) {
1808 var struct = structs[j];
1810 var list = struct.synthetic ? synthetic_implementors : implementors;
1812 if (struct.synthetic) {
1813 var stlength = struct.types.length;
1814 for (var k = 0; k < stlength; k++) {
1815 if (window.inlined_types.has(struct.types[k])) {
1816 continue struct_loop;
1818 window.inlined_types.add(struct.types[k]);
1822 var code = document.createElement("code");
1823 code.innerHTML = struct.text;
1825 var x = code.getElementsByTagName("a");
1826 var xlength = x.length;
1827 for (var it = 0; it < xlength; it++) {
1828 var href = x[it].getAttribute("href");
1829 if (href && href.indexOf("http") !== 0) {
1830 x[it].setAttribute("href", rootPath + href);
1833 var display = document.createElement("h3");
1834 addClass(display, "impl");
1835 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1836 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1837 "</tbody></table></span>";
1838 list.appendChild(display);
1842 if (window.pending_implementors) {
1843 window.register_implementors(window.pending_implementors);
1846 function labelForToggleButton(sectionIsCollapsed) {
1847 if (sectionIsCollapsed) {
1848 // button will expand the section
1851 // button will collapse the section
1852 // note that this text is also set in the HTML template in render.rs
1853 return "\u2212"; // "\u2212" is "−" minus sign
1856 function onEveryMatchingChild(elem, className, func) {
1857 if (elem && className && func) {
1858 var length = elem.childNodes.length;
1859 var nodes = elem.childNodes;
1860 for (var i = 0; i < length; ++i) {
1861 if (hasClass(nodes[i], className)) {
1864 onEveryMatchingChild(nodes[i], className, func);
1870 function toggleAllDocs(pageId, fromAutoCollapse) {
1871 var innerToggle = document.getElementById("toggle-all-docs");
1875 if (hasClass(innerToggle, "will-expand")) {
1876 updateLocalStorage("rustdoc-collapse", "false");
1877 removeClass(innerToggle, "will-expand");
1878 onEveryMatchingChild(innerToggle, "inner", function(e) {
1879 e.innerHTML = labelForToggleButton(false);
1881 innerToggle.title = "collapse all docs";
1882 if (fromAutoCollapse !== true) {
1883 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1884 collapseDocs(e, "show");
1888 updateLocalStorage("rustdoc-collapse", "true");
1889 addClass(innerToggle, "will-expand");
1890 onEveryMatchingChild(innerToggle, "inner", function(e) {
1891 var parent = e.parentNode;
1892 var superParent = null;
1895 superParent = parent.parentNode;
1897 if (!parent || !superParent || superParent.id !== "main" ||
1898 hasClass(parent, "impl") === false) {
1899 e.innerHTML = labelForToggleButton(true);
1902 innerToggle.title = "expand all docs";
1903 if (fromAutoCollapse !== true) {
1904 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1905 var parent = e.parentNode;
1906 var superParent = null;
1909 superParent = parent.parentNode;
1911 if (!parent || !superParent || superParent.id !== "main" ||
1912 hasClass(parent, "impl") === false) {
1913 collapseDocs(e, "hide", pageId);
1920 function collapseDocs(toggle, mode, pageId) {
1921 if (!toggle || !toggle.parentNode) {
1925 function adjustToggle(arg) {
1926 return function(e) {
1927 if (hasClass(e, "toggle-label")) {
1929 e.style.display = "inline-block";
1931 e.style.display = "none";
1934 if (hasClass(e, "inner")) {
1935 e.innerHTML = labelForToggleButton(arg);
1940 function implHider(addOrRemove, fullHide) {
1941 return function(n) {
1942 var is_method = hasClass(n, "method") || fullHide;
1943 if (is_method || hasClass(n, "type")) {
1944 if (is_method === true) {
1946 addClass(n, "hidden-by-impl-hider");
1948 removeClass(n, "hidden-by-impl-hider");
1951 var ns = n.nextElementSibling;
1954 hasClass(ns, "docblock") ||
1955 hasClass(ns, "stability"))) {
1957 addClass(ns, "hidden-by-impl-hider");
1959 removeClass(ns, "hidden-by-impl-hider");
1961 ns = ns.nextElementSibling;
1972 if (hasClass(toggle.parentNode, "impl") === false) {
1973 relatedDoc = toggle.parentNode.nextElementSibling;
1974 if (hasClass(relatedDoc, "stability")) {
1975 relatedDoc = relatedDoc.nextElementSibling;
1977 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1978 if (mode === "toggle") {
1979 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1985 if (action === "hide") {
1986 addClass(relatedDoc, "hidden-by-usual-hider");
1987 onEachLazy(toggle.childNodes, adjustToggle(true));
1988 addClass(toggle.parentNode, "collapsed");
1989 } else if (action === "show") {
1990 removeClass(relatedDoc, "hidden-by-usual-hider");
1991 removeClass(toggle.parentNode, "collapsed");
1992 onEachLazy(toggle.childNodes, adjustToggle(false));
1996 // we are collapsing the impl block(s).
1998 var parentElem = toggle.parentNode;
1999 relatedDoc = parentElem;
2000 var docblock = relatedDoc.nextElementSibling;
2002 while (hasClass(relatedDoc, "impl-items") === false) {
2003 relatedDoc = relatedDoc.nextElementSibling;
2006 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2007 (pageId && document.getElementById(pageId))) {
2011 // Hide all functions, but not associated types/consts.
2013 if (mode === "toggle") {
2014 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2015 hasClass(docblock, "hidden-by-impl-hider")) {
2022 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2023 if (action === "show") {
2024 removeClass(relatedDoc, "fns-now-collapsed");
2025 removeClass(docblock, "hidden-by-usual-hider");
2026 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2027 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2028 } else if (action === "hide") {
2029 addClass(relatedDoc, "fns-now-collapsed");
2030 addClass(docblock, "hidden-by-usual-hider");
2031 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2032 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2037 function collapser(e, collapse) {
2038 // inherent impl ids are like "impl" or impl-<number>'.
2039 // they will never be hidden by default.
2040 var n = e.parentElement;
2041 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2042 // Automatically minimize all non-inherent impls
2043 if (collapse || hasClass(n, "impl")) {
2044 collapseDocs(e, "hide", pageId);
2049 function autoCollapse(pageId, collapse) {
2051 toggleAllDocs(pageId, true);
2052 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2053 var impl_list = document.getElementById("implementations-list");
2055 if (impl_list !== null) {
2056 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2057 collapser(e, collapse);
2063 var toggles = document.getElementById("toggle-all-docs");
2065 toggles.onclick = toggleAllDocs;
2068 function insertAfter(newNode, referenceNode) {
2069 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2072 function createSimpleToggle(sectionIsCollapsed) {
2073 var toggle = document.createElement("a");
2074 toggle.href = "javascript:void(0)";
2075 toggle.className = "collapse-toggle";
2076 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2081 var toggle = createSimpleToggle(false);
2083 var func = function(e) {
2084 var next = e.nextElementSibling;
2088 if (hasClass(next, "docblock") ||
2089 (hasClass(next, "stability") &&
2090 hasClass(next.nextElementSibling, "docblock"))) {
2091 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2095 var funcImpl = function(e) {
2096 var next = e.nextElementSibling;
2097 if (next && hasClass(next, "docblock")) {
2098 next = next.nextElementSibling;
2103 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2104 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2108 onEachLazy(document.getElementsByClassName("method"), func);
2109 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2110 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2111 var impl_call = function() {};
2112 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2113 impl_call = function(e, newToggle, pageId) {
2114 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2115 // Automatically minimize all non-inherent impls
2116 if (hasClass(e, "impl")) {
2117 collapseDocs(newToggle, "hide", pageId);
2122 var pageId = getPageId();
2123 var newToggle = document.createElement("a");
2124 newToggle.href = "javascript:void(0)";
2125 newToggle.className = "collapse-toggle hidden-default collapsed";
2126 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2127 "</span>] Show hidden undocumented items";
2128 function toggleClicked() {
2129 if (hasClass(this, "collapsed")) {
2130 removeClass(this, "collapsed");
2131 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2132 if (hasClass(x, "content") === false) {
2133 removeClass(x, "hidden");
2137 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2138 "</span>] Hide undocumented items";
2140 addClass(this, "collapsed");
2141 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2142 if (hasClass(x, "content") === false) {
2143 addClass(x, "hidden");
2144 removeClass(x, "x");
2147 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2148 "</span>] Show hidden undocumented items";
2151 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2152 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2153 var hiddenElems = e.getElementsByClassName("hidden");
2154 var needToggle = false;
2156 var hlength = hiddenElems.length;
2157 for (var i = 0; i < hlength; ++i) {
2158 if (hasClass(hiddenElems[i], "content") === false &&
2159 hasClass(hiddenElems[i], "docblock") === false) {
2164 if (needToggle === true) {
2165 var inner_toggle = newToggle.cloneNode(true);
2166 inner_toggle.onclick = toggleClicked;
2167 e.insertBefore(inner_toggle, e.firstChild);
2168 impl_call(e, inner_toggle, pageId);
2172 function createToggle(otherMessage, fontSize, extraClass, show) {
2173 var span = document.createElement("span");
2174 span.className = "toggle-label";
2176 span.style.display = "none";
2178 if (!otherMessage) {
2179 span.innerHTML = " Expand description";
2181 span.innerHTML = otherMessage;
2185 span.style.fontSize = fontSize;
2188 var mainToggle = toggle.cloneNode(true);
2189 mainToggle.appendChild(span);
2191 var wrapper = document.createElement("div");
2192 wrapper.className = "toggle-wrapper";
2194 addClass(wrapper, "collapsed");
2195 var inner = mainToggle.getElementsByClassName("inner");
2196 if (inner && inner.length > 0) {
2197 inner[0].innerHTML = "+";
2201 addClass(wrapper, extraClass);
2203 wrapper.appendChild(mainToggle);
2207 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2208 function buildToggleWrapper(e) {
2209 if (hasClass(e, "autohide")) {
2210 var wrap = e.previousElementSibling;
2211 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2212 var inner_toggle = wrap.childNodes[0];
2213 var extra = e.childNodes[0].tagName === "H3";
2215 e.style.display = "none";
2216 addClass(wrap, "collapsed");
2217 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2218 e.innerHTML = labelForToggleButton(true);
2220 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2221 e.style.display = "inline-block";
2222 if (extra === true) {
2223 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2228 if (e.parentNode.id === "main") {
2229 var otherMessage = "";
2233 if (hasClass(e, "type-decl")) {
2235 otherMessage = " Show declaration";
2236 if (showItemDeclarations === false) {
2237 extraClass = "collapsed";
2239 } else if (hasClass(e, "sub-variant")) {
2240 otherMessage = " Show fields";
2241 } else if (hasClass(e, "non-exhaustive")) {
2242 otherMessage = " This ";
2243 if (hasClass(e, "non-exhaustive-struct")) {
2244 otherMessage += "struct";
2245 } else if (hasClass(e, "non-exhaustive-enum")) {
2246 otherMessage += "enum";
2247 } else if (hasClass(e, "non-exhaustive-type")) {
2248 otherMessage += "type";
2250 otherMessage += " is marked as non-exhaustive";
2251 } else if (hasClass(e.childNodes[0], "impl-items")) {
2252 extraClass = "marg-left";
2255 e.parentNode.insertBefore(
2256 createToggle(otherMessage,
2259 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2261 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2262 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2267 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2268 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2270 // In the search display, allows to switch between tabs.
2271 function printTab(nb) {
2272 if (nb === 0 || nb === 1 || nb === 2) {
2276 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2277 if (nb_copy === 0) {
2278 addClass(elem, "selected");
2280 removeClass(elem, "selected");
2284 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2286 elem.style.display = "";
2288 elem.style.display = "none";
2294 function createToggleWrapper(tog) {
2295 var span = document.createElement("span");
2296 span.className = "toggle-label";
2297 span.style.display = "none";
2298 span.innerHTML = " Expand attributes";
2299 tog.appendChild(span);
2301 var wrapper = document.createElement("div");
2302 wrapper.className = "toggle-wrapper toggle-attributes";
2303 wrapper.appendChild(tog);
2307 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2308 var itemAttributesFunc = function() {};
2309 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2310 itemAttributesFunc = function(x) {
2311 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2314 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2315 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2316 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2317 itemAttributesFunc(i_e);
2320 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2321 var lineNumbersFunc = function() {};
2322 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2323 lineNumbersFunc = function(x) {
2324 var count = x.textContent.split("\n").length;
2326 for (var i = 0; i < count; ++i) {
2329 var node = document.createElement("pre");
2330 addClass(node, "line-number");
2331 node.innerHTML = elems.join("\n");
2332 x.parentNode.insertBefore(node, x);
2335 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2336 if (hasClass(e, "compile_fail")) {
2337 e.addEventListener("mouseover", function(event) {
2338 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2340 e.addEventListener("mouseout", function(event) {
2341 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2343 } else if (hasClass(e, "ignore")) {
2344 e.addEventListener("mouseover", function(event) {
2345 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2347 e.addEventListener("mouseout", function(event) {
2348 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2354 function showModal(content) {
2355 var modal = document.createElement("div");
2356 modal.id = "important";
2357 addClass(modal, "modal");
2358 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2359 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2361 document.getElementsByTagName("body")[0].appendChild(modal);
2362 document.getElementById("modal-close").onclick = hideModal;
2363 modal.onclick = hideModal;
2366 function hideModal() {
2367 var modal = document.getElementById("important");
2369 modal.parentNode.removeChild(modal);
2373 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2374 e.onclick = function() {
2375 showModal(e.lastElementChild.innerHTML);
2379 function putBackSearch(search_input) {
2380 if (search_input.value !== "") {
2381 addClass(main, "hidden");
2382 removeClass(document.getElementById("search"), "hidden");
2383 if (browserSupportsHistoryApi()) {
2384 history.replaceState(search_input.value,
2386 "?search=" + encodeURIComponent(search_input.value));
2392 search_input.onfocus = function() {
2393 putBackSearch(this);
2397 var params = getQueryStringParams();
2398 if (params && params.search) {
2399 addClass(main, "hidden");
2400 var search = document.getElementById("search");
2401 removeClass(search, "hidden");
2402 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2405 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2407 sidebar_menu.onclick = function() {
2408 var sidebar = document.getElementsByClassName("sidebar")[0];
2409 if (hasClass(sidebar, "mobile") === true) {
2417 window.onresize = function() {
2421 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2423 if (window.location.hash && window.location.hash.length > 0) {
2424 expandSection(window.location.hash.replace(/^#/, ""));
2428 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2431 onEachLazy(main.childNodes, function(e) {
2432 // Unhide the actual content once loading is complete. Headers get
2433 // flex treatment for their horizontal layout, divs get block treatment
2434 // for vertical layout (column-oriented flex layout for divs caused
2435 // errors in mobile browsers).
2436 if (e.tagName === "H2" || e.tagName === "H3") {
2437 let nextTagName = e.nextElementSibling.tagName;
2438 if (nextTagName == "H2" || nextTagName == "H3") {
2439 e.nextElementSibling.style.display = "flex";
2441 e.nextElementSibling.style.display = "block";
2447 function addSearchOptions(crates) {
2448 var elem = document.getElementById('crate-search');
2453 var crates_text = [];
2454 if (Object.keys(crates).length > 1) {
2455 for (var crate in crates) {
2456 if (crates.hasOwnProperty(crate)) {
2457 crates_text.push(crate);
2461 crates_text.sort(function(a, b) {
2462 var lower_a = a.toLowerCase();
2463 var lower_b = b.toLowerCase();
2465 if (lower_a < lower_b) {
2467 } else if (lower_a > lower_b) {
2472 for (var i = 0; i < crates_text.length; ++i) {
2473 var option = document.createElement("option");
2474 option.value = crates_text[i];
2475 option.innerText = crates_text[i];
2476 elem.appendChild(option);
2480 window.addSearchOptions = addSearchOptions;
2483 // Sets the focus on the search bar at the top of the page
2484 function focusSearchBar() {
2485 document.getElementsByClassName("search-input")[0].focus();
2488 // Removes the focus from the search bar
2489 function defocusSearchBar() {
2490 document.getElementsByClassName("search-input")[0].blur();