2 /* global ALIASES, currentCrate, rootPath */
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */
7 /* global hideThemeButtonState, showThemeButtonState */
9 if (!String.prototype.startsWith) {
10 String.prototype.startsWith = function(searchString, position) {
11 position = position || 0;
12 return this.indexOf(searchString, position) === position;
15 if (!String.prototype.endsWith) {
16 String.prototype.endsWith = function(suffix, length) {
17 var l = length || this.length;
18 return this.indexOf(suffix, l - suffix.length) !== -1;
22 if (!DOMTokenList.prototype.add) {
23 DOMTokenList.prototype.add = function(className) {
24 if (className && !hasClass(this, className)) {
25 if (this.className && this.className.length > 0) {
26 this.className += " " + className;
28 this.className = className;
34 if (!DOMTokenList.prototype.remove) {
35 DOMTokenList.prototype.remove = function(className) {
36 if (className && this.className) {
37 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
43 function getSearchInput() {
44 return document.getElementsByClassName("search-input")[0];
47 function getSearchElement() {
48 return document.getElementById("search");
51 function getThemesElement() {
52 return document.getElementById("theme-choices");
55 function getThemePickerElement() {
56 return document.getElementById("theme-picker");
59 // Sets the focus on the search bar at the top of the page
60 function focusSearchBar() {
61 getSearchInput().focus();
64 // Removes the focus from the search bar
65 function defocusSearchBar() {
66 getSearchInput().blur();
72 // This mapping table should match the discriminants of
73 // `rustdoc::html::item_type::ItemType` type in Rust.
74 var itemTypes = ["mod",
101 var disableShortcuts = getSettingValue("disable-shortcuts") === "true";
102 var search_input = getSearchInput();
103 var searchTimeout = null;
104 var toggleAllDocsId = "toggle-all-docs";
106 // On the search screen, so you remain on the last tab you opened.
109 // 1 for "In Parameters"
110 // 2 for "In Return Types"
113 var mouseMovedAfterSearch = true;
115 var titleBeforeSearch = document.title;
117 function clearInputTimeout() {
118 if (searchTimeout !== null) {
119 clearTimeout(searchTimeout);
120 searchTimeout = null;
124 function getPageId() {
125 if (window.location.hash) {
126 var tmp = window.location.hash.replace(/^#/, "");
127 if (tmp.length > 0) {
134 function showSidebar() {
135 var elems = document.getElementsByClassName("sidebar-elems")[0];
137 addClass(elems, "show-it");
139 var sidebar = document.getElementsByClassName("sidebar")[0];
141 addClass(sidebar, "mobile");
142 var filler = document.getElementById("sidebar-filler");
144 var div = document.createElement("div");
145 div.id = "sidebar-filler";
146 sidebar.appendChild(div);
151 function hideSidebar() {
152 var elems = document.getElementsByClassName("sidebar-elems")[0];
154 removeClass(elems, "show-it");
156 var sidebar = document.getElementsByClassName("sidebar")[0];
157 removeClass(sidebar, "mobile");
158 var filler = document.getElementById("sidebar-filler");
162 document.getElementsByTagName("body")[0].style.marginTop = "";
165 function showSearchResults(search) {
166 if (search === null || typeof search === 'undefined') {
167 search = getSearchElement();
169 addClass(main, "hidden");
170 removeClass(search, "hidden");
171 mouseMovedAfterSearch = false;
174 function hideSearchResults(search) {
175 if (search === null || typeof search === 'undefined') {
176 search = getSearchElement();
178 addClass(search, "hidden");
179 removeClass(main, "hidden");
182 // used for special search precedence
183 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
184 var TY_KEYWORD = itemTypes.indexOf("keyword");
186 function getQueryStringParams() {
188 window.location.search.substring(1).split("&").
190 var pair = s.split("=");
191 params[decodeURIComponent(pair[0])] =
192 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
197 function browserSupportsHistoryApi() {
198 return window.history && typeof window.history.pushState === "function";
201 function isHidden(elem) {
202 return elem.offsetHeight === 0;
205 var main = document.getElementById("main");
208 function handleHashes(ev) {
210 var search = getSearchElement();
211 if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
212 // This block occurs when clicking on an element in the navbar while
214 hideSearchResults(search);
215 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
216 if (browserSupportsHistoryApi()) {
217 history.replaceState(hash, "", "?search=#" + hash);
219 elem = document.getElementById(hash);
221 elem.scrollIntoView();
224 // This part is used in case an element is not visible.
225 if (savedHash !== window.location.hash) {
226 savedHash = window.location.hash;
227 if (savedHash.length === 0) {
230 elem = document.getElementById(savedHash.slice(1)); // we remove the '#'
231 if (!elem || !isHidden(elem)) {
234 var parent = elem.parentNode;
235 if (parent && hasClass(parent, "impl-items")) {
236 // In case this is a trait implementation item, we first need to toggle
237 // the "Show hidden undocumented items".
238 onEachLazy(parent.getElementsByClassName("collapsed"), function(e) {
239 if (e.parentNode === parent) {
240 // Only click on the toggle we're looking for.
245 if (isHidden(elem)) {
246 // The whole parent is collapsed. We need to click on its toggle as well!
247 if (hasClass(parent.lastElementChild, "collapse-toggle")) {
248 parent.lastElementChild.click();
255 function highlightSourceLines(match, ev) {
256 if (typeof match === "undefined") {
257 // If we're in mobile mode, we should hide the sidebar in any case.
259 match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
264 var from = parseInt(match[1], 10);
266 if (typeof match[2] !== "undefined") {
267 to = parseInt(match[2], 10);
274 var elem = document.getElementById(from);
279 var x = document.getElementById(from);
284 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
285 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
286 removeClass(i_e, "line-highlighted");
289 for (var i = from; i <= to; ++i) {
290 elem = document.getElementById(i);
294 addClass(elem, "line-highlighted");
298 function onHashChange(ev) {
299 // If we're in mobile mode, we should hide the sidebar in any case.
301 var match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
303 return highlightSourceLines(match, ev);
308 function expandSection(id) {
309 var elem = document.getElementById(id);
310 if (elem && isHidden(elem)) {
311 var h3 = elem.parentNode.previousElementSibling;
312 if (h3 && h3.tagName !== "H3") {
313 h3 = h3.previousElementSibling; // skip div.docblock
317 var collapses = h3.getElementsByClassName("collapse-toggle");
318 if (collapses.length > 0) {
319 // The element is not visible, we need to make it appear!
320 collapseDocs(collapses[0], "show");
326 // Gets the human-readable string for the virtual-key code of the
327 // given KeyboardEvent, ev.
329 // This function is meant as a polyfill for KeyboardEvent#key,
330 // since it is not supported in Trident. We also test for
331 // KeyboardEvent#keyCode because the handleShortcut handler is
332 // also registered for the keydown event, because Blink doesn't fire
333 // keypress on hitting the Escape key.
335 // So I guess you could say things are getting pretty interoperable.
336 function getVirtualKey(ev) {
337 if ("key" in ev && typeof ev.key != "undefined") {
341 var c = ev.charCode || ev.keyCode;
345 return String.fromCharCode(c);
348 function getHelpElement() {
350 return document.getElementById("help");
353 function displayHelp(display, ev, help) {
354 help = help ? help : getHelpElement();
355 if (display === true) {
356 if (hasClass(help, "hidden")) {
358 removeClass(help, "hidden");
359 addClass(document.body, "blur");
361 } else if (hasClass(help, "hidden") === false) {
363 addClass(help, "hidden");
364 removeClass(document.body, "blur");
368 function handleEscape(ev) {
369 var help = getHelpElement();
370 var search = getSearchElement();
371 if (hasClass(help, "hidden") === false) {
372 displayHelp(false, ev, help);
373 } else if (hasClass(search, "hidden") === false) {
376 hideSearchResults(search);
377 document.title = titleBeforeSearch;
380 hideThemeButtonState();
383 function handleShortcut(ev) {
384 // Don't interfere with browser shortcuts
385 if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts === true) {
389 if (document.activeElement.tagName === "INPUT") {
390 switch (getVirtualKey(ev)) {
396 switch (getVirtualKey(ev)) {
403 displayHelp(false, ev);
415 displayHelp(true, ev);
419 var themePicker = getThemePickerElement();
420 if (themePicker.parentNode.contains(ev.target)) {
421 handleThemeKeyDown(ev);
427 function handleThemeKeyDown(ev) {
428 var active = document.activeElement;
429 var themes = getThemesElement();
430 switch (getVirtualKey(ev)) {
433 if (active.previousElementSibling && ev.target.id !== "theme-picker") {
434 active.previousElementSibling.focus();
436 showThemeButtonState();
437 themes.lastElementChild.focus();
442 if (active.nextElementSibling && ev.target.id !== "theme-picker") {
443 active.nextElementSibling.focus();
445 showThemeButtonState();
446 themes.firstElementChild.focus();
452 if (ev.target.id === "theme-picker" && themes.style.display === "none") {
454 showThemeButtonState();
455 themes.firstElementChild.focus();
460 themes.firstElementChild.focus();
464 themes.lastElementChild.focus();
466 // The escape key is handled in handleEscape, not here,
467 // so that pressing escape will close the menu even if it isn't focused
471 function findParentElement(elem, tagName) {
473 if (elem && elem.tagName === tagName) {
476 elem = elem.parentNode;
481 document.addEventListener("keypress", handleShortcut);
482 document.addEventListener("keydown", handleShortcut);
484 function resetMouseMoved(ev) {
485 mouseMovedAfterSearch = true;
488 document.addEventListener("mousemove", resetMouseMoved);
490 var handleSourceHighlight = (function() {
491 var prev_line_id = 0;
493 var set_fragment = function(name) {
494 var x = window.scrollX,
496 if (browserSupportsHistoryApi()) {
497 history.replaceState(null, null, "#" + name);
498 highlightSourceLines();
500 location.replace("#" + name);
502 // Prevent jumps when selecting one or many lines
503 window.scrollTo(x, y);
506 return function(ev) {
507 var cur_line_id = parseInt(ev.target.id, 10);
510 if (ev.shiftKey && prev_line_id) {
511 // Swap selection if needed
512 if (prev_line_id > cur_line_id) {
513 var tmp = prev_line_id;
514 prev_line_id = cur_line_id;
518 set_fragment(prev_line_id + "-" + cur_line_id);
520 prev_line_id = cur_line_id;
522 set_fragment(cur_line_id);
527 document.addEventListener("click", function(ev) {
528 if (hasClass(ev.target, "help-button")) {
529 displayHelp(true, ev);
530 } else if (hasClass(ev.target, "collapse-toggle")) {
531 collapseDocs(ev.target, "toggle");
532 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
533 collapseDocs(ev.target.parentNode, "toggle");
534 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
535 handleSourceHighlight(ev);
536 } else if (hasClass(getHelpElement(), "hidden") === false) {
537 var help = getHelpElement();
538 var is_inside_help_popup = ev.target !== help && help.contains(ev.target);
539 if (is_inside_help_popup === false) {
540 addClass(help, "hidden");
541 removeClass(document.body, "blur");
544 // Making a collapsed element visible on onhashchange seems
546 var a = findParentElement(ev.target, "A");
548 expandSection(a.hash.replace(/^#/, ""));
554 var x = document.getElementsByClassName("version-selector");
556 x[0].onchange = function() {
558 url = document.location.href,
560 len = rootPath.match(/\.\.\//g).length + 1;
562 for (i = 0; i < len; ++i) {
563 match = url.match(/\/[^\/]*$/);
565 stripped = match[0] + stripped;
567 url = url.substring(0, url.length - match[0].length);
570 var selectedVersion = document.getElementsByClassName("version-selector")[0].value;
571 url += "/" + selectedVersion + stripped;
573 document.location.href = url;
579 * A function to compute the Levenshtein distance between two strings
580 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
581 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
582 * This code is an unmodified version of the code written by Marco de Wit
583 * and was found at http://stackoverflow.com/a/18514751/745719
585 var levenshtein_row2 = [];
586 function levenshtein(s1, s2) {
590 var s1_len = s1.length, s2_len = s2.length;
591 if (s1_len && s2_len) {
592 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
593 while (i1 < s1_len) {
596 while (i2 < s2_len) {
597 c2 = s2.charCodeAt(i2);
601 for (i1 = 0; i1 < s1_len; ++i1) {
602 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
604 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
610 return s1_len + s2_len;
613 window.initSearch = function(rawSearchIndex) {
614 var MAX_LEV_DISTANCE = 3;
615 var MAX_RESULTS = 200;
616 var GENERICS_DATA = 1;
620 var NO_TYPE_FILTER = -1;
621 var currentResults, index, searchIndex;
623 var params = getQueryStringParams();
625 // Populate search bar with query string search term when provided,
626 // but only if the input bar is empty. This avoid the obnoxious issue
627 // where you start trying to do a search, and the index loads, and
628 // suddenly your search is gone!
629 if (search_input.value === "") {
630 search_input.value = params.search || "";
634 * Executes the query and builds an index of results
635 * @param {[Object]} query [The user query]
636 * @param {[type]} searchWords [The list of search words to query
638 * @param {[type]} filterCrates [Crate to search in if defined]
639 * @return {[type]} [A search index of results]
641 function execQuery(query, searchWords, filterCrates) {
642 function itemTypeFromName(typename) {
643 var length = itemTypes.length;
644 for (var i = 0; i < length; ++i) {
645 if (itemTypes[i] === typename) {
649 return NO_TYPE_FILTER;
652 var valLower = query.query.toLowerCase(),
654 typeFilter = itemTypeFromName(query.type),
655 results = {}, results_in_args = {}, results_returned = {},
656 split = valLower.split("::");
658 var length = split.length;
659 for (var z = 0; z < length; ++z) {
660 if (split[z] === "") {
666 function transformResults(results, isType) {
668 var length = results.length;
669 for (var i = 0; i < length; ++i) {
670 if (results[i].id > -1) {
671 var obj = searchIndex[results[i].id];
672 obj.lev = results[i].lev;
673 if (isType !== true || obj.type) {
674 var res = buildHrefAndPath(obj);
675 obj.displayPath = pathSplitter(res[0]);
676 obj.fullPath = obj.displayPath + obj.name;
677 // To be sure than it some items aren't considered as duplicate.
678 obj.fullPath += "|" + obj.ty;
681 if (out.length >= MAX_RESULTS) {
690 function sortResults(results, isType) {
692 for (var entry in results) {
693 if (hasOwnProperty(results, entry)) {
694 ar.push(results[entry]);
699 var nresults = results.length;
700 for (i = 0; i < nresults; ++i) {
701 results[i].word = searchWords[results[i].id];
702 results[i].item = searchIndex[results[i].id] || {};
704 // if there are no results then return to default and fail
705 if (results.length === 0) {
709 results.sort(function(aaa, bbb) {
712 // sort by exact match with regard to the last word (mismatch goes later)
713 a = (aaa.word !== val);
714 b = (bbb.word !== val);
715 if (a !== b) { return a - b; }
717 // Sort by non levenshtein results and then levenshtein results by the distance
718 // (less changes required to match means higher rankings)
721 if (a !== b) { return a - b; }
723 // sort by crate (non-current crate goes later)
724 a = (aaa.item.crate !== window.currentCrate);
725 b = (bbb.item.crate !== window.currentCrate);
726 if (a !== b) { return a - b; }
728 // sort by item name length (longer goes later)
731 if (a !== b) { return a - b; }
733 // sort by item name (lexicographically larger goes later)
736 if (a !== b) { return (a > b ? +1 : -1); }
738 // sort by index of keyword in item name (no literal occurrence goes later)
741 if (a !== b) { return a - b; }
742 // (later literal occurrence, if any, goes later)
745 if (a !== b) { return a - b; }
747 // special precedence for primitive and keyword pages
748 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
749 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
752 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
753 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
757 // sort by description (no description goes later)
758 a = (aaa.item.desc === "");
759 b = (bbb.item.desc === "");
760 if (a !== b) { return a - b; }
762 // sort by type (later occurrence in `itemTypes` goes later)
765 if (a !== b) { return a - b; }
767 // sort by path (lexicographically larger goes later)
770 if (a !== b) { return (a > b ? +1 : -1); }
776 var length = results.length;
777 for (i = 0; i < length; ++i) {
778 var result = results[i];
780 // this validation does not make sense when searching by types
781 if (result.dontValidate) {
784 var name = result.item.name.toLowerCase(),
785 path = result.item.path.toLowerCase(),
786 parent = result.item.parent;
788 if (isType !== true &&
789 validateResult(name, path, split, parent) === false)
794 return transformResults(results);
797 function extractGenerics(val) {
798 val = val.toLowerCase();
799 if (val.indexOf("<") !== -1) {
800 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
802 name: val.substring(0, val.indexOf("<")),
803 generics: values.split(/\s*,\s*/),
812 function getObjectFromId(id) {
813 if (typeof id === "number") {
814 return searchIndex[id];
819 function checkGenerics(obj, val) {
820 // The names match, but we need to be sure that all generics kinda
822 var lev_distance = MAX_LEV_DISTANCE + 1;
823 if (val.generics.length > 0) {
824 if (obj.length > GENERICS_DATA &&
825 obj[GENERICS_DATA].length >= val.generics.length) {
826 var elems = obj[GENERICS_DATA].slice(0);
829 // We need to find the type that matches the most to remove it in order
831 var vlength = val.generics.length;
832 for (var y = 0; y < vlength; ++y) {
833 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
834 var elength = elems.length;
835 var firstGeneric = getObjectFromId(val.generics[y]).name;
836 for (var x = 0; x < elength; ++x) {
837 var tmp_lev = levenshtein(getObjectFromId(elems[x]).name,
839 if (tmp_lev < lev.lev) {
844 if (lev.pos !== -1) {
845 elems.splice(lev.pos, 1);
846 lev_distance = Math.min(lev.lev, lev_distance);
850 return MAX_LEV_DISTANCE + 1;
853 return Math.ceil(total / done);
856 return MAX_LEV_DISTANCE + 1;
859 // Check for type name and type generics (if any).
860 function checkType(obj, val, literalSearch) {
861 var lev_distance = MAX_LEV_DISTANCE + 1;
863 if (obj[NAME] === val.name) {
864 if (literalSearch === true) {
865 if (val.generics && val.generics.length !== 0) {
866 if (obj.length > GENERICS_DATA &&
867 obj[GENERICS_DATA].length >= val.generics.length) {
868 var elems = obj[GENERICS_DATA].slice(0);
871 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
873 var firstGeneric = getObjectFromId(val.generics[y]).name;
874 for (x = 0; allFound === false && x < elems.length; ++x) {
875 allFound = getObjectFromId(elems[x]).name === firstGeneric;
877 if (allFound === true) {
878 elems.splice(x - 1, 1);
881 if (allFound === true) {
890 // If the type has generics but don't match, then it won't return at this point.
891 // Otherwise, `checkGenerics` will return 0 and it'll return.
892 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
893 var tmp_lev = checkGenerics(obj, val);
894 if (tmp_lev <= MAX_LEV_DISTANCE) {
901 // Names didn't match so let's check if one of the generic types could.
902 if (literalSearch === true) {
903 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
904 var length = obj[GENERICS_DATA].length;
905 for (x = 0; x < length; ++x) {
906 if (obj[GENERICS_DATA][x] === val.name) {
913 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
914 if (lev_distance <= MAX_LEV_DISTANCE) {
915 // The generics didn't match but the name kinda did so we give it
916 // a levenshtein distance value that isn't *this* good so it goes
917 // into the search results but not too high.
918 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
919 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
920 // We can check if the type we're looking for is inside the generics!
921 var olength = obj[GENERICS_DATA].length;
922 for (x = 0; x < olength; ++x) {
923 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
927 // Now whatever happens, the returned distance is "less good" so we should mark it
928 // as such, and so we add 1 to the distance to make it "less good".
929 return lev_distance + 1;
932 function findArg(obj, val, literalSearch, typeFilter) {
933 var lev_distance = MAX_LEV_DISTANCE + 1;
935 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
936 var length = obj.type[INPUTS_DATA].length;
937 for (var i = 0; i < length; i++) {
938 var tmp = obj.type[INPUTS_DATA][i];
939 if (typePassesFilter(typeFilter, tmp[1]) === false) {
942 tmp = checkType(tmp, val, literalSearch);
943 if (literalSearch === true) {
949 lev_distance = Math.min(tmp, lev_distance);
950 if (lev_distance === 0) {
955 return literalSearch === true ? false : lev_distance;
958 function checkReturned(obj, val, literalSearch, typeFilter) {
959 var lev_distance = MAX_LEV_DISTANCE + 1;
961 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
962 var ret = obj.type[OUTPUT_DATA];
963 if (typeof ret[0] === "string") {
966 for (var x = 0; x < ret.length; ++x) {
968 if (typePassesFilter(typeFilter, tmp[1]) === false) {
971 tmp = checkType(tmp, val, literalSearch);
972 if (literalSearch === true) {
978 lev_distance = Math.min(tmp, lev_distance);
979 if (lev_distance === 0) {
984 return literalSearch === true ? false : lev_distance;
987 function checkPath(contains, lastElem, ty) {
988 if (contains.length === 0) {
991 var ret_lev = MAX_LEV_DISTANCE + 1;
992 var path = ty.path.split("::");
994 if (ty.parent && ty.parent.name) {
995 path.push(ty.parent.name.toLowerCase());
998 var length = path.length;
999 var clength = contains.length;
1000 if (clength > length) {
1001 return MAX_LEV_DISTANCE + 1;
1003 for (var i = 0; i < length; ++i) {
1004 if (i + clength > length) {
1008 var aborted = false;
1009 for (var x = 0; x < clength; ++x) {
1010 var lev = levenshtein(path[i + x], contains[x]);
1011 if (lev > MAX_LEV_DISTANCE) {
1017 if (aborted === false) {
1018 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1024 function typePassesFilter(filter, type) {
1026 if (filter <= NO_TYPE_FILTER) return true;
1029 if (filter === type) return true;
1031 // Match related items
1032 var name = itemTypes[type];
1033 switch (itemTypes[filter]) {
1035 return name === "associatedconstant";
1037 return name === "method" || name === "tymethod";
1039 return name === "primitive" || name === "associatedtype";
1041 return name === "traitalias";
1048 function generateId(ty) {
1049 if (ty.parent && ty.parent.name) {
1050 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
1052 return itemTypes[ty.ty] + ty.path + ty.name;
1055 function createAliasFromItem(item) {
1062 parent: item.parent,
1068 function handleAliases(ret, query, filterCrates) {
1069 // We separate aliases and crate aliases because we want to have current crate
1070 // aliases to be before the others in the displayed results.
1072 var crateAliases = [];
1074 if (filterCrates !== undefined) {
1075 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
1076 for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) {
1078 createAliasFromItem(
1079 searchIndex[ALIASES[filterCrates][query.search][i]]));
1083 Object.keys(ALIASES).forEach(function(crate) {
1084 if (ALIASES[crate][query.search]) {
1085 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
1086 for (i = 0; i < ALIASES[crate][query.search].length; ++i) {
1088 createAliasFromItem(
1089 searchIndex[ALIASES[crate][query.search][i]]));
1095 var sortFunc = function(aaa, bbb) {
1096 if (aaa.path < bbb.path) {
1098 } else if (aaa.path === bbb.path) {
1103 crateAliases.sort(sortFunc);
1104 aliases.sort(sortFunc);
1106 var pushFunc = function(alias) {
1107 alias.alias = query.raw;
1108 var res = buildHrefAndPath(alias);
1109 alias.displayPath = pathSplitter(res[0]);
1110 alias.fullPath = alias.displayPath + alias.name;
1111 alias.href = res[1];
1113 ret.others.unshift(alias);
1114 if (ret.others.length > MAX_RESULTS) {
1118 onEach(aliases, pushFunc);
1119 onEach(crateAliases, pushFunc);
1122 // quoted values mean literal search
1123 var nSearchWords = searchWords.length;
1129 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
1130 val.charAt(val.length - 1) === val.charAt(0))
1132 val = extractGenerics(val.substr(1, val.length - 2));
1133 for (i = 0; i < nSearchWords; ++i) {
1134 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1137 in_args = findArg(searchIndex[i], val, true, typeFilter);
1138 returned = checkReturned(searchIndex[i], val, true, typeFilter);
1139 ty = searchIndex[i];
1140 fullId = generateId(ty);
1142 if (searchWords[i] === val.name
1143 && typePassesFilter(typeFilter, searchIndex[i].ty)
1144 && results[fullId] === undefined) {
1151 if (in_args === true && results_in_args[fullId] === undefined) {
1152 results_in_args[fullId] = {
1158 if (returned === true && results_returned[fullId] === undefined) {
1159 results_returned[fullId] = {
1166 query.inputs = [val];
1169 // searching by type
1170 } else if (val.search("->") > -1) {
1171 var trimmer = function(s) { return s.trim(); };
1172 var parts = val.split("->").map(trimmer);
1173 var input = parts[0];
1174 // sort inputs so that order does not matter
1175 var inputs = input.split(",").map(trimmer).sort();
1176 for (i = 0; i < inputs.length; ++i) {
1177 inputs[i] = extractGenerics(inputs[i]);
1179 var output = extractGenerics(parts[1]);
1181 for (i = 0; i < nSearchWords; ++i) {
1182 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1185 var type = searchIndex[i].type;
1186 ty = searchIndex[i];
1190 fullId = generateId(ty);
1192 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
1193 if (output.name === "*" || returned === true) {
1195 var is_module = false;
1197 if (input === "*") {
1200 var allFound = true;
1201 for (var it = 0; allFound === true && it < inputs.length; it++) {
1202 allFound = checkType(type, inputs[it], true);
1206 if (in_args === true) {
1207 results_in_args[fullId] = {
1213 if (returned === true) {
1214 results_returned[fullId] = {
1220 if (is_module === true) {
1229 query.inputs = inputs.map(function(input) {
1232 query.output = output.name;
1234 query.inputs = [val];
1237 // gather matching search results up to a certain maximum
1238 val = val.replace(/\_/g, "");
1240 var valGenerics = extractGenerics(val);
1242 var paths = valLower.split("::");
1244 for (j = 0; j < paths.length; ++j) {
1245 if (paths[j] === "") {
1250 val = paths[paths.length - 1];
1251 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
1254 for (j = 0; j < nSearchWords; ++j) {
1255 ty = searchIndex[j];
1256 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1260 if (paths.length > 1) {
1261 lev = checkPath(contains, paths[paths.length - 1], ty);
1262 if (lev > MAX_LEV_DISTANCE) {
1264 } else if (lev > 0) {
1269 returned = MAX_LEV_DISTANCE + 1;
1270 in_args = MAX_LEV_DISTANCE + 1;
1272 // we want lev results to go lower than others
1273 lev = MAX_LEV_DISTANCE + 1;
1274 fullId = generateId(ty);
1276 if (searchWords[j].indexOf(split[i]) > -1 ||
1277 searchWords[j].indexOf(val) > -1 ||
1278 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1280 // filter type: ... queries
1281 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1282 index = searchWords[j].replace(/_/g, "").indexOf(val);
1285 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1286 if (typePassesFilter(typeFilter, ty.ty) === false) {
1287 lev = MAX_LEV_DISTANCE + 1;
1292 in_args = findArg(ty, valGenerics, false, typeFilter);
1293 returned = checkReturned(ty, valGenerics, false, typeFilter);
1296 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1297 if (val.length < 6) {
1303 if (in_args <= MAX_LEV_DISTANCE) {
1304 if (results_in_args[fullId] === undefined) {
1305 results_in_args[fullId] = {
1311 results_in_args[fullId].lev =
1312 Math.min(results_in_args[fullId].lev, in_args);
1314 if (returned <= MAX_LEV_DISTANCE) {
1315 if (results_returned[fullId] === undefined) {
1316 results_returned[fullId] = {
1322 results_returned[fullId].lev =
1323 Math.min(results_returned[fullId].lev, returned);
1325 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1326 if (index !== -1 && paths.length < 2) {
1329 if (results[fullId] === undefined) {
1336 results[fullId].lev = Math.min(results[fullId].lev, lev);
1342 "in_args": sortResults(results_in_args, true),
1343 "returned": sortResults(results_returned, true),
1344 "others": sortResults(results),
1346 handleAliases(ret, query, filterCrates);
1351 * Validate performs the following boolean logic. For example:
1352 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1353 * exists in (name || path || parent) OR => ("file" && "open") exists in
1356 * This could be written functionally, but I wanted to minimise
1357 * functions on stack.
1359 * @param {[string]} name [The name of the result]
1360 * @param {[string]} path [The path of the result]
1361 * @param {[string]} keys [The keys to be used (["file", "open"])]
1362 * @param {[object]} parent [The parent of the result]
1363 * @return {[boolean]} [Whether the result is valid or not]
1365 function validateResult(name, path, keys, parent) {
1366 for (var i = 0; i < keys.length; ++i) {
1367 // each check is for validation so we negate the conditions and invalidate
1369 // check for an exact name match
1370 name.indexOf(keys[i]) > -1 ||
1371 // then an exact path match
1372 path.indexOf(keys[i]) > -1 ||
1373 // next if there is a parent, check for exact parent match
1374 (parent !== undefined && parent.name !== undefined &&
1375 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1376 // lastly check to see if the name was a levenshtein match
1377 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1384 function getQuery(raw) {
1385 var matches, type, query;
1388 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1390 type = matches[1].replace(/^const$/, "constant");
1391 query = query.substring(matches[0].length);
1402 function initSearchNav() {
1405 var click_func = function(e) {
1407 // to retrieve the real "owner" of the event.
1408 while (el.tagName !== "TR") {
1411 var dst = e.target.getElementsByTagName("a");
1412 if (dst.length < 1) {
1416 if (window.location.pathname === dst.pathname) {
1417 hideSearchResults();
1418 document.location.href = dst.href;
1421 var mouseover_func = function(e) {
1422 if (mouseMovedAfterSearch) {
1424 // to retrieve the real "owner" of the event.
1425 while (el.tagName !== "TR") {
1428 clearTimeout(hoverTimeout);
1429 hoverTimeout = setTimeout(function() {
1430 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1431 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1432 removeClass(i_e, "highlighted");
1435 addClass(el, "highlighted");
1439 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1440 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1441 i_e.onclick = click_func;
1442 i_e.onmouseover = mouseover_func;
1446 search_input.onkeydown = function(e) {
1447 // "actives" references the currently highlighted item in each search tab.
1448 // Each array in "actives" represents a tab.
1449 var actives = [[], [], []];
1450 // "current" is used to know which tab we're looking into.
1452 onEachLazy(document.getElementById("results").childNodes, function(e) {
1453 onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
1454 actives[current].push(h_e);
1459 if (e.which === 38) { // up
1460 if (!actives[currentTab].length ||
1461 !actives[currentTab][0].previousElementSibling) {
1465 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1466 removeClass(actives[currentTab][0], "highlighted");
1468 } else if (e.which === 40) { // down
1469 if (!actives[currentTab].length) {
1470 var results = document.getElementById("results").childNodes;
1471 if (results.length > 0) {
1472 var res = results[currentTab].getElementsByClassName("result");
1473 if (res.length > 0) {
1474 addClass(res[0], "highlighted");
1477 } else if (actives[currentTab][0].nextElementSibling) {
1478 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1479 removeClass(actives[currentTab][0], "highlighted");
1482 } else if (e.which === 13) { // return
1483 if (actives[currentTab].length) {
1484 document.location.href =
1485 actives[currentTab][0].getElementsByTagName("a")[0].href;
1487 } else if (e.which === 9) { // tab
1489 printTab(currentTab > 0 ? currentTab - 1 : 2);
1491 printTab(currentTab > 1 ? 0 : currentTab + 1);
1494 } else if (e.which === 16) { // shift
1495 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1496 } else if (actives[currentTab].length > 0) {
1497 removeClass(actives[currentTab][0], "highlighted");
1502 function buildHrefAndPath(item) {
1505 var type = itemTypes[item.ty];
1506 var name = item.name;
1507 var path = item.path;
1509 if (type === "mod") {
1510 displayPath = path + "::";
1511 href = rootPath + path.replace(/::/g, "/") + "/" +
1512 name + "/index.html";
1513 } else if (type === "primitive" || type === "keyword") {
1515 href = rootPath + path.replace(/::/g, "/") +
1516 "/" + type + "." + name + ".html";
1517 } else if (type === "externcrate") {
1519 href = rootPath + name + "/index.html";
1520 } else if (item.parent !== undefined) {
1521 var myparent = item.parent;
1522 var anchor = "#" + type + "." + name;
1523 var parentType = itemTypes[myparent.ty];
1524 var pageType = parentType;
1525 var pageName = myparent.name;
1527 if (parentType === "primitive") {
1528 displayPath = myparent.name + "::";
1529 } else if (type === "structfield" && parentType === "variant") {
1530 // Structfields belonging to variants are special: the
1531 // final path element is the enum name.
1532 var splitPath = item.path.split("::");
1533 var enumName = splitPath.pop();
1534 path = splitPath.join("::");
1535 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1536 anchor = "#variant." + myparent.name + ".field." + name;
1538 pageName = enumName;
1540 displayPath = path + "::" + myparent.name + "::";
1542 href = rootPath + path.replace(/::/g, "/") +
1547 displayPath = item.path + "::";
1548 href = rootPath + item.path.replace(/::/g, "/") +
1549 "/" + type + "." + name + ".html";
1551 return [displayPath, href];
1554 function escape(content) {
1555 var h1 = document.createElement("h1");
1556 h1.textContent = content;
1557 return h1.innerHTML;
1560 function pathSplitter(path) {
1561 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1562 if (tmp.endsWith("<span>")) {
1563 return tmp.slice(0, tmp.length - 6);
1568 function addTab(array, query, display) {
1569 var extraStyle = "";
1570 if (display === false) {
1571 extraStyle = " style=\"display: none;\"";
1575 var duplicates = {};
1577 if (array.length > 0) {
1578 output = "<table class=\"search-results\"" + extraStyle + ">";
1580 array.forEach(function(item) {
1584 type = itemTypes[item.ty];
1586 if (item.is_alias !== true) {
1587 if (duplicates[item.fullPath]) {
1590 duplicates[item.fullPath] = true;
1594 output += "<tr class=\"" + type + " result\"><td>" +
1595 "<a href=\"" + item.href + "\">" +
1596 (item.is_alias === true ?
1597 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1598 "class=\"grey\"><i> - see </i></span>") : "") +
1599 item.displayPath + "<span class=\"" + type + "\">" +
1600 name + "</span></a></td><td>" +
1601 "<a href=\"" + item.href + "\">" +
1602 "<span class=\"desc\">" + escape(item.desc) +
1603 " </span></a></td></tr>";
1605 output += "</table>";
1607 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1608 "Try on <a href=\"https://duckduckgo.com/?q=" +
1609 encodeURIComponent("rust " + query.query) +
1610 "\">DuckDuckGo</a>?<br/><br/>" +
1611 "Or try looking in one of these:<ul><li>The <a " +
1612 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1613 " for technical details about the language.</li><li><a " +
1614 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1615 "Example</a> for expository code examples.</a></li><li>The <a " +
1616 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1617 "introductions to language features and the language itself.</li><li><a " +
1618 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1619 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1621 return [output, length];
1624 function makeTabHeader(tabNb, text, nbElems) {
1625 if (currentTab === tabNb) {
1626 return "<div class=\"selected\">" + text +
1627 " <div class=\"count\">(" + nbElems + ")</div></div>";
1629 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1632 function showResults(results) {
1633 var search = getSearchElement();
1634 if (results.others.length === 1
1635 && getSettingValue("go-to-only-result") === "true"
1636 // By default, the search DOM element is "empty" (meaning it has no children not
1637 // text content). Once a search has been run, it won't be empty, even if you press
1638 // ESC or empty the search input (which also "cancels" the search).
1639 && (!search.firstChild || search.firstChild.innerText !== getSearchLoadingText()))
1641 var elem = document.createElement("a");
1642 elem.href = results.others[0].href;
1643 elem.style.display = "none";
1644 // For firefox, we need the element to be in the DOM so it can be clicked.
1645 document.body.appendChild(elem);
1649 var query = getQuery(search_input.value);
1651 currentResults = query.id;
1653 var ret_others = addTab(results.others, query);
1654 var ret_in_args = addTab(results.in_args, query, false);
1655 var ret_returned = addTab(results.returned, query, false);
1657 var output = "<h1>Results for " + escape(query.query) +
1658 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1659 "<div id=\"titles\">" +
1660 makeTabHeader(0, "In Names", ret_others[1]) +
1661 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1662 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1663 "</div><div id=\"results\">" +
1664 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1666 search.innerHTML = output;
1667 showSearchResults(search);
1668 var tds = search.getElementsByTagName("td");
1670 if (tds.length > 0) {
1671 td_width = tds[0].offsetWidth;
1673 var width = search.offsetWidth - 40 - td_width;
1674 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1675 e.style.width = width + "px";
1678 var elems = document.getElementById("titles").childNodes;
1679 elems[0].onclick = function() { printTab(0); };
1680 elems[1].onclick = function() { printTab(1); };
1681 elems[2].onclick = function() { printTab(2); };
1682 printTab(currentTab);
1685 function execSearch(query, searchWords, filterCrates) {
1686 function getSmallest(arrays, positions, notDuplicates) {
1689 for (var it = 0; it < positions.length; ++it) {
1690 if (arrays[it].length > positions[it] &&
1691 (start === null || start > arrays[it][positions[it]].lev) &&
1692 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1693 start = arrays[it][positions[it]].lev;
1699 function mergeArrays(arrays) {
1702 var notDuplicates = {};
1704 for (var x = 0; x < arrays.length; ++x) {
1707 while (ret.length < MAX_RESULTS) {
1708 var smallest = getSmallest(arrays, positions, notDuplicates);
1710 if (smallest === null) {
1713 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1714 if (arrays[x].length > positions[x] &&
1715 arrays[x][positions[x]].lev === smallest &&
1716 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1717 ret.push(arrays[x][positions[x]]);
1718 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1726 var queries = query.raw.split(",");
1733 for (var i = 0; i < queries.length; ++i) {
1734 query = queries[i].trim();
1735 if (query.length !== 0) {
1736 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1738 results.in_args.push(tmp.in_args);
1739 results.returned.push(tmp.returned);
1740 results.others.push(tmp.others);
1743 if (queries.length > 1) {
1745 "in_args": mergeArrays(results.in_args),
1746 "returned": mergeArrays(results.returned),
1747 "others": mergeArrays(results.others),
1751 "in_args": results.in_args[0],
1752 "returned": results.returned[0],
1753 "others": results.others[0],
1757 function getFilterCrates() {
1758 var elem = document.getElementById("crate-search");
1760 if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1766 function search(e, forced) {
1767 var params = getQueryStringParams();
1768 var query = getQuery(search_input.value.trim());
1774 if (query.query.length === 0) {
1777 if (forced !== true && query.id === currentResults) {
1778 if (query.query.length > 0) {
1779 putBackSearch(search_input);
1784 // Update document title to maintain a meaningful browser history
1785 document.title = "Results for " + query.query + " - Rust";
1787 // Because searching is incremental by character, only the most
1788 // recent search query is added to the browser history.
1789 if (browserSupportsHistoryApi()) {
1790 if (!history.state && !params.search) {
1791 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1793 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1797 var filterCrates = getFilterCrates();
1798 showResults(execSearch(query, index, filterCrates));
1801 function buildIndex(rawSearchIndex) {
1803 var searchWords = [];
1805 var currentIndex = 0;
1807 for (var crate in rawSearchIndex) {
1808 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1812 searchWords.push(crate);
1815 ty: 1, // == ExternCrate
1818 desc: rawSearchIndex[crate].doc,
1823 // an array of [(Number) item type,
1825 // (String) full path or empty string for previous path,
1826 // (String) description,
1827 // (Number | null) the parent path index to `paths`]
1828 // (Object | null) the type of the function (if any)
1829 var items = rawSearchIndex[crate].i;
1830 // an array of [(Number) item type,
1832 var paths = rawSearchIndex[crate].p;
1833 // a array of [(String) alias name
1834 // [Number] index to items]
1835 var aliases = rawSearchIndex[crate].a;
1837 // convert `rawPaths` entries into object form
1838 var len = paths.length;
1839 for (i = 0; i < len; ++i) {
1840 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1843 // convert `items` into an object form, and construct word indices.
1845 // before any analysis is performed lets gather the search terms to
1846 // search against apart from the rest of the data. This is a quick
1847 // operation that is cached for the life of the page state so that
1848 // all other search operations have access to this cached data for
1849 // faster analysis operations
1852 for (i = 0; i < len; ++i) {
1853 var rawRow = items[i];
1855 rawRow[2] = lastPath;
1863 parent: paths[rawRow[4]],
1866 searchIndex.push(row);
1867 if (typeof row.name === "string") {
1868 var word = row.name.toLowerCase();
1869 searchWords.push(word);
1871 searchWords.push("");
1873 lastPath = row.path;
1878 ALIASES[crate] = {};
1879 var j, local_aliases;
1880 for (var alias_name in aliases) {
1881 if (!aliases.hasOwnProperty(alias_name)) { continue; }
1883 if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1884 ALIASES[crate][alias_name] = [];
1886 local_aliases = aliases[alias_name];
1887 for (j = 0; j < local_aliases.length; ++j) {
1888 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1892 currentIndex += crateSize;
1897 function startSearch() {
1898 var callback = function() {
1899 clearInputTimeout();
1900 if (search_input.value.length === 0) {
1901 if (browserSupportsHistoryApi()) {
1902 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1904 hideSearchResults();
1906 searchTimeout = setTimeout(search, 500);
1909 search_input.onkeyup = callback;
1910 search_input.oninput = callback;
1911 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1913 clearInputTimeout();
1916 search_input.onchange = function(e) {
1917 if (e.target !== document.activeElement) {
1918 // To prevent doing anything when it's from a blur event.
1921 // Do NOT e.preventDefault() here. It will prevent pasting.
1922 clearInputTimeout();
1923 // zero-timeout necessary here because at the time of event handler execution the
1924 // pasted content is not in the input field yet. Shouldn’t make any difference for
1926 setTimeout(search, 0);
1928 search_input.onpaste = search_input.onchange;
1930 var selectCrate = document.getElementById("crate-search");
1932 selectCrate.onchange = function() {
1933 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1934 search(undefined, true);
1938 // Push and pop states are used to add search results to the browser
1940 if (browserSupportsHistoryApi()) {
1941 // Store the previous <title> so we can revert back to it later.
1942 var previousTitle = document.title;
1944 window.addEventListener("popstate", function(e) {
1945 var params = getQueryStringParams();
1946 // Revert to the previous title manually since the History
1947 // API ignores the title parameter.
1948 document.title = previousTitle;
1949 // When browsing forward to search results the previous
1950 // search will be repeated, so the currentResults are
1951 // cleared to ensure the search is successful.
1952 currentResults = null;
1953 // Synchronize search bar with query string state and
1954 // perform the search. This will empty the bar if there's
1955 // nothing there, which lets you really go back to a
1956 // previous state with nothing in the bar.
1957 if (params.search && params.search.length > 0) {
1958 search_input.value = params.search;
1959 // Some browsers fire "onpopstate" for every page load
1960 // (Chrome), while others fire the event only when actually
1961 // popping a state (Firefox), which is why search() is
1962 // called both here and at the end of the startSearch()
1966 search_input.value = "";
1967 // When browsing back from search results the main page
1968 // visibility must be reset.
1969 hideSearchResults();
1976 index = buildIndex(rawSearchIndex);
1979 // Draw a convenient sidebar of known crates if we have a listing
1980 if (rootPath === "../" || rootPath === "./") {
1981 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1983 var div = document.createElement("div");
1984 div.className = "block crate";
1985 div.innerHTML = "<h3>Crates</h3>";
1986 var ul = document.createElement("ul");
1987 div.appendChild(ul);
1990 for (var crate in rawSearchIndex) {
1991 if (!hasOwnProperty(rawSearchIndex, crate)) {
1997 for (var i = 0; i < crates.length; ++i) {
1998 var klass = "crate";
1999 if (rootPath !== "./" && crates[i] === window.currentCrate) {
2000 klass += " current";
2002 var link = document.createElement("a");
2003 link.href = rootPath + crates[i] + "/index.html";
2004 link.title = rawSearchIndex[crates[i]].doc;
2005 link.className = klass;
2006 link.textContent = crates[i];
2008 var li = document.createElement("li");
2009 li.appendChild(link);
2012 sidebar.appendChild(div);
2018 // delayed sidebar rendering.
2019 window.initSidebarItems = function(items) {
2020 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
2021 var current = window.sidebarCurrent;
2023 function block(shortty, longty) {
2024 var filtered = items[shortty];
2029 var div = document.createElement("div");
2030 div.className = "block " + shortty;
2031 var h3 = document.createElement("h3");
2032 h3.textContent = longty;
2033 div.appendChild(h3);
2034 var ul = document.createElement("ul");
2036 var length = filtered.length;
2037 for (var i = 0; i < length; ++i) {
2038 var item = filtered[i];
2040 var desc = item[1]; // can be null
2042 var klass = shortty;
2043 if (name === current.name && shortty === current.ty) {
2044 klass += " current";
2047 if (shortty === "mod") {
2048 path = name + "/index.html";
2050 path = shortty + "." + name + ".html";
2052 var link = document.createElement("a");
2053 link.href = current.relpath + path;
2055 link.className = klass;
2056 link.textContent = name;
2057 var li = document.createElement("li");
2058 li.appendChild(link);
2061 div.appendChild(ul);
2063 sidebar.appendChild(div);
2067 block("primitive", "Primitive Types");
2068 block("mod", "Modules");
2069 block("macro", "Macros");
2070 block("struct", "Structs");
2071 block("enum", "Enums");
2072 block("union", "Unions");
2073 block("constant", "Constants");
2074 block("static", "Statics");
2075 block("trait", "Traits");
2076 block("fn", "Functions");
2077 block("type", "Type Definitions");
2078 block("foreigntype", "Foreign Types");
2079 block("keyword", "Keywords");
2080 block("traitalias", "Trait Aliases");
2083 window.register_implementors = function(imp) {
2084 var implementors = document.getElementById("implementors-list");
2085 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
2087 if (synthetic_implementors) {
2088 // This `inlined_types` variable is used to avoid having the same implementation
2089 // showing up twice. For example "String" in the "Sync" doc page.
2091 // By the way, this is only used by and useful for traits implemented automatically
2092 // (like "Send" and "Sync").
2093 var inlined_types = new Set();
2094 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) {
2095 var aliases = el.getAttribute("aliases");
2099 aliases.split(",").forEach(function(alias) {
2100 inlined_types.add(alias);
2105 var libs = Object.getOwnPropertyNames(imp);
2106 var llength = libs.length;
2107 for (var i = 0; i < llength; ++i) {
2108 if (libs[i] === currentCrate) { continue; }
2109 var structs = imp[libs[i]];
2111 var slength = structs.length;
2113 for (var j = 0; j < slength; ++j) {
2114 var struct = structs[j];
2116 var list = struct.synthetic ? synthetic_implementors : implementors;
2118 if (struct.synthetic) {
2119 var stlength = struct.types.length;
2120 for (var k = 0; k < stlength; k++) {
2121 if (inlined_types.has(struct.types[k])) {
2122 continue struct_loop;
2124 inlined_types.add(struct.types[k]);
2128 var code = document.createElement("code");
2129 code.innerHTML = struct.text;
2131 var x = code.getElementsByTagName("a");
2132 var xlength = x.length;
2133 for (var it = 0; it < xlength; it++) {
2134 var href = x[it].getAttribute("href");
2135 if (href && href.indexOf("http") !== 0) {
2136 x[it].setAttribute("href", rootPath + href);
2139 var display = document.createElement("h3");
2140 addClass(display, "impl");
2141 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
2142 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
2143 "</tbody></table></span>";
2144 list.appendChild(display);
2148 if (window.pending_implementors) {
2149 window.register_implementors(window.pending_implementors);
2152 function labelForToggleButton(sectionIsCollapsed) {
2153 if (sectionIsCollapsed) {
2154 // button will expand the section
2157 // button will collapse the section
2158 // note that this text is also set in the HTML template in render.rs
2159 return "\u2212"; // "\u2212" is "−" minus sign
2162 function onEveryMatchingChild(elem, className, func) {
2163 if (elem && className && func) {
2164 var length = elem.childNodes.length;
2165 var nodes = elem.childNodes;
2166 for (var i = 0; i < length; ++i) {
2167 if (hasClass(nodes[i], className)) {
2170 onEveryMatchingChild(nodes[i], className, func);
2176 function toggleAllDocs(pageId, fromAutoCollapse) {
2177 var innerToggle = document.getElementById(toggleAllDocsId);
2181 if (hasClass(innerToggle, "will-expand")) {
2182 updateLocalStorage("rustdoc-collapse", "false");
2183 removeClass(innerToggle, "will-expand");
2184 onEveryMatchingChild(innerToggle, "inner", function(e) {
2185 e.innerHTML = labelForToggleButton(false);
2187 innerToggle.title = "collapse all docs";
2188 if (fromAutoCollapse !== true) {
2189 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2190 collapseDocs(e, "show");
2194 updateLocalStorage("rustdoc-collapse", "true");
2195 addClass(innerToggle, "will-expand");
2196 onEveryMatchingChild(innerToggle, "inner", function(e) {
2197 var parent = e.parentNode;
2198 var superParent = null;
2201 superParent = parent.parentNode;
2203 if (!parent || !superParent || superParent.id !== "main" ||
2204 hasClass(parent, "impl") === false) {
2205 e.innerHTML = labelForToggleButton(true);
2208 innerToggle.title = "expand all docs";
2209 if (fromAutoCollapse !== true) {
2210 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2211 var parent = e.parentNode;
2212 var superParent = null;
2215 superParent = parent.parentNode;
2217 if (!parent || !superParent || superParent.id !== "main" ||
2218 hasClass(parent, "impl") === false) {
2219 collapseDocs(e, "hide", pageId);
2226 function collapseDocs(toggle, mode, pageId) {
2227 if (!toggle || !toggle.parentNode) {
2231 function adjustToggle(arg) {
2232 return function(e) {
2233 if (hasClass(e, "toggle-label")) {
2235 e.style.display = "inline-block";
2237 e.style.display = "none";
2240 if (hasClass(e, "inner")) {
2241 e.innerHTML = labelForToggleButton(arg);
2246 function implHider(addOrRemove, fullHide) {
2247 return function(n) {
2248 var is_method = hasClass(n, "method") || fullHide;
2249 if (is_method || hasClass(n, "type")) {
2250 if (is_method === true) {
2252 addClass(n, "hidden-by-impl-hider");
2254 removeClass(n, "hidden-by-impl-hider");
2257 var ns = n.nextElementSibling;
2258 while (ns && (hasClass(ns, "docblock") || hasClass(ns, "stability"))) {
2260 addClass(ns, "hidden-by-impl-hider");
2262 removeClass(ns, "hidden-by-impl-hider");
2264 ns = ns.nextElementSibling;
2272 if (hasClass(toggle.parentNode, "impl") === false) {
2273 relatedDoc = toggle.parentNode.nextElementSibling;
2274 if (hasClass(relatedDoc, "stability")) {
2275 relatedDoc = relatedDoc.nextElementSibling;
2277 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
2278 if (mode === "toggle") {
2279 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2285 if (action === "hide") {
2286 addClass(relatedDoc, "hidden-by-usual-hider");
2287 onEachLazy(toggle.childNodes, adjustToggle(true));
2288 addClass(toggle.parentNode, "collapsed");
2289 } else if (action === "show") {
2290 removeClass(relatedDoc, "hidden-by-usual-hider");
2291 removeClass(toggle.parentNode, "collapsed");
2292 onEachLazy(toggle.childNodes, adjustToggle(false));
2296 // we are collapsing the impl block(s).
2298 var parentElem = toggle.parentNode;
2299 relatedDoc = parentElem;
2300 var docblock = relatedDoc.nextElementSibling;
2302 while (hasClass(relatedDoc, "impl-items") === false) {
2303 relatedDoc = relatedDoc.nextElementSibling;
2306 if (!relatedDoc && hasClass(docblock, "docblock") === false) {
2310 // Hide all functions, but not associated types/consts.
2312 if (mode === "toggle") {
2313 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2314 hasClass(docblock, "hidden-by-impl-hider")) {
2321 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2322 if (action === "show") {
2323 removeClass(relatedDoc, "fns-now-collapsed");
2324 removeClass(docblock, "hidden-by-usual-hider");
2325 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2326 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2327 } else if (action === "hide") {
2328 addClass(relatedDoc, "fns-now-collapsed");
2329 addClass(docblock, "hidden-by-usual-hider");
2330 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2331 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2336 function collapser(pageId, e, collapse) {
2337 // inherent impl ids are like "impl" or impl-<number>'.
2338 // they will never be hidden by default.
2339 var n = e.parentElement;
2340 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2341 // Automatically minimize all non-inherent impls
2342 if (collapse || hasClass(n, "impl")) {
2343 collapseDocs(e, "hide", pageId);
2348 function autoCollapse(pageId, collapse) {
2350 toggleAllDocs(pageId, true);
2351 } else if (getSettingValue("auto-hide-trait-implementations") !== "false") {
2352 var impl_list = document.getElementById("trait-implementations-list");
2354 if (impl_list !== null) {
2355 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2356 collapser(pageId, e, collapse);
2360 var blanket_list = document.getElementById("blanket-implementations-list");
2362 if (blanket_list !== null) {
2363 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2364 collapser(pageId, e, collapse);
2370 function insertAfter(newNode, referenceNode) {
2371 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2374 function createSimpleToggle(sectionIsCollapsed) {
2375 var toggle = document.createElement("a");
2376 toggle.href = "javascript:void(0)";
2377 toggle.className = "collapse-toggle";
2378 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2383 function createToggle(toggle, otherMessage, fontSize, extraClass, show) {
2384 var span = document.createElement("span");
2385 span.className = "toggle-label";
2387 span.style.display = "none";
2389 if (!otherMessage) {
2390 span.innerHTML = " Expand description";
2392 span.innerHTML = otherMessage;
2396 span.style.fontSize = fontSize;
2399 var mainToggle = toggle.cloneNode(true);
2400 mainToggle.appendChild(span);
2402 var wrapper = document.createElement("div");
2403 wrapper.className = "toggle-wrapper";
2405 addClass(wrapper, "collapsed");
2406 var inner = mainToggle.getElementsByClassName("inner");
2407 if (inner && inner.length > 0) {
2408 inner[0].innerHTML = "+";
2412 addClass(wrapper, extraClass);
2414 wrapper.appendChild(mainToggle);
2419 var toggles = document.getElementById(toggleAllDocsId);
2421 toggles.onclick = toggleAllDocs;
2424 var toggle = createSimpleToggle(false);
2425 var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
2426 var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false";
2427 var pageId = getPageId();
2429 var func = function(e) {
2430 var next = e.nextElementSibling;
2434 if (hasClass(next, "docblock") === true ||
2435 (hasClass(next, "stability") === true &&
2436 hasClass(next.nextElementSibling, "docblock") === true)) {
2437 var newToggle = toggle.cloneNode(true);
2438 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2439 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2440 collapseDocs(newToggle, "hide", pageId);
2445 var funcImpl = function(e) {
2446 var next = e.nextElementSibling;
2447 if (next && hasClass(next, "docblock")) {
2448 next = next.nextElementSibling;
2453 if (hasClass(e, "impl") &&
2454 (next.getElementsByClassName("method").length > 0 ||
2455 next.getElementsByClassName("associatedconstant").length > 0)) {
2456 var newToggle = toggle.cloneNode(true);
2457 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2458 // In case the option "auto-collapse implementors" is not set to false, we collapse
2459 // all implementors.
2460 if (hideImplementors === true && e.parentNode.id === "implementors-list") {
2461 collapseDocs(newToggle, "hide", pageId);
2466 onEachLazy(document.getElementsByClassName("method"), func);
2467 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2468 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2469 var impl_call = function() {};
2470 if (hideMethodDocs === true) {
2471 impl_call = function(e, newToggle) {
2472 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2473 // Automatically minimize all non-inherent impls
2474 if (hasClass(e, "impl") === true) {
2475 collapseDocs(newToggle, "hide", pageId);
2480 var newToggle = document.createElement("a");
2481 newToggle.href = "javascript:void(0)";
2482 newToggle.className = "collapse-toggle hidden-default collapsed";
2483 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2484 "</span>] Show hidden undocumented items";
2485 function toggleClicked() {
2486 if (hasClass(this, "collapsed")) {
2487 removeClass(this, "collapsed");
2488 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2489 if (hasClass(x, "content") === false) {
2490 removeClass(x, "hidden");
2494 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2495 "</span>] Hide undocumented items";
2497 addClass(this, "collapsed");
2498 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2499 if (hasClass(x, "content") === false) {
2500 addClass(x, "hidden");
2501 removeClass(x, "x");
2504 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2505 "</span>] Show hidden undocumented items";
2508 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2509 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2510 var hiddenElems = e.getElementsByClassName("hidden");
2511 var needToggle = false;
2513 var hlength = hiddenElems.length;
2514 for (var i = 0; i < hlength; ++i) {
2515 if (hasClass(hiddenElems[i], "content") === false &&
2516 hasClass(hiddenElems[i], "docblock") === false) {
2521 if (needToggle === true) {
2522 var inner_toggle = newToggle.cloneNode(true);
2523 inner_toggle.onclick = toggleClicked;
2524 e.insertBefore(inner_toggle, e.firstChild);
2525 impl_call(e.previousSibling, inner_toggle);
2529 var currentType = document.getElementsByClassName("type-decl")[0];
2530 var className = null;
2532 currentType = currentType.getElementsByClassName("rust")[0];
2534 currentType.classList.forEach(function(item) {
2535 if (item !== "main") {
2542 var showItemDeclarations = getSettingValue("auto-hide-" + className);
2543 if (showItemDeclarations === null) {
2544 if (className === "enum" || className === "macro") {
2545 showItemDeclarations = "false";
2546 } else if (className === "struct" || className === "union" || className === "trait") {
2547 showItemDeclarations = "true";
2549 // In case we found an unknown type, we just use the "parent" value.
2550 showItemDeclarations = getSettingValue("auto-hide-declarations");
2553 showItemDeclarations = showItemDeclarations === "false";
2554 function buildToggleWrapper(e) {
2555 if (hasClass(e, "autohide")) {
2556 var wrap = e.previousElementSibling;
2557 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2558 var inner_toggle = wrap.childNodes[0];
2559 var extra = e.childNodes[0].tagName === "H3";
2561 e.style.display = "none";
2562 addClass(wrap, "collapsed");
2563 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2564 e.innerHTML = labelForToggleButton(true);
2566 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2567 e.style.display = "inline-block";
2568 if (extra === true) {
2569 e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2574 if (e.parentNode.id === "main") {
2575 var otherMessage = "";
2579 if (hasClass(e, "type-decl")) {
2581 otherMessage = " Show declaration";
2582 if (showItemDeclarations === false) {
2583 extraClass = "collapsed";
2585 } else if (hasClass(e, "sub-variant")) {
2586 otherMessage = " Show fields";
2587 } else if (hasClass(e, "non-exhaustive")) {
2588 otherMessage = " This ";
2589 if (hasClass(e, "non-exhaustive-struct")) {
2590 otherMessage += "struct";
2591 } else if (hasClass(e, "non-exhaustive-enum")) {
2592 otherMessage += "enum";
2593 } else if (hasClass(e, "non-exhaustive-variant")) {
2594 otherMessage += "enum variant";
2595 } else if (hasClass(e, "non-exhaustive-type")) {
2596 otherMessage += "type";
2598 otherMessage += " is marked as non-exhaustive";
2599 } else if (hasClass(e.childNodes[0], "impl-items")) {
2600 extraClass = "marg-left";
2603 e.parentNode.insertBefore(
2609 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2611 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2612 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2614 if (hasClass(e, "non-exhaustive") === true) {
2615 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2620 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2621 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2622 var pageId = getPageId();
2624 autoCollapse(pageId, getSettingValue("collapse") === "true");
2626 if (pageId !== null) {
2627 expandSection(pageId);
2631 function createToggleWrapper(tog) {
2632 var span = document.createElement("span");
2633 span.className = "toggle-label";
2634 span.style.display = "none";
2635 span.innerHTML = " Expand attributes";
2636 tog.appendChild(span);
2638 var wrapper = document.createElement("div");
2639 wrapper.className = "toggle-wrapper toggle-attributes";
2640 wrapper.appendChild(tog);
2645 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2646 var itemAttributesFunc = function() {};
2647 if (getSettingValue("auto-hide-attributes") !== "false") {
2648 itemAttributesFunc = function(x) {
2649 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2652 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2653 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2654 var attr_tog = attributesToggle.cloneNode(true);
2655 if (hasClass(i_e, "top-attr") === true) {
2656 addClass(attr_tog, "top-attr");
2658 i_e.parentNode.insertBefore(attr_tog, i_e);
2659 itemAttributesFunc(i_e);
2664 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2665 var lineNumbersFunc = function() {};
2666 if (getSettingValue("line-numbers") === "true") {
2667 lineNumbersFunc = function(x) {
2668 var count = x.textContent.split("\n").length;
2670 for (var i = 0; i < count; ++i) {
2673 var node = document.createElement("pre");
2674 addClass(node, "line-number");
2675 node.innerHTML = elems.join("\n");
2676 x.parentNode.insertBefore(node, x);
2679 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2680 if (hasClass(e, "compile_fail")) {
2681 e.addEventListener("mouseover", function() {
2682 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2684 e.addEventListener("mouseout", function() {
2685 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2687 } else if (hasClass(e, "ignore")) {
2688 e.addEventListener("mouseover", function() {
2689 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2691 e.addEventListener("mouseout", function() {
2692 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2699 onEachLazy(document.getElementsByClassName("notable-traits"), function(e) {
2700 e.onclick = function() {
2701 this.getElementsByClassName('notable-traits-tooltiptext')[0]
2702 .classList.toggle("force-tooltip");
2706 // In the search display, allows to switch between tabs.
2707 function printTab(nb) {
2708 if (nb === 0 || nb === 1 || nb === 2) {
2712 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2713 if (nb_copy === 0) {
2714 addClass(elem, "selected");
2716 removeClass(elem, "selected");
2720 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2722 elem.style.display = "";
2724 elem.style.display = "none";
2730 function putBackSearch(search_input) {
2731 var search = getSearchElement();
2732 if (search_input.value !== "" && hasClass(search, "hidden")) {
2733 showSearchResults(search);
2734 if (browserSupportsHistoryApi()) {
2735 history.replaceState(search_input.value,
2737 "?search=" + encodeURIComponent(search_input.value));
2742 function getSearchLoadingText() {
2743 return "Loading search results...";
2747 search_input.onfocus = function() {
2748 putBackSearch(this);
2752 var params = getQueryStringParams();
2753 if (params && params.search) {
2754 var search = getSearchElement();
2755 search.innerHTML = "<h3 style=\"text-align: center;\">" + getSearchLoadingText() + "</h3>";
2756 showSearchResults(search);
2759 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2761 sidebar_menu.onclick = function() {
2762 var sidebar = document.getElementsByClassName("sidebar")[0];
2763 if (hasClass(sidebar, "mobile") === true) {
2772 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2775 onEachLazy(main.childNodes, function(e) {
2776 // Unhide the actual content once loading is complete. Headers get
2777 // flex treatment for their horizontal layout, divs get block treatment
2778 // for vertical layout (column-oriented flex layout for divs caused
2779 // errors in mobile browsers).
2780 if (e.tagName === "H2" || e.tagName === "H3") {
2781 var nextTagName = e.nextElementSibling.tagName;
2782 if (nextTagName == "H2" || nextTagName == "H3") {
2783 e.nextElementSibling.style.display = "flex";
2785 e.nextElementSibling.style.display = "block";
2791 function enableSearchInput() {
2793 search_input.removeAttribute('disabled');
2797 window.addSearchOptions = function(crates) {
2798 var elem = document.getElementById("crate-search");
2801 enableSearchInput();
2804 var crates_text = [];
2805 if (Object.keys(crates).length > 1) {
2806 for (var crate in crates) {
2807 if (hasOwnProperty(crates, crate)) {
2808 crates_text.push(crate);
2812 crates_text.sort(function(a, b) {
2813 var lower_a = a.toLowerCase();
2814 var lower_b = b.toLowerCase();
2816 if (lower_a < lower_b) {
2818 } else if (lower_a > lower_b) {
2823 var savedCrate = getSettingValue("saved-filter-crate");
2824 for (var i = 0; i < crates_text.length; ++i) {
2825 var option = document.createElement("option");
2826 option.value = crates_text[i];
2827 option.innerText = crates_text[i];
2828 elem.appendChild(option);
2829 // Set the crate filter from saved storage, if the current page has the saved crate
2832 // If not, ignore the crate filter -- we want to support filtering for crates on sites
2833 // like doc.rust-lang.org where the crates may differ from page to page while on the
2835 if (crates_text[i] === savedCrate) {
2836 elem.value = savedCrate;
2839 enableSearchInput();
2842 function buildHelperPopup() {
2843 var popup = document.createElement("aside");
2844 addClass(popup, "hidden");
2847 var book_info = document.createElement("span");
2848 book_info.innerHTML = "You can find more information in \
2849 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
2851 var container = document.createElement("div");
2853 ["?", "Show this help dialog"],
2854 ["S", "Focus the search field"],
2855 ["↑", "Move up in search results"],
2856 ["↓", "Move down in search results"],
2857 ["↹", "Switch tab"],
2858 ["⏎", "Go to active search result"],
2859 ["+", "Expand all sections"],
2860 ["-", "Collapse all sections"],
2861 ].map(x => "<dt><kbd>" + x[0] + "</kbd></dt><dd>" + x[1] + "</dd>").join("");
2862 var div_shortcuts = document.createElement("div");
2863 addClass(div_shortcuts, "shortcuts");
2864 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2867 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2868 restrict the search to a given item kind.",
2869 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
2870 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
2871 and <code>const</code>.",
2872 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
2873 <code>* -> vec</code>)",
2874 "Search multiple things at once by splitting your query with comma (e.g., \
2875 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
2876 "You can look for items with an exact name by putting double quotes around \
2877 your request: <code>\"string\"</code>",
2878 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
2879 ].map(x => "<p>" + x + "</p>").join("");
2880 var div_infos = document.createElement("div");
2881 addClass(div_infos, "infos");
2882 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2884 container.appendChild(book_info);
2885 container.appendChild(div_shortcuts);
2886 container.appendChild(div_infos);
2888 popup.appendChild(container);
2889 insertAfter(popup, getSearchElement());
2890 // So that it's only built once and then it'll do nothing when called!
2891 buildHelperPopup = function() {};
2895 window.onhashchange = onHashChange;
2898 // This is required in firefox. Explanations: when going back in the history, firefox doesn't re-run
2899 // the JS, therefore preventing rustdoc from setting a few things required to be able to reload the
2900 // previous search results (if you navigated to a search result with the keyboard, pressed enter on
2901 // it to navigate to that result, and then came back to this page).
2902 window.onunload = function(){};