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 // The generics didn't match but the name kinda did so we give it
718 // a levenshtein distance value that isn't *this* good so it goes
719 // into the search results but not too high.
720 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
721 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
722 // We can check if the type we're looking for is inside the generics!
723 var olength = obj[GENERICS_DATA].length;
724 for (x = 0; x < olength; ++x) {
725 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
729 // Now whatever happens, the returned distance is "less good" so we should mark it
730 // as such, and so we add 1 to the distance to make it "less good".
731 return lev_distance + 1;
734 function findArg(obj, val, literalSearch) {
735 var lev_distance = MAX_LEV_DISTANCE + 1;
737 if (obj && obj.type && obj.type[INPUTS_DATA] &&
738 obj.type[INPUTS_DATA].length > 0) {
739 var length = obj.type[INPUTS_DATA].length;
740 for (var i = 0; i < length; i++) {
741 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
742 if (literalSearch === true && tmp === true) {
745 lev_distance = Math.min(tmp, lev_distance);
746 if (lev_distance === 0) {
751 return literalSearch === true ? false : lev_distance;
754 function checkReturned(obj, val, literalSearch) {
755 var lev_distance = MAX_LEV_DISTANCE + 1;
757 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
758 var ret = obj.type[OUTPUT_DATA];
759 if (!obj.type[OUTPUT_DATA].length) {
762 for (var x = 0; x < ret.length; ++x) {
764 if (typeof r === "string") {
767 var tmp = checkType(r, val, literalSearch);
768 if (literalSearch === true) {
774 lev_distance = Math.min(tmp, lev_distance);
775 if (lev_distance === 0) {
780 return literalSearch === true ? false : lev_distance;
783 function checkPath(contains, lastElem, ty) {
784 if (contains.length === 0) {
787 var ret_lev = MAX_LEV_DISTANCE + 1;
788 var path = ty.path.split("::");
790 if (ty.parent && ty.parent.name) {
791 path.push(ty.parent.name.toLowerCase());
794 var length = path.length;
795 var clength = contains.length;
796 if (clength > length) {
797 return MAX_LEV_DISTANCE + 1;
799 for (var i = 0; i < length; ++i) {
800 if (i + clength > length) {
805 for (var x = 0; x < clength; ++x) {
806 var lev = levenshtein(path[i + x], contains[x]);
807 if (lev > MAX_LEV_DISTANCE) {
813 if (aborted === false) {
814 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
820 function typePassesFilter(filter, type) {
822 if (filter < 0) return true;
825 if (filter === type) return true;
827 // Match related items
828 var name = itemTypes[type];
829 switch (itemTypes[filter]) {
831 return (name == "associatedconstant");
833 return (name == "method" || name == "tymethod");
835 return (name == "primitive" || name == "keyword");
842 function generateId(ty) {
843 if (ty.parent && ty.parent.name) {
844 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
846 return itemTypes[ty.ty] + ty.path + ty.name;
849 // quoted values mean literal search
850 var nSearchWords = searchWords.length;
856 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
857 val.charAt(val.length - 1) === val.charAt(0))
859 val = extractGenerics(val.substr(1, val.length - 2));
860 for (i = 0; i < nSearchWords; ++i) {
861 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
864 in_args = findArg(searchIndex[i], val, true);
865 returned = checkReturned(searchIndex[i], val, true);
867 fullId = generateId(ty);
869 if (searchWords[i] === val.name) {
870 // filter type: ... queries
871 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
872 results[fullId] === undefined)
874 results[fullId] = {id: i, index: -1};
876 } else if ((in_args === true || returned === true) &&
877 typePassesFilter(typeFilter, searchIndex[i].ty)) {
878 if (in_args === true || returned === true) {
879 if (in_args === true) {
880 results_in_args[fullId] = {
886 if (returned === true) {
887 results_returned[fullId] = {
902 query.inputs = [val];
906 } else if (val.search("->") > -1) {
907 var trimmer = function(s) { return s.trim(); };
908 var parts = val.split("->").map(trimmer);
909 var input = parts[0];
910 // sort inputs so that order does not matter
911 var inputs = input.split(",").map(trimmer).sort();
912 for (i = 0; i < inputs.length; ++i) {
913 inputs[i] = extractGenerics(inputs[i]);
915 var output = extractGenerics(parts[1]);
917 for (i = 0; i < nSearchWords; ++i) {
918 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
921 var type = searchIndex[i].type;
926 fullId = generateId(ty);
928 // allow searching for void (no output) functions as well
929 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
930 returned = checkReturned(ty, output, true);
931 if (output.name === "*" || returned === true) {
933 var is_module = false;
939 for (var it = 0; allFound === true && it < inputs.length; it++) {
940 allFound = checkType(type, inputs[it], true);
944 if (in_args === true) {
945 results_in_args[fullId] = {
951 if (returned === true) {
952 results_returned[fullId] = {
958 if (is_module === true) {
967 query.inputs = inputs.map(function(input) {
970 query.output = output.name;
972 query.inputs = [val];
975 // gather matching search results up to a certain maximum
976 val = val.replace(/\_/g, "");
978 var valGenerics = extractGenerics(val);
980 var paths = valLower.split("::");
982 for (j = 0; j < paths.length; ++j) {
983 if (paths[j] === "") {
988 val = paths[paths.length - 1];
989 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
991 for (j = 0; j < nSearchWords; ++j) {
995 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1000 if (paths.length > 1) {
1001 lev = checkPath(contains, paths[paths.length - 1], ty);
1002 if (lev > MAX_LEV_DISTANCE) {
1004 } else if (lev > 0) {
1009 returned = MAX_LEV_DISTANCE + 1;
1010 in_args = MAX_LEV_DISTANCE + 1;
1012 // we want lev results to go lower than others
1013 lev = MAX_LEV_DISTANCE + 1;
1014 fullId = generateId(ty);
1016 if (searchWords[j].indexOf(split[i]) > -1 ||
1017 searchWords[j].indexOf(val) > -1 ||
1018 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1020 // filter type: ... queries
1021 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1022 index = searchWords[j].replace(/_/g, "").indexOf(val);
1025 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1026 if (typePassesFilter(typeFilter, ty.ty) === false) {
1027 lev = MAX_LEV_DISTANCE + 1;
1032 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1033 if (typePassesFilter(typeFilter, ty.ty) === false) {
1034 in_args = MAX_LEV_DISTANCE + 1;
1037 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1038 if (typePassesFilter(typeFilter, ty.ty) === false) {
1039 returned = MAX_LEV_DISTANCE + 1;
1044 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1045 if (val.length < 6) {
1051 if (in_args <= MAX_LEV_DISTANCE) {
1052 if (results_in_args[fullId] === undefined) {
1053 results_in_args[fullId] = {
1059 results_in_args[fullId].lev =
1060 Math.min(results_in_args[fullId].lev, in_args);
1062 if (returned <= MAX_LEV_DISTANCE) {
1063 if (results_returned[fullId] === undefined) {
1064 results_returned[fullId] = {
1070 results_returned[fullId].lev =
1071 Math.min(results_returned[fullId].lev, returned);
1073 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1074 if (index !== -1 && paths.length < 2) {
1076 } else if (searchWords[j] === val) {
1077 // Small trick to fix when you're looking for a one letter type
1078 // and there are other short named types.
1081 if (results[fullId] === undefined) {
1088 results[fullId].lev = Math.min(results[fullId].lev, lev);
1094 "in_args": sortResults(results_in_args, true),
1095 "returned": sortResults(results_returned, true),
1096 "others": sortResults(results),
1098 if (ALIASES && ALIASES[window.currentCrate] &&
1099 ALIASES[window.currentCrate][query.raw]) {
1100 var aliases = ALIASES[window.currentCrate][query.raw];
1101 for (i = 0; i < aliases.length; ++i) {
1102 aliases[i].is_alias = true;
1103 aliases[i].alias = query.raw;
1104 aliases[i].path = aliases[i].p;
1105 var res = buildHrefAndPath(aliases[i]);
1106 aliases[i].displayPath = pathSplitter(res[0]);
1107 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1108 aliases[i].href = res[1];
1109 ret.others.unshift(aliases[i]);
1110 if (ret.others.length > MAX_RESULTS) {
1119 * Validate performs the following boolean logic. For example:
1120 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1121 * exists in (name || path || parent) OR => ("file" && "open") exists in
1124 * This could be written functionally, but I wanted to minimise
1125 * functions on stack.
1127 * @param {[string]} name [The name of the result]
1128 * @param {[string]} path [The path of the result]
1129 * @param {[string]} keys [The keys to be used (["file", "open"])]
1130 * @param {[object]} parent [The parent of the result]
1131 * @return {[boolean]} [Whether the result is valid or not]
1133 function validateResult(name, path, keys, parent) {
1134 for (var i = 0; i < keys.length; ++i) {
1135 // each check is for validation so we negate the conditions and invalidate
1137 // check for an exact name match
1138 name.indexOf(keys[i]) > -1 ||
1139 // then an exact path match
1140 path.indexOf(keys[i]) > -1 ||
1141 // next if there is a parent, check for exact parent match
1142 (parent !== undefined &&
1143 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1144 // lastly check to see if the name was a levenshtein match
1145 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1152 function getQuery(raw) {
1153 var matches, type, query;
1156 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1158 type = matches[1].replace(/^const$/, "constant");
1159 query = query.substring(matches[0].length);
1170 function initSearchNav() {
1173 var click_func = function(e) {
1175 // to retrieve the real "owner" of the event.
1176 while (el.tagName !== "TR") {
1179 var dst = e.target.getElementsByTagName("a");
1180 if (dst.length < 1) {
1184 if (window.location.pathname === dst.pathname) {
1185 addClass(document.getElementById("search"), "hidden");
1186 removeClass(main, "hidden");
1187 document.location.href = dst.href;
1190 var mouseover_func = function(e) {
1192 // to retrieve the real "owner" of the event.
1193 while (el.tagName !== "TR") {
1196 clearTimeout(hoverTimeout);
1197 hoverTimeout = setTimeout(function() {
1198 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1199 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1200 removeClass(i_e, "highlighted");
1203 addClass(el, "highlighted");
1206 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1207 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1208 i_e.onclick = click_func;
1209 i_e.onmouseover = mouseover_func;
1213 search_input.onkeydown = function(e) {
1214 // "actives" references the currently highlighted item in each search tab.
1215 // Each array in "actives" represents a tab.
1216 var actives = [[], [], []];
1217 // "current" is used to know which tab we're looking into.
1219 onEachLazy(document.getElementById("results").childNodes, function(e) {
1220 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1221 actives[current].push(e);
1226 if (e.which === 38) { // up
1227 if (!actives[currentTab].length ||
1228 !actives[currentTab][0].previousElementSibling) {
1232 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1233 removeClass(actives[currentTab][0], "highlighted");
1234 } else if (e.which === 40) { // down
1235 if (!actives[currentTab].length) {
1236 var results = document.getElementById("results").childNodes;
1237 if (results.length > 0) {
1238 var res = results[currentTab].getElementsByClassName("result");
1239 if (res.length > 0) {
1240 addClass(res[0], "highlighted");
1243 } else if (actives[currentTab][0].nextElementSibling) {
1244 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1245 removeClass(actives[currentTab][0], "highlighted");
1247 } else if (e.which === 13) { // return
1248 if (actives[currentTab].length) {
1249 document.location.href =
1250 actives[currentTab][0].getElementsByTagName("a")[0].href;
1252 } else if (e.which === 9) { // tab
1254 printTab(currentTab > 0 ? currentTab - 1 : 2);
1256 printTab(currentTab > 1 ? 0 : currentTab + 1);
1259 } else if (e.which === 16) { // shift
1260 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1261 } else if (e.which === 27) { // escape
1262 removeClass(actives[currentTab][0], "highlighted");
1263 search_input.value = "";
1265 } else if (actives[currentTab].length > 0) {
1266 removeClass(actives[currentTab][0], "highlighted");
1271 function buildHrefAndPath(item) {
1274 var type = itemTypes[item.ty];
1275 var name = item.name;
1277 if (type === "mod") {
1278 displayPath = item.path + "::";
1279 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1280 name + "/index.html";
1281 } else if (type === "primitive" || type === "keyword") {
1283 href = rootPath + item.path.replace(/::/g, "/") +
1284 "/" + type + "." + name + ".html";
1285 } else if (type === "externcrate") {
1287 href = rootPath + name + "/index.html";
1288 } else if (item.parent !== undefined) {
1289 var myparent = item.parent;
1290 var anchor = "#" + type + "." + name;
1291 var parentType = itemTypes[myparent.ty];
1292 if (parentType === "primitive") {
1293 displayPath = myparent.name + "::";
1295 displayPath = item.path + "::" + myparent.name + "::";
1297 href = rootPath + item.path.replace(/::/g, "/") +
1299 "." + myparent.name +
1302 displayPath = item.path + "::";
1303 href = rootPath + item.path.replace(/::/g, "/") +
1304 "/" + type + "." + name + ".html";
1306 return [displayPath, href];
1309 function escape(content) {
1310 var h1 = document.createElement("h1");
1311 h1.textContent = content;
1312 return h1.innerHTML;
1315 function pathSplitter(path) {
1316 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1317 if (tmp.endsWith("<span>")) {
1318 return tmp.slice(0, tmp.length - 6);
1323 function addTab(array, query, display) {
1324 var extraStyle = "";
1325 if (display === false) {
1326 extraStyle = " style=\"display: none;\"";
1330 var duplicates = {};
1332 if (array.length > 0) {
1333 output = "<table class=\"search-results\"" + extraStyle + ">";
1335 array.forEach(function(item) {
1339 type = itemTypes[item.ty];
1341 if (item.is_alias !== true) {
1342 if (duplicates[item.fullPath]) {
1345 duplicates[item.fullPath] = true;
1349 output += "<tr class=\"" + type + " result\"><td>" +
1350 "<a href=\"" + item.href + "\">" +
1351 (item.is_alias === true ?
1352 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1353 "class=\"grey\"><i> - see </i></span>") : "") +
1354 item.displayPath + "<span class=\"" + type + "\">" +
1355 name + "</span></a></td><td>" +
1356 "<a href=\"" + item.href + "\">" +
1357 "<span class=\"desc\">" + escape(item.desc) +
1358 " </span></a></td></tr>";
1360 output += "</table>";
1362 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1363 "Try on <a href=\"https://duckduckgo.com/?q=" +
1364 encodeURIComponent("rust " + query.query) +
1365 "\">DuckDuckGo</a>?<br/><br/>" +
1366 "Or try looking in one of these:<ul><li>The <a " +
1367 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1368 " for technical details about the language.</li><li><a " +
1369 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1370 "Example</a> for expository code examples.</a></li><li>The <a " +
1371 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1372 "introductions to language features and the language itself.</li><li><a " +
1373 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1374 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1376 return [output, length];
1379 function makeTabHeader(tabNb, text, nbElems) {
1380 if (currentTab === tabNb) {
1381 return "<div class=\"selected\">" + text +
1382 " <div class=\"count\">(" + nbElems + ")</div></div>";
1384 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1387 function showResults(results) {
1388 if (results.others.length === 1 &&
1389 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1390 var elem = document.createElement("a");
1391 elem.href = results.others[0].href;
1392 elem.style.display = "none";
1393 // For firefox, we need the element to be in the DOM so it can be clicked.
1394 document.body.appendChild(elem);
1397 var query = getQuery(search_input.value);
1399 currentResults = query.id;
1401 var ret_others = addTab(results.others, query);
1402 var ret_in_args = addTab(results.in_args, query, false);
1403 var ret_returned = addTab(results.returned, query, false);
1405 var output = "<h1>Results for " + escape(query.query) +
1406 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1407 "<div id=\"titles\">" +
1408 makeTabHeader(0, "In Names", ret_others[1]) +
1409 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1410 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1411 "</div><div id=\"results\">" +
1412 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1414 addClass(main, "hidden");
1415 var search = document.getElementById("search");
1416 removeClass(search, "hidden");
1417 search.innerHTML = output;
1418 var tds = search.getElementsByTagName("td");
1420 if (tds.length > 0) {
1421 td_width = tds[0].offsetWidth;
1423 var width = search.offsetWidth - 40 - td_width;
1424 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1425 e.style.width = width + "px";
1428 var elems = document.getElementById("titles").childNodes;
1429 elems[0].onclick = function() { printTab(0); };
1430 elems[1].onclick = function() { printTab(1); };
1431 elems[2].onclick = function() { printTab(2); };
1432 printTab(currentTab);
1435 function execSearch(query, searchWords, filterCrates) {
1436 function getSmallest(arrays, positions, notDuplicates) {
1439 for (var it = 0; it < positions.length; ++it) {
1440 if (arrays[it].length > positions[it] &&
1441 (start === null || start > arrays[it][positions[it]].lev) &&
1442 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1443 start = arrays[it][positions[it]].lev;
1449 function mergeArrays(arrays) {
1452 var notDuplicates = {};
1454 for (var x = 0; x < arrays.length; ++x) {
1457 while (ret.length < MAX_RESULTS) {
1458 var smallest = getSmallest(arrays, positions, notDuplicates);
1460 if (smallest === null) {
1463 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1464 if (arrays[x].length > positions[x] &&
1465 arrays[x][positions[x]].lev === smallest &&
1466 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1467 ret.push(arrays[x][positions[x]]);
1468 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1476 var queries = query.raw.split(",");
1483 for (var i = 0; i < queries.length; ++i) {
1484 query = queries[i].trim();
1485 if (query.length !== 0) {
1486 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1488 results.in_args.push(tmp.in_args);
1489 results.returned.push(tmp.returned);
1490 results.others.push(tmp.others);
1493 if (queries.length > 1) {
1495 "in_args": mergeArrays(results.in_args),
1496 "returned": mergeArrays(results.returned),
1497 "others": mergeArrays(results.others),
1501 "in_args": results.in_args[0],
1502 "returned": results.returned[0],
1503 "others": results.others[0],
1508 function getFilterCrates() {
1509 var elem = document.getElementById("crate-search");
1511 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1517 function search(e, forced) {
1518 var params = getQueryStringParams();
1519 var query = getQuery(search_input.value.trim());
1525 if (query.query.length === 0) {
1528 if (forced !== true && query.id === currentResults) {
1529 if (query.query.length > 0) {
1530 putBackSearch(search_input);
1535 // Update document title to maintain a meaningful browser history
1536 document.title = "Results for " + query.query + " - Rust";
1538 // Because searching is incremental by character, only the most
1539 // recent search query is added to the browser history.
1540 if (browserSupportsHistoryApi()) {
1541 if (!history.state && !params.search) {
1542 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1544 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1548 var filterCrates = getFilterCrates();
1549 showResults(execSearch(query, index, filterCrates), filterCrates);
1552 function buildIndex(rawSearchIndex) {
1554 var searchWords = [];
1557 for (var crate in rawSearchIndex) {
1558 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1560 searchWords.push(crate);
1563 ty: 1, // == ExternCrate
1566 desc: rawSearchIndex[crate].doc,
1570 // an array of [(Number) item type,
1572 // (String) full path or empty string for previous path,
1573 // (String) description,
1574 // (Number | null) the parent path index to `paths`]
1575 // (Object | null) the type of the function (if any)
1576 var items = rawSearchIndex[crate].i;
1577 // an array of [(Number) item type,
1579 var paths = rawSearchIndex[crate].p;
1581 // convert `paths` into an object form
1582 var len = paths.length;
1583 for (i = 0; i < len; ++i) {
1584 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1587 // convert `items` into an object form, and construct word indices.
1589 // before any analysis is performed lets gather the search terms to
1590 // search against apart from the rest of the data. This is a quick
1591 // operation that is cached for the life of the page state so that
1592 // all other search operations have access to this cached data for
1593 // faster analysis operations
1596 for (i = 0; i < len; ++i) {
1597 var rawRow = items[i];
1598 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1599 path: rawRow[2] || lastPath, desc: rawRow[3],
1600 parent: paths[rawRow[4]], type: rawRow[5]};
1601 searchIndex.push(row);
1602 if (typeof row.name === "string") {
1603 var word = row.name.toLowerCase();
1604 searchWords.push(word);
1606 searchWords.push("");
1608 lastPath = row.path;
1614 function startSearch() {
1616 var callback = function() {
1617 clearTimeout(searchTimeout);
1618 if (search_input.value.length === 0) {
1619 if (browserSupportsHistoryApi()) {
1620 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1622 if (hasClass(main, "content")) {
1623 removeClass(main, "hidden");
1625 var search_c = document.getElementById("search");
1626 if (hasClass(search_c, "content")) {
1627 addClass(search_c, "hidden");
1630 searchTimeout = setTimeout(search, 500);
1633 search_input.onkeyup = callback;
1634 search_input.oninput = callback;
1635 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1637 clearTimeout(searchTimeout);
1640 search_input.onchange = function(e) {
1641 // Do NOT e.preventDefault() here. It will prevent pasting.
1642 clearTimeout(searchTimeout);
1643 // zero-timeout necessary here because at the time of event handler execution the
1644 // pasted content is not in the input field yet. Shouldn’t make any difference for
1646 setTimeout(search, 0);
1648 search_input.onpaste = search_input.onchange;
1650 var selectCrate = document.getElementById('crate-search');
1652 selectCrate.onchange = function() {
1653 search(undefined, true);
1657 // Push and pop states are used to add search results to the browser
1659 if (browserSupportsHistoryApi()) {
1660 // Store the previous <title> so we can revert back to it later.
1661 var previousTitle = document.title;
1663 window.onpopstate = function(e) {
1664 var params = getQueryStringParams();
1665 // When browsing back from search results the main page
1666 // visibility must be reset.
1667 if (!params.search) {
1668 if (hasClass(main, "content")) {
1669 removeClass(main, "hidden");
1671 var search_c = document.getElementById("search");
1672 if (hasClass(search_c, "content")) {
1673 addClass(search_c, "hidden");
1676 // Revert to the previous title manually since the History
1677 // API ignores the title parameter.
1678 document.title = previousTitle;
1679 // When browsing forward to search results the previous
1680 // search will be repeated, so the currentResults are
1681 // cleared to ensure the search is successful.
1682 currentResults = null;
1683 // Synchronize search bar with query string state and
1684 // perform the search. This will empty the bar if there's
1685 // nothing there, which lets you really go back to a
1686 // previous state with nothing in the bar.
1687 if (params.search) {
1688 search_input.value = params.search;
1690 search_input.value = "";
1692 // Some browsers fire "onpopstate" for every page load
1693 // (Chrome), while others fire the event only when actually
1694 // popping a state (Firefox), which is why search() is
1695 // called both here and at the end of the startSearch()
1703 index = buildIndex(rawSearchIndex);
1706 // Draw a convenient sidebar of known crates if we have a listing
1707 if (rootPath === "../" || rootPath === "./") {
1708 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1710 var div = document.createElement("div");
1711 div.className = "block crate";
1712 div.innerHTML = "<h3>Crates</h3>";
1713 var ul = document.createElement("ul");
1714 div.appendChild(ul);
1717 for (var crate in rawSearchIndex) {
1718 if (!rawSearchIndex.hasOwnProperty(crate)) {
1724 for (var i = 0; i < crates.length; ++i) {
1725 var klass = "crate";
1726 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1727 klass += " current";
1729 var link = document.createElement("a");
1730 link.href = rootPath + crates[i] + "/index.html";
1731 link.title = rawSearchIndex[crates[i]].doc;
1732 link.className = klass;
1733 link.textContent = crates[i];
1735 var li = document.createElement("li");
1736 li.appendChild(link);
1739 sidebar.appendChild(div);
1744 window.initSearch = initSearch;
1746 // delayed sidebar rendering.
1747 function initSidebarItems(items) {
1748 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1749 var current = window.sidebarCurrent;
1751 function block(shortty, longty) {
1752 var filtered = items[shortty];
1757 var div = document.createElement("div");
1758 div.className = "block " + shortty;
1759 var h3 = document.createElement("h3");
1760 h3.textContent = longty;
1761 div.appendChild(h3);
1762 var ul = document.createElement("ul");
1764 var length = filtered.length;
1765 for (var i = 0; i < length; ++i) {
1766 var item = filtered[i];
1768 var desc = item[1]; // can be null
1770 var klass = shortty;
1771 if (name === current.name && shortty === current.ty) {
1772 klass += " current";
1775 if (shortty === "mod") {
1776 path = name + "/index.html";
1778 path = shortty + "." + name + ".html";
1780 var link = document.createElement("a");
1781 link.href = current.relpath + path;
1783 link.className = klass;
1784 link.textContent = name;
1785 var li = document.createElement("li");
1786 li.appendChild(link);
1789 div.appendChild(ul);
1791 sidebar.appendChild(div);
1795 block("primitive", "Primitive Types");
1796 block("mod", "Modules");
1797 block("macro", "Macros");
1798 block("struct", "Structs");
1799 block("enum", "Enums");
1800 block("union", "Unions");
1801 block("constant", "Constants");
1802 block("static", "Statics");
1803 block("trait", "Traits");
1804 block("fn", "Functions");
1805 block("type", "Type Definitions");
1806 block("foreigntype", "Foreign Types");
1807 block("keyword", "Keywords");
1808 block("traitalias", "Trait Aliases");
1811 window.initSidebarItems = initSidebarItems;
1813 window.register_implementors = function(imp) {
1814 var implementors = document.getElementById("implementors-list");
1815 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1817 var libs = Object.getOwnPropertyNames(imp);
1818 var llength = libs.length;
1819 for (var i = 0; i < llength; ++i) {
1820 if (libs[i] === currentCrate) { continue; }
1821 var structs = imp[libs[i]];
1823 var slength = structs.length;
1825 for (var j = 0; j < slength; ++j) {
1826 var struct = structs[j];
1828 var list = struct.synthetic ? synthetic_implementors : implementors;
1830 if (struct.synthetic) {
1831 var stlength = struct.types.length;
1832 for (var k = 0; k < stlength; k++) {
1833 if (window.inlined_types.has(struct.types[k])) {
1834 continue struct_loop;
1836 window.inlined_types.add(struct.types[k]);
1840 var code = document.createElement("code");
1841 code.innerHTML = struct.text;
1843 var x = code.getElementsByTagName("a");
1844 var xlength = x.length;
1845 for (var it = 0; it < xlength; it++) {
1846 var href = x[it].getAttribute("href");
1847 if (href && href.indexOf("http") !== 0) {
1848 x[it].setAttribute("href", rootPath + href);
1851 var display = document.createElement("h3");
1852 addClass(display, "impl");
1853 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1854 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1855 "</tbody></table></span>";
1856 list.appendChild(display);
1860 if (window.pending_implementors) {
1861 window.register_implementors(window.pending_implementors);
1864 function labelForToggleButton(sectionIsCollapsed) {
1865 if (sectionIsCollapsed) {
1866 // button will expand the section
1869 // button will collapse the section
1870 // note that this text is also set in the HTML template in render.rs
1871 return "\u2212"; // "\u2212" is "−" minus sign
1874 function onEveryMatchingChild(elem, className, func) {
1875 if (elem && className && func) {
1876 var length = elem.childNodes.length;
1877 var nodes = elem.childNodes;
1878 for (var i = 0; i < length; ++i) {
1879 if (hasClass(nodes[i], className)) {
1882 onEveryMatchingChild(nodes[i], className, func);
1888 function toggleAllDocs(pageId, fromAutoCollapse) {
1889 var innerToggle = document.getElementById("toggle-all-docs");
1893 if (hasClass(innerToggle, "will-expand")) {
1894 updateLocalStorage("rustdoc-collapse", "false");
1895 removeClass(innerToggle, "will-expand");
1896 onEveryMatchingChild(innerToggle, "inner", function(e) {
1897 e.innerHTML = labelForToggleButton(false);
1899 innerToggle.title = "collapse all docs";
1900 if (fromAutoCollapse !== true) {
1901 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1902 collapseDocs(e, "show");
1906 updateLocalStorage("rustdoc-collapse", "true");
1907 addClass(innerToggle, "will-expand");
1908 onEveryMatchingChild(innerToggle, "inner", function(e) {
1909 var parent = e.parentNode;
1910 var superParent = null;
1913 superParent = parent.parentNode;
1915 if (!parent || !superParent || superParent.id !== "main" ||
1916 hasClass(parent, "impl") === false) {
1917 e.innerHTML = labelForToggleButton(true);
1920 innerToggle.title = "expand all docs";
1921 if (fromAutoCollapse !== true) {
1922 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1923 var parent = e.parentNode;
1924 var superParent = null;
1927 superParent = parent.parentNode;
1929 if (!parent || !superParent || superParent.id !== "main" ||
1930 hasClass(parent, "impl") === false) {
1931 collapseDocs(e, "hide", pageId);
1938 function collapseDocs(toggle, mode, pageId) {
1939 if (!toggle || !toggle.parentNode) {
1943 function adjustToggle(arg) {
1944 return function(e) {
1945 if (hasClass(e, "toggle-label")) {
1947 e.style.display = "inline-block";
1949 e.style.display = "none";
1952 if (hasClass(e, "inner")) {
1953 e.innerHTML = labelForToggleButton(arg);
1958 function implHider(addOrRemove, fullHide) {
1959 return function(n) {
1960 var is_method = hasClass(n, "method") || fullHide;
1961 if (is_method || hasClass(n, "type")) {
1962 if (is_method === true) {
1964 addClass(n, "hidden-by-impl-hider");
1966 removeClass(n, "hidden-by-impl-hider");
1969 var ns = n.nextElementSibling;
1972 hasClass(ns, "docblock") ||
1973 hasClass(ns, "stability"))) {
1975 addClass(ns, "hidden-by-impl-hider");
1977 removeClass(ns, "hidden-by-impl-hider");
1979 ns = ns.nextElementSibling;
1990 if (hasClass(toggle.parentNode, "impl") === false) {
1991 relatedDoc = toggle.parentNode.nextElementSibling;
1992 if (hasClass(relatedDoc, "stability")) {
1993 relatedDoc = relatedDoc.nextElementSibling;
1995 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1996 if (mode === "toggle") {
1997 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2003 if (action === "hide") {
2004 addClass(relatedDoc, "hidden-by-usual-hider");
2005 onEachLazy(toggle.childNodes, adjustToggle(true));
2006 addClass(toggle.parentNode, "collapsed");
2007 } else if (action === "show") {
2008 removeClass(relatedDoc, "hidden-by-usual-hider");
2009 removeClass(toggle.parentNode, "collapsed");
2010 onEachLazy(toggle.childNodes, adjustToggle(false));
2014 // we are collapsing the impl block(s).
2016 var parentElem = toggle.parentNode;
2017 relatedDoc = parentElem;
2018 var docblock = relatedDoc.nextElementSibling;
2020 while (hasClass(relatedDoc, "impl-items") === false) {
2021 relatedDoc = relatedDoc.nextElementSibling;
2024 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2025 (pageId && document.getElementById(pageId))) {
2029 // Hide all functions, but not associated types/consts.
2031 if (mode === "toggle") {
2032 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2033 hasClass(docblock, "hidden-by-impl-hider")) {
2040 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2041 if (action === "show") {
2042 removeClass(relatedDoc, "fns-now-collapsed");
2043 removeClass(docblock, "hidden-by-usual-hider");
2044 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2045 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2046 } else if (action === "hide") {
2047 addClass(relatedDoc, "fns-now-collapsed");
2048 addClass(docblock, "hidden-by-usual-hider");
2049 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2050 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2055 function collapser(e, collapse) {
2056 // inherent impl ids are like "impl" or impl-<number>'.
2057 // they will never be hidden by default.
2058 var n = e.parentElement;
2059 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2060 // Automatically minimize all non-inherent impls
2061 if (collapse || hasClass(n, "impl")) {
2062 collapseDocs(e, "hide", pageId);
2067 function autoCollapse(pageId, collapse) {
2069 toggleAllDocs(pageId, true);
2070 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2071 var impl_list = document.getElementById("implementations-list");
2073 if (impl_list !== null) {
2074 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2075 collapser(e, collapse);
2079 var blanket_list = document.getElementById("blanket-implementations-list");
2081 if (blanket_list !== null) {
2082 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2083 collapser(e, collapse);
2089 var toggles = document.getElementById("toggle-all-docs");
2091 toggles.onclick = toggleAllDocs;
2094 function insertAfter(newNode, referenceNode) {
2095 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2098 function createSimpleToggle(sectionIsCollapsed) {
2099 var toggle = document.createElement("a");
2100 toggle.href = "javascript:void(0)";
2101 toggle.className = "collapse-toggle";
2102 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2107 var toggle = createSimpleToggle(false);
2108 var hideMethodDocs = getCurrentValue("rustdoc-method-docs") === "true";
2109 var pageId = getPageId();
2111 var func = function(e) {
2112 var next = e.nextElementSibling;
2116 if (hasClass(next, "docblock") === true ||
2117 (hasClass(next, "stability") === true &&
2118 hasClass(next.nextElementSibling, "docblock") === true)) {
2119 var newToggle = toggle.cloneNode(true);
2120 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2121 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2122 collapseDocs(newToggle, "hide", pageId);
2127 var funcImpl = function(e) {
2128 var next = e.nextElementSibling;
2129 if (next && hasClass(next, "docblock")) {
2130 next = next.nextElementSibling;
2135 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2136 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2140 onEachLazy(document.getElementsByClassName("method"), func);
2141 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2142 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2143 var impl_call = function() {};
2144 if (hideMethodDocs === true) {
2145 impl_call = function(e, newToggle, pageId) {
2146 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2147 // Automatically minimize all non-inherent impls
2148 if (hasClass(e, "impl") === true) {
2149 collapseDocs(newToggle, "hide", pageId);
2154 var newToggle = document.createElement("a");
2155 newToggle.href = "javascript:void(0)";
2156 newToggle.className = "collapse-toggle hidden-default collapsed";
2157 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2158 "</span>] Show hidden undocumented items";
2159 function toggleClicked() {
2160 if (hasClass(this, "collapsed")) {
2161 removeClass(this, "collapsed");
2162 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2163 if (hasClass(x, "content") === false) {
2164 removeClass(x, "hidden");
2168 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2169 "</span>] Hide undocumented items";
2171 addClass(this, "collapsed");
2172 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2173 if (hasClass(x, "content") === false) {
2174 addClass(x, "hidden");
2175 removeClass(x, "x");
2178 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2179 "</span>] Show hidden undocumented items";
2182 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2183 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2184 var hiddenElems = e.getElementsByClassName("hidden");
2185 var needToggle = false;
2187 var hlength = hiddenElems.length;
2188 for (var i = 0; i < hlength; ++i) {
2189 if (hasClass(hiddenElems[i], "content") === false &&
2190 hasClass(hiddenElems[i], "docblock") === false) {
2195 if (needToggle === true) {
2196 var inner_toggle = newToggle.cloneNode(true);
2197 inner_toggle.onclick = toggleClicked;
2198 e.insertBefore(inner_toggle, e.firstChild);
2199 impl_call(e.previousSibling, inner_toggle, pageId);
2203 function createToggle(otherMessage, fontSize, extraClass, show) {
2204 var span = document.createElement("span");
2205 span.className = "toggle-label";
2207 span.style.display = "none";
2209 if (!otherMessage) {
2210 span.innerHTML = " Expand description";
2212 span.innerHTML = otherMessage;
2216 span.style.fontSize = fontSize;
2219 var mainToggle = toggle.cloneNode(true);
2220 mainToggle.appendChild(span);
2222 var wrapper = document.createElement("div");
2223 wrapper.className = "toggle-wrapper";
2225 addClass(wrapper, "collapsed");
2226 var inner = mainToggle.getElementsByClassName("inner");
2227 if (inner && inner.length > 0) {
2228 inner[0].innerHTML = "+";
2232 addClass(wrapper, extraClass);
2234 wrapper.appendChild(mainToggle);
2238 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2239 function buildToggleWrapper(e) {
2240 if (hasClass(e, "autohide")) {
2241 var wrap = e.previousElementSibling;
2242 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2243 var inner_toggle = wrap.childNodes[0];
2244 var extra = e.childNodes[0].tagName === "H3";
2246 e.style.display = "none";
2247 addClass(wrap, "collapsed");
2248 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2249 e.innerHTML = labelForToggleButton(true);
2251 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2252 e.style.display = "inline-block";
2253 if (extra === true) {
2254 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2259 if (e.parentNode.id === "main") {
2260 var otherMessage = "";
2264 if (hasClass(e, "type-decl")) {
2266 otherMessage = " Show declaration";
2267 if (showItemDeclarations === false) {
2268 extraClass = "collapsed";
2270 } else if (hasClass(e, "sub-variant")) {
2271 otherMessage = " Show fields";
2272 } else if (hasClass(e, "non-exhaustive")) {
2273 otherMessage = " This ";
2274 if (hasClass(e, "non-exhaustive-struct")) {
2275 otherMessage += "struct";
2276 } else if (hasClass(e, "non-exhaustive-enum")) {
2277 otherMessage += "enum";
2278 } else if (hasClass(e, "non-exhaustive-variant")) {
2279 otherMessage += "enum variant";
2280 } else if (hasClass(e, "non-exhaustive-type")) {
2281 otherMessage += "type";
2283 otherMessage += " is marked as non-exhaustive";
2284 } else if (hasClass(e.childNodes[0], "impl-items")) {
2285 extraClass = "marg-left";
2288 e.parentNode.insertBefore(
2289 createToggle(otherMessage,
2292 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2294 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2295 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2297 if (hasClass(e, "non-exhaustive") === true) {
2298 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2303 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2304 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2306 function createToggleWrapper(tog) {
2307 var span = document.createElement("span");
2308 span.className = "toggle-label";
2309 span.style.display = "none";
2310 span.innerHTML = " Expand attributes";
2311 tog.appendChild(span);
2313 var wrapper = document.createElement("div");
2314 wrapper.className = "toggle-wrapper toggle-attributes";
2315 wrapper.appendChild(tog);
2319 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2320 var itemAttributesFunc = function() {};
2321 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2322 itemAttributesFunc = function(x) {
2323 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2326 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2327 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2328 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2329 itemAttributesFunc(i_e);
2332 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2333 var lineNumbersFunc = function() {};
2334 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2335 lineNumbersFunc = function(x) {
2336 var count = x.textContent.split("\n").length;
2338 for (var i = 0; i < count; ++i) {
2341 var node = document.createElement("pre");
2342 addClass(node, "line-number");
2343 node.innerHTML = elems.join("\n");
2344 x.parentNode.insertBefore(node, x);
2347 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2348 if (hasClass(e, "compile_fail")) {
2349 e.addEventListener("mouseover", function(event) {
2350 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2352 e.addEventListener("mouseout", function(event) {
2353 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2355 } else if (hasClass(e, "ignore")) {
2356 e.addEventListener("mouseover", function(event) {
2357 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2359 e.addEventListener("mouseout", function(event) {
2360 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2366 function showModal(content) {
2367 var modal = document.createElement("div");
2368 modal.id = "important";
2369 addClass(modal, "modal");
2370 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2371 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2373 document.getElementsByTagName("body")[0].appendChild(modal);
2374 document.getElementById("modal-close").onclick = hideModal;
2375 modal.onclick = hideModal;
2378 function hideModal() {
2379 var modal = document.getElementById("important");
2381 modal.parentNode.removeChild(modal);
2385 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2386 e.onclick = function() {
2387 showModal(e.lastElementChild.innerHTML);
2391 // In the search display, allows to switch between tabs.
2392 function printTab(nb) {
2393 if (nb === 0 || nb === 1 || nb === 2) {
2397 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2398 if (nb_copy === 0) {
2399 addClass(elem, "selected");
2401 removeClass(elem, "selected");
2405 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2407 elem.style.display = "";
2409 elem.style.display = "none";
2415 function putBackSearch(search_input) {
2416 if (search_input.value !== "") {
2417 addClass(main, "hidden");
2418 removeClass(document.getElementById("search"), "hidden");
2419 if (browserSupportsHistoryApi()) {
2420 history.replaceState(search_input.value,
2422 "?search=" + encodeURIComponent(search_input.value));
2428 search_input.onfocus = function() {
2429 putBackSearch(this);
2433 var params = getQueryStringParams();
2434 if (params && params.search) {
2435 addClass(main, "hidden");
2436 var search = document.getElementById("search");
2437 removeClass(search, "hidden");
2438 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2441 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2443 sidebar_menu.onclick = function() {
2444 var sidebar = document.getElementsByClassName("sidebar")[0];
2445 if (hasClass(sidebar, "mobile") === true) {
2453 window.onresize = function() {
2457 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2459 if (window.location.hash && window.location.hash.length > 0) {
2460 expandSection(window.location.hash.replace(/^#/, ""));
2464 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2467 onEachLazy(main.childNodes, function(e) {
2468 // Unhide the actual content once loading is complete. Headers get
2469 // flex treatment for their horizontal layout, divs get block treatment
2470 // for vertical layout (column-oriented flex layout for divs caused
2471 // errors in mobile browsers).
2472 if (e.tagName === "H2" || e.tagName === "H3") {
2473 var nextTagName = e.nextElementSibling.tagName;
2474 if (nextTagName == "H2" || nextTagName == "H3") {
2475 e.nextElementSibling.style.display = "flex";
2477 e.nextElementSibling.style.display = "block";
2483 function addSearchOptions(crates) {
2484 var elem = document.getElementById('crate-search');
2489 var crates_text = [];
2490 if (Object.keys(crates).length > 1) {
2491 for (var crate in crates) {
2492 if (crates.hasOwnProperty(crate)) {
2493 crates_text.push(crate);
2497 crates_text.sort(function(a, b) {
2498 var lower_a = a.toLowerCase();
2499 var lower_b = b.toLowerCase();
2501 if (lower_a < lower_b) {
2503 } else if (lower_a > lower_b) {
2508 for (var i = 0; i < crates_text.length; ++i) {
2509 var option = document.createElement("option");
2510 option.value = crates_text[i];
2511 option.innerText = crates_text[i];
2512 elem.appendChild(option);
2516 window.addSearchOptions = addSearchOptions;
2519 // Sets the focus on the search bar at the top of the page
2520 function focusSearchBar() {
2521 document.getElementsByClassName("search-input")[0].focus();
2524 // Removes the focus from the search bar
2525 function defocusSearchBar() {
2526 document.getElementsByClassName("search-input")[0].blur();