2 /* global ALIASES, currentCrate, rootPath */
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global isHidden onEach, removeClass, updateLocalStorage */
8 if (!String.prototype.startsWith) {
9 String.prototype.startsWith = function(searchString, position) {
10 position = position || 0;
11 return this.indexOf(searchString, position) === position;
14 if (!String.prototype.endsWith) {
15 String.prototype.endsWith = function(suffix, length) {
16 var l = length || this.length;
17 return this.indexOf(suffix, l - suffix.length) !== -1;
21 if (!DOMTokenList.prototype.add) {
22 DOMTokenList.prototype.add = function(className) {
23 if (className && !hasClass(this, className)) {
24 if (this.className && this.className.length > 0) {
25 this.className += " " + className;
27 this.className = className;
33 if (!DOMTokenList.prototype.remove) {
34 DOMTokenList.prototype.remove = function(className) {
35 if (className && this.className) {
36 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
45 // This mapping table should match the discriminants of
46 // `rustdoc::html::item_type::ItemType` type in Rust.
47 var itemTypes = ["mod",
73 var search_input = document.getElementsByClassName("search-input")[0];
75 // On the search screen, so you remain on the last tab you opened.
78 // 1 for "In Parameters"
79 // 2 for "In Return Types"
82 var titleBeforeSearch = document.title;
84 function getPageId() {
85 var id = document.location.href.split("#")[1];
87 return id.split("?")[0].split("&")[0];
92 function showSidebar() {
93 var elems = document.getElementsByClassName("sidebar-elems")[0];
95 addClass(elems, "show-it");
97 var sidebar = document.getElementsByClassName("sidebar")[0];
99 addClass(sidebar, "mobile");
100 var filler = document.getElementById("sidebar-filler");
102 var div = document.createElement("div");
103 div.id = "sidebar-filler";
104 sidebar.appendChild(div);
107 var themePicker = document.getElementsByClassName("theme-picker");
108 if (themePicker && themePicker.length > 0) {
109 themePicker[0].style.display = "none";
113 function hideSidebar() {
114 var elems = document.getElementsByClassName("sidebar-elems")[0];
116 removeClass(elems, "show-it");
118 var sidebar = document.getElementsByClassName("sidebar")[0];
119 removeClass(sidebar, "mobile");
120 var filler = document.getElementById("sidebar-filler");
124 document.getElementsByTagName("body")[0].style.marginTop = "";
125 var themePicker = document.getElementsByClassName("theme-picker");
126 if (themePicker && themePicker.length > 0) {
127 themePicker[0].style.display = null;
131 // used for special search precedence
132 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
133 var TY_KEYWORD = itemTypes.indexOf("keyword");
135 onEachLazy(document.getElementsByClassName("js-only"), function(e) {
136 removeClass(e, "js-only");
139 function getQueryStringParams() {
141 window.location.search.substring(1).split("&").
143 var pair = s.split("=");
144 params[decodeURIComponent(pair[0])] =
145 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
150 function browserSupportsHistoryApi() {
151 return window.history && typeof window.history.pushState === "function";
154 var main = document.getElementById("main");
156 function highlightSourceLines(ev) {
157 // If we're in mobile mode, we should add the sidebar in any case.
160 var search = document.getElementById("search");
161 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
163 from = parseInt(match[1], 10);
164 to = Math.min(50000, parseInt(match[2] || match[1], 10));
165 from = Math.min(from, to);
166 elem = document.getElementById(from);
171 var x = document.getElementById(from);
176 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
177 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
178 removeClass(i_e, "line-highlighted");
181 for (i = from; i <= to; ++i) {
182 addClass(document.getElementById(i), "line-highlighted");
184 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
185 addClass(search, "hidden");
186 removeClass(main, "hidden");
187 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
188 if (browserSupportsHistoryApi()) {
189 history.replaceState(hash, "", "?search=#" + hash);
191 elem = document.getElementById(hash);
193 elem.scrollIntoView();
198 function expandSection(id) {
199 var elem = document.getElementById(id);
200 if (elem && isHidden(elem)) {
201 var h3 = elem.parentNode.previousElementSibling;
202 if (h3 && h3.tagName !== "H3") {
203 h3 = h3.previousElementSibling; // skip div.docblock
207 var collapses = h3.getElementsByClassName("collapse-toggle");
208 if (collapses.length > 0) {
209 // The element is not visible, we need to make it appear!
210 collapseDocs(collapses[0], "show");
216 highlightSourceLines(null);
217 window.onhashchange = highlightSourceLines;
219 // Gets the human-readable string for the virtual-key code of the
220 // given KeyboardEvent, ev.
222 // This function is meant as a polyfill for KeyboardEvent#key,
223 // since it is not supported in Trident. We also test for
224 // KeyboardEvent#keyCode because the handleShortcut handler is
225 // also registered for the keydown event, because Blink doesn't fire
226 // keypress on hitting the Escape key.
228 // So I guess you could say things are getting pretty interoperable.
229 function getVirtualKey(ev) {
230 if ("key" in ev && typeof ev.key != "undefined") {
234 var c = ev.charCode || ev.keyCode;
238 return String.fromCharCode(c);
241 function displayHelp(display, ev, help) {
242 if (display === true) {
243 if (hasClass(help, "hidden")) {
245 removeClass(help, "hidden");
246 addClass(document.body, "blur");
248 } else if (hasClass(help, "hidden") === false) {
250 addClass(help, "hidden");
251 removeClass(document.body, "blur");
255 function handleEscape(ev, help) {
257 var search = document.getElementById("search");
258 if (hasClass(help, "hidden") === false) {
259 displayHelp(false, ev, help);
260 } else if (hasClass(search, "hidden") === false) {
262 addClass(search, "hidden");
263 removeClass(main, "hidden");
264 document.title = titleBeforeSearch;
269 function handleShortcut(ev) {
270 // Don't interfere with browser shortcuts
271 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
275 var help = document.getElementById("help");
276 if (document.activeElement.tagName === "INPUT") {
277 switch (getVirtualKey(ev)) {
279 handleEscape(ev, help);
283 switch (getVirtualKey(ev)) {
285 handleEscape(ev, help);
290 displayHelp(false, ev, help);
305 displayHelp(true, ev, help);
312 function findParentElement(elem, tagName) {
314 if (elem && elem.tagName === tagName) {
317 elem = elem.parentNode;
322 document.onkeypress = handleShortcut;
323 document.onkeydown = handleShortcut;
324 document.onclick = function(ev) {
325 if (hasClass(ev.target, "collapse-toggle")) {
326 collapseDocs(ev.target, "toggle");
327 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
328 collapseDocs(ev.target.parentNode, "toggle");
329 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
332 var set_fragment = function(name) {
333 if (browserSupportsHistoryApi()) {
334 history.replaceState(null, null, "#" + name);
337 location.replace("#" + name);
341 var cur_id = parseInt(ev.target.id, 10);
343 if (ev.shiftKey && prev_id) {
344 if (prev_id > cur_id) {
350 set_fragment(prev_id + "-" + cur_id);
354 set_fragment(cur_id);
356 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
357 addClass(document.getElementById("help"), "hidden");
358 removeClass(document.body, "blur");
360 // Making a collapsed element visible on onhashchange seems
362 var a = findParentElement(ev.target, "A");
364 expandSection(a.hash.replace(/^#/, ""));
369 var x = document.getElementsByClassName("version-selector");
371 x[0].onchange = function() {
373 url = document.location.href,
375 len = rootPath.match(/\.\.\//g).length + 1;
377 for (i = 0; i < len; ++i) {
378 match = url.match(/\/[^\/]*$/);
380 stripped = match[0] + stripped;
382 url = url.substring(0, url.length - match[0].length);
385 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
387 document.location.href = url;
392 * A function to compute the Levenshtein distance between two strings
393 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
394 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
395 * This code is an unmodified version of the code written by Marco de Wit
396 * and was found at http://stackoverflow.com/a/18514751/745719
398 var levenshtein_row2 = [];
399 function levenshtein(s1, s2) {
403 var s1_len = s1.length, s2_len = s2.length;
404 if (s1_len && s2_len) {
405 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
406 while (i1 < s1_len) {
409 while (i2 < s2_len) {
410 c2 = s2.charCodeAt(i2);
414 for (i1 = 0; i1 < s1_len; ++i1) {
415 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
417 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
423 return s1_len + s2_len;
426 function initSearch(rawSearchIndex) {
427 var currentResults, index, searchIndex;
428 var MAX_LEV_DISTANCE = 3;
429 var MAX_RESULTS = 200;
430 var GENERICS_DATA = 1;
434 var params = getQueryStringParams();
436 // Populate search bar with query string search term when provided,
437 // but only if the input bar is empty. This avoid the obnoxious issue
438 // where you start trying to do a search, and the index loads, and
439 // suddenly your search is gone!
440 if (search_input.value === "") {
441 search_input.value = params.search || "";
445 * Executes the query and builds an index of results
446 * @param {[Object]} query [The user query]
447 * @param {[type]} searchWords [The list of search words to query
449 * @param {[type]} filterCrates [Crate to search in if defined]
450 * @return {[type]} [A search index of results]
452 function execQuery(query, searchWords, filterCrates) {
453 function itemTypeFromName(typename) {
454 var length = itemTypes.length;
455 for (var i = 0; i < length; ++i) {
456 if (itemTypes[i] === typename) {
463 var valLower = query.query.toLowerCase(),
465 typeFilter = itemTypeFromName(query.type),
466 results = {}, results_in_args = {}, results_returned = {},
467 split = valLower.split("::");
469 var length = split.length;
470 for (var z = 0; z < length; ++z) {
471 if (split[z] === "") {
477 function transformResults(results, isType) {
479 var length = results.length;
480 for (var i = 0; i < length; ++i) {
481 if (results[i].id > -1) {
482 var obj = searchIndex[results[i].id];
483 obj.lev = results[i].lev;
484 if (isType !== true || obj.type) {
485 var res = buildHrefAndPath(obj);
486 obj.displayPath = pathSplitter(res[0]);
487 obj.fullPath = obj.displayPath + obj.name;
488 // To be sure than it some items aren't considered as duplicate.
489 obj.fullPath += "|" + obj.ty;
492 if (out.length >= MAX_RESULTS) {
501 function sortResults(results, isType) {
503 for (var entry in results) {
504 if (results.hasOwnProperty(entry)) {
505 ar.push(results[entry]);
510 var nresults = results.length;
511 for (i = 0; i < nresults; ++i) {
512 results[i].word = searchWords[results[i].id];
513 results[i].item = searchIndex[results[i].id] || {};
515 // if there are no results then return to default and fail
516 if (results.length === 0) {
520 results.sort(function(aaa, bbb) {
523 // Sort by non levenshtein results and then levenshtein results by the distance
524 // (less changes required to match means higher rankings)
527 if (a !== b) { return a - b; }
529 // sort by crate (non-current crate goes later)
530 a = (aaa.item.crate !== window.currentCrate);
531 b = (bbb.item.crate !== window.currentCrate);
532 if (a !== b) { return a - b; }
534 // sort by exact match (mismatch goes later)
535 a = (aaa.word !== valLower);
536 b = (bbb.word !== valLower);
537 if (a !== b) { return a - b; }
539 // sort by item name length (longer goes later)
542 if (a !== b) { return a - b; }
544 // sort by item name (lexicographically larger goes later)
547 if (a !== b) { return (a > b ? +1 : -1); }
549 // sort by index of keyword in item name (no literal occurrence goes later)
552 if (a !== b) { return a - b; }
553 // (later literal occurrence, if any, goes later)
556 if (a !== b) { return a - b; }
558 // special precedence for primitive and keyword pages
559 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
560 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
563 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
564 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
568 // sort by description (no description goes later)
569 a = (aaa.item.desc === "");
570 b = (bbb.item.desc === "");
571 if (a !== b) { return a - b; }
573 // sort by type (later occurrence in `itemTypes` goes later)
576 if (a !== b) { return a - b; }
578 // sort by path (lexicographically larger goes later)
581 if (a !== b) { return (a > b ? +1 : -1); }
587 var length = results.length;
588 for (i = 0; i < length; ++i) {
589 var result = results[i];
591 // this validation does not make sense when searching by types
592 if (result.dontValidate) {
595 var name = result.item.name.toLowerCase(),
596 path = result.item.path.toLowerCase(),
597 parent = result.item.parent;
599 if (isType !== true &&
600 validateResult(name, path, split, parent) === false)
605 return transformResults(results);
608 function extractGenerics(val) {
609 val = val.toLowerCase();
610 if (val.indexOf("<") !== -1) {
611 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
613 name: val.substring(0, val.indexOf("<")),
614 generics: values.split(/\s*,\s*/),
623 function checkGenerics(obj, val) {
624 // The names match, but we need to be sure that all generics kinda
626 var lev_distance = MAX_LEV_DISTANCE + 1;
627 if (val.generics.length > 0) {
628 if (obj.length > GENERICS_DATA &&
629 obj[GENERICS_DATA].length >= val.generics.length) {
630 var elems = obj[GENERICS_DATA].slice(0);
633 // We need to find the type that matches the most to remove it in order
635 var vlength = val.generics.length;
636 for (var y = 0; y < vlength; ++y) {
637 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
638 var elength = elems.length;
639 for (var x = 0; x < elength; ++x) {
640 var tmp_lev = levenshtein(elems[x], val.generics[y]);
641 if (tmp_lev < lev.lev) {
646 if (lev.pos !== -1) {
647 elems.splice(lev.pos, 1);
648 lev_distance = Math.min(lev.lev, lev_distance);
652 return MAX_LEV_DISTANCE + 1;
655 return Math.ceil(total / done);
658 return MAX_LEV_DISTANCE + 1;
661 // Check for type name and type generics (if any).
662 function checkType(obj, val, literalSearch) {
663 var lev_distance = MAX_LEV_DISTANCE + 1;
665 if (obj[NAME] === val.name) {
666 if (literalSearch === true) {
667 if (val.generics && val.generics.length !== 0) {
668 if (obj.length > GENERICS_DATA &&
669 obj[GENERICS_DATA].length >= val.generics.length) {
670 var elems = obj[GENERICS_DATA].slice(0);
673 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
675 for (x = 0; allFound === false && x < elems.length; ++x) {
676 allFound = elems[x] === val.generics[y];
678 if (allFound === true) {
679 elems.splice(x - 1, 1);
682 if (allFound === true) {
691 // If the type has generics but don't match, then it won't return at this point.
692 // Otherwise, `checkGenerics` will return 0 and it'll return.
693 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
694 var tmp_lev = checkGenerics(obj, val);
695 if (tmp_lev <= MAX_LEV_DISTANCE) {
702 // Names didn't match so let's check if one of the generic types could.
703 if (literalSearch === true) {
704 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
705 var length = obj[GENERICS_DATA].length;
706 for (x = 0; x < length; ++x) {
707 if (obj[GENERICS_DATA][x] === val.name) {
714 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
715 if (lev_distance <= MAX_LEV_DISTANCE) {
716 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
717 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
718 // We can check if the type we're looking for is inside the generics!
719 var olength = obj[GENERICS_DATA].length;
720 for (x = 0; x < olength; ++x) {
721 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
725 // Now whatever happens, the returned distance is "less good" so we should mark it
726 // as such, and so we add 1 to the distance to make it "less good".
727 return lev_distance + 1;
730 function findArg(obj, val, literalSearch) {
731 var lev_distance = MAX_LEV_DISTANCE + 1;
733 if (obj && obj.type && obj.type[INPUTS_DATA] &&
734 obj.type[INPUTS_DATA].length > 0) {
735 var length = obj.type[INPUTS_DATA].length;
736 for (var i = 0; i < length; i++) {
737 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
738 if (literalSearch === true && tmp === true) {
741 lev_distance = Math.min(tmp, lev_distance);
742 if (lev_distance === 0) {
747 return literalSearch === true ? false : lev_distance;
750 function checkReturned(obj, val, literalSearch) {
751 var lev_distance = MAX_LEV_DISTANCE + 1;
753 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
754 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
755 if (literalSearch === true && tmp === true) {
758 lev_distance = Math.min(tmp, lev_distance);
759 if (lev_distance === 0) {
763 return literalSearch === true ? false : lev_distance;
766 function checkPath(contains, lastElem, ty) {
767 if (contains.length === 0) {
770 var ret_lev = MAX_LEV_DISTANCE + 1;
771 var path = ty.path.split("::");
773 if (ty.parent && ty.parent.name) {
774 path.push(ty.parent.name.toLowerCase());
777 var length = path.length;
778 var clength = contains.length;
779 if (clength > length) {
780 return MAX_LEV_DISTANCE + 1;
782 for (var i = 0; i < length; ++i) {
783 if (i + clength > length) {
788 for (var x = 0; x < clength; ++x) {
789 var lev = levenshtein(path[i + x], contains[x]);
790 if (lev > MAX_LEV_DISTANCE) {
796 if (aborted === false) {
797 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
803 function typePassesFilter(filter, type) {
805 if (filter < 0) return true;
808 if (filter === type) return true;
810 // Match related items
811 var name = itemTypes[type];
812 switch (itemTypes[filter]) {
814 return (name == "associatedconstant");
816 return (name == "method" || name == "tymethod");
818 return (name == "primitive" || name == "keyword");
825 function generateId(ty) {
826 if (ty.parent && ty.parent.name) {
827 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
829 return itemTypes[ty.ty] + ty.path + ty.name;
832 // quoted values mean literal search
833 var nSearchWords = searchWords.length;
839 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
840 val.charAt(val.length - 1) === val.charAt(0))
842 val = extractGenerics(val.substr(1, val.length - 2));
843 for (i = 0; i < nSearchWords; ++i) {
844 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
847 in_args = findArg(searchIndex[i], val, true);
848 returned = checkReturned(searchIndex[i], val, true);
850 fullId = generateId(ty);
852 if (searchWords[i] === val.name) {
853 // filter type: ... queries
854 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
855 results[fullId] === undefined)
857 results[fullId] = {id: i, index: -1};
859 } else if ((in_args === true || returned === true) &&
860 typePassesFilter(typeFilter, searchIndex[i].ty)) {
861 if (in_args === true || returned === true) {
862 if (in_args === true) {
863 results_in_args[fullId] = {
869 if (returned === true) {
870 results_returned[fullId] = {
885 query.inputs = [val];
889 } else if (val.search("->") > -1) {
890 var trimmer = function(s) { return s.trim(); };
891 var parts = val.split("->").map(trimmer);
892 var input = parts[0];
893 // sort inputs so that order does not matter
894 var inputs = input.split(",").map(trimmer).sort();
895 for (i = 0; i < inputs.length; ++i) {
896 inputs[i] = extractGenerics(inputs[i]);
898 var output = extractGenerics(parts[1]);
900 for (i = 0; i < nSearchWords; ++i) {
901 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
904 var type = searchIndex[i].type;
909 fullId = generateId(ty);
911 // allow searching for void (no output) functions as well
912 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
913 returned = checkReturned(ty, output, true);
914 if (output.name === "*" || returned === true) {
922 for (var it = 0; allFound === true && it < inputs.length; it++) {
923 allFound = checkType(type, inputs[it], true);
927 if (in_args === true) {
928 results_in_args[fullId] = {
934 if (returned === true) {
935 results_returned[fullId] = {
941 if (module === true) {
950 query.inputs = inputs.map(function(input) {
953 query.output = output.name;
955 query.inputs = [val];
958 // gather matching search results up to a certain maximum
959 val = val.replace(/\_/g, "");
961 var valGenerics = extractGenerics(val);
963 var paths = valLower.split("::");
965 for (j = 0; j < paths.length; ++j) {
966 if (paths[j] === "") {
971 val = paths[paths.length - 1];
972 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
974 for (j = 0; j < nSearchWords; ++j) {
978 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
983 if (paths.length > 1) {
984 lev = checkPath(contains, paths[paths.length - 1], ty);
985 if (lev > MAX_LEV_DISTANCE) {
987 } else if (lev > 0) {
992 returned = MAX_LEV_DISTANCE + 1;
993 in_args = MAX_LEV_DISTANCE + 1;
995 // we want lev results to go lower than others
996 lev = MAX_LEV_DISTANCE + 1;
997 fullId = generateId(ty);
999 if (searchWords[j].indexOf(split[i]) > -1 ||
1000 searchWords[j].indexOf(val) > -1 ||
1001 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1003 // filter type: ... queries
1004 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1005 index = searchWords[j].replace(/_/g, "").indexOf(val);
1008 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1009 if (typePassesFilter(typeFilter, ty.ty) === false) {
1010 lev = MAX_LEV_DISTANCE + 1;
1015 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1016 if (typePassesFilter(typeFilter, ty.ty) === false) {
1017 in_args = MAX_LEV_DISTANCE + 1;
1020 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1021 if (typePassesFilter(typeFilter, ty.ty) === false) {
1022 returned = MAX_LEV_DISTANCE + 1;
1027 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1028 if (val.length < 6) {
1034 if (in_args <= MAX_LEV_DISTANCE) {
1035 if (results_in_args[fullId] === undefined) {
1036 results_in_args[fullId] = {
1042 results_in_args[fullId].lev =
1043 Math.min(results_in_args[fullId].lev, in_args);
1045 if (returned <= MAX_LEV_DISTANCE) {
1046 if (results_returned[fullId] === undefined) {
1047 results_returned[fullId] = {
1053 results_returned[fullId].lev =
1054 Math.min(results_returned[fullId].lev, returned);
1056 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1057 if (index !== -1 && paths.length < 2) {
1060 if (results[fullId] === undefined) {
1067 results[fullId].lev = Math.min(results[fullId].lev, lev);
1073 "in_args": sortResults(results_in_args, true),
1074 "returned": sortResults(results_returned, true),
1075 "others": sortResults(results),
1077 if (ALIASES && ALIASES[window.currentCrate] &&
1078 ALIASES[window.currentCrate][query.raw]) {
1079 var aliases = ALIASES[window.currentCrate][query.raw];
1080 for (i = 0; i < aliases.length; ++i) {
1081 aliases[i].is_alias = true;
1082 aliases[i].alias = query.raw;
1083 aliases[i].path = aliases[i].p;
1084 var res = buildHrefAndPath(aliases[i]);
1085 aliases[i].displayPath = pathSplitter(res[0]);
1086 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1087 aliases[i].href = res[1];
1088 ret.others.unshift(aliases[i]);
1089 if (ret.others.length > MAX_RESULTS) {
1098 * Validate performs the following boolean logic. For example:
1099 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1100 * exists in (name || path || parent) OR => ("file" && "open") exists in
1103 * This could be written functionally, but I wanted to minimise
1104 * functions on stack.
1106 * @param {[string]} name [The name of the result]
1107 * @param {[string]} path [The path of the result]
1108 * @param {[string]} keys [The keys to be used (["file", "open"])]
1109 * @param {[object]} parent [The parent of the result]
1110 * @return {[boolean]} [Whether the result is valid or not]
1112 function validateResult(name, path, keys, parent) {
1113 for (var i = 0; i < keys.length; ++i) {
1114 // each check is for validation so we negate the conditions and invalidate
1116 // check for an exact name match
1117 name.indexOf(keys[i]) > -1 ||
1118 // then an exact path match
1119 path.indexOf(keys[i]) > -1 ||
1120 // next if there is a parent, check for exact parent match
1121 (parent !== undefined &&
1122 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1123 // lastly check to see if the name was a levenshtein match
1124 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1131 function getQuery(raw) {
1132 var matches, type, query;
1135 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1137 type = matches[1].replace(/^const$/, "constant");
1138 query = query.substring(matches[0].length);
1149 function initSearchNav() {
1152 var click_func = function(e) {
1154 // to retrieve the real "owner" of the event.
1155 while (el.tagName !== "TR") {
1158 var dst = e.target.getElementsByTagName("a");
1159 if (dst.length < 1) {
1163 if (window.location.pathname === dst.pathname) {
1164 addClass(document.getElementById("search"), "hidden");
1165 removeClass(main, "hidden");
1166 document.location.href = dst.href;
1169 var mouseover_func = function(e) {
1171 // to retrieve the real "owner" of the event.
1172 while (el.tagName !== "TR") {
1175 clearTimeout(hoverTimeout);
1176 hoverTimeout = setTimeout(function() {
1177 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1178 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1179 removeClass(i_e, "highlighted");
1182 addClass(el, "highlighted");
1185 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1186 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1187 i_e.onclick = click_func;
1188 i_e.onmouseover = mouseover_func;
1192 search_input.onkeydown = function(e) {
1193 // "actives" references the currently highlighted item in each search tab.
1194 // Each array in "actives" represents a tab.
1195 var actives = [[], [], []];
1196 // "current" is used to know which tab we're looking into.
1198 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1199 onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1200 actives[current].push(e);
1205 if (e.which === 38) { // up
1206 if (!actives[currentTab].length ||
1207 !actives[currentTab][0].previousElementSibling) {
1211 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1212 removeClass(actives[currentTab][0], "highlighted");
1213 } else if (e.which === 40) { // down
1214 if (!actives[currentTab].length) {
1215 var results = document.getElementsByClassName("search-results");
1216 if (results.length > 0) {
1217 var res = results[currentTab].getElementsByClassName("result");
1218 if (res.length > 0) {
1219 addClass(res[0], "highlighted");
1222 } else if (actives[currentTab][0].nextElementSibling) {
1223 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1224 removeClass(actives[currentTab][0], "highlighted");
1226 } else if (e.which === 13) { // return
1227 if (actives[currentTab].length) {
1228 document.location.href =
1229 actives[currentTab][0].getElementsByTagName("a")[0].href;
1231 } else if (e.which === 9) { // tab
1233 printTab(currentTab > 0 ? currentTab - 1 : 2);
1235 printTab(currentTab > 1 ? 0 : currentTab + 1);
1238 } else if (e.which === 16) { // shift
1239 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1240 } else if (e.which === 27) { // escape
1241 removeClass(actives[currentTab][0], "highlighted");
1242 search_input.value = "";
1244 } else if (actives[currentTab].length > 0) {
1245 removeClass(actives[currentTab][0], "highlighted");
1250 function buildHrefAndPath(item) {
1253 var type = itemTypes[item.ty];
1254 var name = item.name;
1256 if (type === "mod") {
1257 displayPath = item.path + "::";
1258 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1259 name + "/index.html";
1260 } else if (type === "primitive" || type === "keyword") {
1262 href = rootPath + item.path.replace(/::/g, "/") +
1263 "/" + type + "." + name + ".html";
1264 } else if (type === "externcrate") {
1266 href = rootPath + name + "/index.html";
1267 } else if (item.parent !== undefined) {
1268 var myparent = item.parent;
1269 var anchor = "#" + type + "." + name;
1270 var parentType = itemTypes[myparent.ty];
1271 if (parentType === "primitive") {
1272 displayPath = myparent.name + "::";
1274 displayPath = item.path + "::" + myparent.name + "::";
1276 href = rootPath + item.path.replace(/::/g, "/") +
1278 "." + myparent.name +
1281 displayPath = item.path + "::";
1282 href = rootPath + item.path.replace(/::/g, "/") +
1283 "/" + type + "." + name + ".html";
1285 return [displayPath, href];
1288 function escape(content) {
1289 var h1 = document.createElement("h1");
1290 h1.textContent = content;
1291 return h1.innerHTML;
1294 function pathSplitter(path) {
1295 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1296 if (tmp.endsWith("<span>")) {
1297 return tmp.slice(0, tmp.length - 6);
1302 function addTab(array, query, display) {
1303 var extraStyle = "";
1304 if (display === false) {
1305 extraStyle = " style=\"display: none;\"";
1309 var duplicates = {};
1311 if (array.length > 0) {
1312 output = "<table class=\"search-results\"" + extraStyle + ">";
1314 array.forEach(function(item) {
1318 type = itemTypes[item.ty];
1320 if (item.is_alias !== true) {
1321 if (duplicates[item.fullPath]) {
1324 duplicates[item.fullPath] = true;
1328 output += "<tr class=\"" + type + " result\"><td>" +
1329 "<a href=\"" + item.href + "\">" +
1330 (item.is_alias === true ?
1331 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1332 "class=\"grey\"><i> - see </i></span>") : "") +
1333 item.displayPath + "<span class=\"" + type + "\">" +
1334 name + "</span></a></td><td>" +
1335 "<a href=\"" + item.href + "\">" +
1336 "<span class=\"desc\">" + escape(item.desc) +
1337 " </span></a></td></tr>";
1339 output += "</table>";
1341 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1342 "Try on <a href=\"https://duckduckgo.com/?q=" +
1343 encodeURIComponent("rust " + query.query) +
1344 "\">DuckDuckGo</a>?<br/><br/>" +
1345 "Or try looking in one of these:<ul><li>The <a " +
1346 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1347 " for technical details about the language.</li><li><a " +
1348 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1349 "Example</a> for expository code examples.</a></li><li>The <a " +
1350 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1351 "introductions to language features and the language itself.</li><li><a " +
1352 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1353 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1355 return [output, length];
1358 function makeTabHeader(tabNb, text, nbElems) {
1359 if (currentTab === tabNb) {
1360 return "<div class=\"selected\">" + text +
1361 " <div class=\"count\">(" + nbElems + ")</div></div>";
1363 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1366 function showResults(results) {
1367 if (results.others.length === 1 &&
1368 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1369 var elem = document.createElement("a");
1370 elem.href = results.others[0].href;
1371 elem.style.display = "none";
1372 // For firefox, we need the element to be in the DOM so it can be clicked.
1373 document.body.appendChild(elem);
1376 var query = getQuery(search_input.value);
1378 currentResults = query.id;
1380 var ret_others = addTab(results.others, query);
1381 var ret_in_args = addTab(results.in_args, query, false);
1382 var ret_returned = addTab(results.returned, query, false);
1384 var output = "<h1>Results for " + escape(query.query) +
1385 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1386 "<div id=\"titles\">" +
1387 makeTabHeader(0, "In Names", ret_others[1]) +
1388 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1389 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1390 "</div><div id=\"results\">" +
1391 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1393 addClass(main, "hidden");
1394 var search = document.getElementById("search");
1395 removeClass(search, "hidden");
1396 search.innerHTML = output;
1397 var tds = search.getElementsByTagName("td");
1399 if (tds.length > 0) {
1400 td_width = tds[0].offsetWidth;
1402 var width = search.offsetWidth - 40 - td_width;
1403 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1404 e.style.width = width + "px";
1407 var elems = document.getElementById("titles").childNodes;
1408 elems[0].onclick = function() { printTab(0); };
1409 elems[1].onclick = function() { printTab(1); };
1410 elems[2].onclick = function() { printTab(2); };
1411 printTab(currentTab);
1414 function execSearch(query, searchWords, filterCrates) {
1415 function getSmallest(arrays, positions, notDuplicates) {
1418 for (var it = 0; it < positions.length; ++it) {
1419 if (arrays[it].length > positions[it] &&
1420 (start === null || start > arrays[it][positions[it]].lev) &&
1421 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1422 start = arrays[it][positions[it]].lev;
1428 function mergeArrays(arrays) {
1431 var notDuplicates = {};
1433 for (var x = 0; x < arrays.length; ++x) {
1436 while (ret.length < MAX_RESULTS) {
1437 var smallest = getSmallest(arrays, positions, notDuplicates);
1439 if (smallest === null) {
1442 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1443 if (arrays[x].length > positions[x] &&
1444 arrays[x][positions[x]].lev === smallest &&
1445 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1446 ret.push(arrays[x][positions[x]]);
1447 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1455 var queries = query.raw.split(",");
1462 for (var i = 0; i < queries.length; ++i) {
1463 query = queries[i].trim();
1464 if (query.length !== 0) {
1465 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1467 results.in_args.push(tmp.in_args);
1468 results.returned.push(tmp.returned);
1469 results.others.push(tmp.others);
1472 if (queries.length > 1) {
1474 "in_args": mergeArrays(results.in_args),
1475 "returned": mergeArrays(results.returned),
1476 "others": mergeArrays(results.others),
1480 "in_args": results.in_args[0],
1481 "returned": results.returned[0],
1482 "others": results.others[0],
1487 function getFilterCrates() {
1488 var elem = document.getElementById("crate-search");
1490 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1496 function search(e, forced) {
1497 var params = getQueryStringParams();
1498 var query = getQuery(search_input.value.trim());
1504 if (query.query.length === 0) {
1507 if (forced !== true && query.id === currentResults) {
1508 if (query.query.length > 0) {
1509 putBackSearch(search_input);
1514 // Update document title to maintain a meaningful browser history
1515 document.title = "Results for " + query.query + " - Rust";
1517 // Because searching is incremental by character, only the most
1518 // recent search query is added to the browser history.
1519 if (browserSupportsHistoryApi()) {
1520 if (!history.state && !params.search) {
1521 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1523 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1527 var filterCrates = getFilterCrates();
1528 showResults(execSearch(query, index, filterCrates), filterCrates);
1531 function buildIndex(rawSearchIndex) {
1533 var searchWords = [];
1536 for (var crate in rawSearchIndex) {
1537 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1539 searchWords.push(crate);
1542 ty: 1, // == ExternCrate
1545 desc: rawSearchIndex[crate].doc,
1549 // an array of [(Number) item type,
1551 // (String) full path or empty string for previous path,
1552 // (String) description,
1553 // (Number | null) the parent path index to `paths`]
1554 // (Object | null) the type of the function (if any)
1555 var items = rawSearchIndex[crate].i;
1556 // an array of [(Number) item type,
1558 var paths = rawSearchIndex[crate].p;
1560 // convert `paths` into an object form
1561 var len = paths.length;
1562 for (i = 0; i < len; ++i) {
1563 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1566 // convert `items` into an object form, and construct word indices.
1568 // before any analysis is performed lets gather the search terms to
1569 // search against apart from the rest of the data. This is a quick
1570 // operation that is cached for the life of the page state so that
1571 // all other search operations have access to this cached data for
1572 // faster analysis operations
1575 for (i = 0; i < len; ++i) {
1576 var rawRow = items[i];
1577 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1578 path: rawRow[2] || lastPath, desc: rawRow[3],
1579 parent: paths[rawRow[4]], type: rawRow[5]};
1580 searchIndex.push(row);
1581 if (typeof row.name === "string") {
1582 var word = row.name.toLowerCase();
1583 searchWords.push(word);
1585 searchWords.push("");
1587 lastPath = row.path;
1593 function startSearch() {
1595 var callback = function() {
1596 clearTimeout(searchTimeout);
1597 if (search_input.value.length === 0) {
1598 if (browserSupportsHistoryApi()) {
1599 history.replaceState("", "std - Rust", "?search=");
1601 if (hasClass(main, "content")) {
1602 removeClass(main, "hidden");
1604 var search_c = document.getElementById("search");
1605 if (hasClass(search_c, "content")) {
1606 addClass(search_c, "hidden");
1609 searchTimeout = setTimeout(search, 500);
1612 search_input.onkeyup = callback;
1613 search_input.oninput = callback;
1614 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1616 clearTimeout(searchTimeout);
1619 search_input.onchange = function(e) {
1620 // Do NOT e.preventDefault() here. It will prevent pasting.
1621 clearTimeout(searchTimeout);
1622 // zero-timeout necessary here because at the time of event handler execution the
1623 // pasted content is not in the input field yet. Shouldn’t make any difference for
1625 setTimeout(search, 0);
1627 search_input.onpaste = search_input.onchange;
1629 var selectCrate = document.getElementById('crate-search');
1631 selectCrate.onchange = function() {
1632 search(undefined, true);
1636 // Push and pop states are used to add search results to the browser
1638 if (browserSupportsHistoryApi()) {
1639 // Store the previous <title> so we can revert back to it later.
1640 var previousTitle = document.title;
1642 window.onpopstate = function(e) {
1643 var params = getQueryStringParams();
1644 // When browsing back from search results the main page
1645 // visibility must be reset.
1646 if (!params.search) {
1647 if (hasClass(main, "content")) {
1648 removeClass(main, "hidden");
1650 var search_c = document.getElementById("search");
1651 if (hasClass(search_c, "content")) {
1652 addClass(search_c, "hidden");
1655 // Revert to the previous title manually since the History
1656 // API ignores the title parameter.
1657 document.title = previousTitle;
1658 // When browsing forward to search results the previous
1659 // search will be repeated, so the currentResults are
1660 // cleared to ensure the search is successful.
1661 currentResults = null;
1662 // Synchronize search bar with query string state and
1663 // perform the search. This will empty the bar if there's
1664 // nothing there, which lets you really go back to a
1665 // previous state with nothing in the bar.
1666 if (params.search) {
1667 search_input.value = params.search;
1669 search_input.value = "";
1671 // Some browsers fire "onpopstate" for every page load
1672 // (Chrome), while others fire the event only when actually
1673 // popping a state (Firefox), which is why search() is
1674 // called both here and at the end of the startSearch()
1682 index = buildIndex(rawSearchIndex);
1685 // Draw a convenient sidebar of known crates if we have a listing
1686 if (rootPath === "../" || rootPath === "./") {
1687 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1689 var div = document.createElement("div");
1690 div.className = "block crate";
1691 div.innerHTML = "<h3>Crates</h3>";
1692 var ul = document.createElement("ul");
1693 div.appendChild(ul);
1696 for (var crate in rawSearchIndex) {
1697 if (!rawSearchIndex.hasOwnProperty(crate)) {
1703 for (var i = 0; i < crates.length; ++i) {
1704 var klass = "crate";
1705 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1706 klass += " current";
1708 var link = document.createElement("a");
1709 link.href = rootPath + crates[i] + "/index.html";
1710 link.title = rawSearchIndex[crates[i]].doc;
1711 link.className = klass;
1712 link.textContent = crates[i];
1714 var li = document.createElement("li");
1715 li.appendChild(link);
1718 sidebar.appendChild(div);
1723 window.initSearch = initSearch;
1725 // delayed sidebar rendering.
1726 function initSidebarItems(items) {
1727 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1728 var current = window.sidebarCurrent;
1730 function block(shortty, longty) {
1731 var filtered = items[shortty];
1736 var div = document.createElement("div");
1737 div.className = "block " + shortty;
1738 var h3 = document.createElement("h3");
1739 h3.textContent = longty;
1740 div.appendChild(h3);
1741 var ul = document.createElement("ul");
1743 var length = filtered.length;
1744 for (var i = 0; i < length; ++i) {
1745 var item = filtered[i];
1747 var desc = item[1]; // can be null
1749 var klass = shortty;
1750 if (name === current.name && shortty === current.ty) {
1751 klass += " current";
1754 if (shortty === "mod") {
1755 path = name + "/index.html";
1757 path = shortty + "." + name + ".html";
1759 var link = document.createElement("a");
1760 link.href = current.relpath + path;
1762 link.className = klass;
1763 link.textContent = name;
1764 var li = document.createElement("li");
1765 li.appendChild(link);
1768 div.appendChild(ul);
1770 sidebar.appendChild(div);
1774 block("primitive", "Primitive Types");
1775 block("mod", "Modules");
1776 block("macro", "Macros");
1777 block("struct", "Structs");
1778 block("enum", "Enums");
1779 block("union", "Unions");
1780 block("constant", "Constants");
1781 block("static", "Statics");
1782 block("trait", "Traits");
1783 block("fn", "Functions");
1784 block("type", "Type Definitions");
1785 block("foreigntype", "Foreign Types");
1786 block("keyword", "Keywords");
1789 window.initSidebarItems = initSidebarItems;
1791 window.register_implementors = function(imp) {
1792 var implementors = document.getElementById("implementors-list");
1793 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1795 var libs = Object.getOwnPropertyNames(imp);
1796 var llength = libs.length;
1797 for (var i = 0; i < llength; ++i) {
1798 if (libs[i] === currentCrate) { continue; }
1799 var structs = imp[libs[i]];
1801 var slength = structs.length;
1803 for (var j = 0; j < slength; ++j) {
1804 var struct = structs[j];
1806 var list = struct.synthetic ? synthetic_implementors : implementors;
1808 if (struct.synthetic) {
1809 var stlength = struct.types.length;
1810 for (var k = 0; k < stlength; k++) {
1811 if (window.inlined_types.has(struct.types[k])) {
1812 continue struct_loop;
1814 window.inlined_types.add(struct.types[k]);
1818 var code = document.createElement("code");
1819 code.innerHTML = struct.text;
1821 var x = code.getElementsByTagName("a");
1822 var xlength = x.length;
1823 for (var it = 0; it < xlength; it++) {
1824 var href = x[it].getAttribute("href");
1825 if (href && href.indexOf("http") !== 0) {
1826 x[it].setAttribute("href", rootPath + href);
1829 var display = document.createElement("h3");
1830 addClass(display, "impl");
1831 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1832 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1833 "</tbody></table></span>";
1834 list.appendChild(display);
1838 if (window.pending_implementors) {
1839 window.register_implementors(window.pending_implementors);
1842 function labelForToggleButton(sectionIsCollapsed) {
1843 if (sectionIsCollapsed) {
1844 // button will expand the section
1847 // button will collapse the section
1848 // note that this text is also set in the HTML template in render.rs
1849 return "\u2212"; // "\u2212" is "−" minus sign
1852 function onEveryMatchingChild(elem, className, func) {
1853 if (elem && className && func) {
1854 var length = elem.childNodes.length;
1855 var nodes = elem.childNodes;
1856 for (var i = 0; i < length; ++i) {
1857 if (hasClass(nodes[i], className)) {
1860 onEveryMatchingChild(nodes[i], className, func);
1866 function toggleAllDocs(pageId, fromAutoCollapse) {
1867 var innerToggle = document.getElementById("toggle-all-docs");
1871 if (hasClass(innerToggle, "will-expand")) {
1872 updateLocalStorage("rustdoc-collapse", "false");
1873 removeClass(innerToggle, "will-expand");
1874 onEveryMatchingChild(innerToggle, "inner", function(e) {
1875 e.innerHTML = labelForToggleButton(false);
1877 innerToggle.title = "collapse all docs";
1878 if (fromAutoCollapse !== true) {
1879 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1880 collapseDocs(e, "show");
1884 updateLocalStorage("rustdoc-collapse", "true");
1885 addClass(innerToggle, "will-expand");
1886 onEveryMatchingChild(innerToggle, "inner", function(e) {
1887 var parent = e.parentNode;
1888 var superParent = null;
1891 superParent = parent.parentNode;
1893 if (!parent || !superParent || superParent.id !== "main" ||
1894 hasClass(parent, "impl") === false) {
1895 e.innerHTML = labelForToggleButton(true);
1898 innerToggle.title = "expand all docs";
1899 if (fromAutoCollapse !== true) {
1900 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1901 var parent = e.parentNode;
1902 var superParent = null;
1905 superParent = parent.parentNode;
1907 if (!parent || !superParent || superParent.id !== "main" ||
1908 hasClass(parent, "impl") === false) {
1909 collapseDocs(e, "hide", pageId);
1916 function collapseDocs(toggle, mode, pageId) {
1917 if (!toggle || !toggle.parentNode) {
1921 function adjustToggle(arg) {
1922 return function(e) {
1923 if (hasClass(e, "toggle-label")) {
1925 e.style.display = "inline-block";
1927 e.style.display = "none";
1930 if (hasClass(e, "inner")) {
1931 e.innerHTML = labelForToggleButton(arg);
1936 function implHider(addOrRemove, fullHide) {
1937 return function(n) {
1938 var is_method = hasClass(n, "method") || fullHide;
1939 if (is_method || hasClass(n, "type")) {
1940 if (is_method === true) {
1942 addClass(n, "hidden-by-impl-hider");
1944 removeClass(n, "hidden-by-impl-hider");
1947 var ns = n.nextElementSibling;
1950 hasClass(ns, "docblock") ||
1951 hasClass(ns, "stability"))) {
1953 addClass(ns, "hidden-by-impl-hider");
1955 removeClass(ns, "hidden-by-impl-hider");
1957 ns = ns.nextElementSibling;
1968 if (hasClass(toggle.parentNode, "impl") === false) {
1969 relatedDoc = toggle.parentNode.nextElementSibling;
1970 if (hasClass(relatedDoc, "stability")) {
1971 relatedDoc = relatedDoc.nextElementSibling;
1973 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1974 if (mode === "toggle") {
1975 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1981 if (action === "hide") {
1982 addClass(relatedDoc, "hidden-by-usual-hider");
1983 onEachLazy(toggle.childNodes, adjustToggle(true));
1984 addClass(toggle.parentNode, "collapsed");
1985 } else if (action === "show") {
1986 removeClass(relatedDoc, "hidden-by-usual-hider");
1987 removeClass(toggle.parentNode, "collapsed");
1988 onEachLazy(toggle.childNodes, adjustToggle(false));
1992 // we are collapsing the impl block(s).
1994 var parentElem = toggle.parentNode;
1995 relatedDoc = parentElem;
1996 var docblock = relatedDoc.nextElementSibling;
1998 while (hasClass(relatedDoc, "impl-items") === false) {
1999 relatedDoc = relatedDoc.nextElementSibling;
2002 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2003 (pageId && document.getElementById(pageId))) {
2007 // Hide all functions, but not associated types/consts.
2009 if (mode === "toggle") {
2010 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2011 hasClass(docblock, "hidden-by-impl-hider")) {
2018 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2019 if (action === "show") {
2020 removeClass(relatedDoc, "fns-now-collapsed");
2021 removeClass(docblock, "hidden-by-usual-hider");
2022 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2023 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2024 } else if (action === "hide") {
2025 addClass(relatedDoc, "fns-now-collapsed");
2026 addClass(docblock, "hidden-by-usual-hider");
2027 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule);
2028 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2033 function collapser(e, collapse) {
2034 // inherent impl ids are like "impl" or impl-<number>'.
2035 // they will never be hidden by default.
2036 var n = e.parentElement;
2037 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2038 // Automatically minimize all non-inherent impls
2039 if (collapse || hasClass(n, "impl")) {
2040 collapseDocs(e, "hide", pageId);
2045 function autoCollapse(pageId, collapse) {
2047 toggleAllDocs(pageId, true);
2048 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2049 var impl_list = document.getElementById("implementations-list");
2051 if (impl_list !== null) {
2052 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2053 collapser(e, collapse);
2059 var toggles = document.getElementById("toggle-all-docs");
2061 toggles.onclick = toggleAllDocs;
2064 function insertAfter(newNode, referenceNode) {
2065 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2068 function createSimpleToggle(sectionIsCollapsed) {
2069 var toggle = document.createElement("a");
2070 toggle.href = "javascript:void(0)";
2071 toggle.className = "collapse-toggle";
2072 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2077 var toggle = createSimpleToggle(false);
2079 var func = function(e) {
2080 var next = e.nextElementSibling;
2084 if (hasClass(next, "docblock") ||
2085 (hasClass(next, "stability") &&
2086 hasClass(next.nextElementSibling, "docblock"))) {
2087 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2091 var funcImpl = function(e) {
2092 var next = e.nextElementSibling;
2093 if (next && hasClass(next, "docblock")) {
2094 next = next.nextElementSibling;
2099 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2100 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2104 onEachLazy(document.getElementsByClassName("method"), func);
2105 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2106 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2107 var impl_call = function() {};
2108 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2109 impl_call = function(e, newToggle, pageId) {
2110 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2111 // Automatically minimize all non-inherent impls
2112 if (hasClass(e, "impl")) {
2113 collapseDocs(newToggle, "hide", pageId);
2118 var pageId = getPageId();
2119 var newToggle = document.createElement("a");
2120 newToggle.href = "javascript:void(0)";
2121 newToggle.className = "collapse-toggle hidden-default collapsed";
2122 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2123 "</span>] Show hidden undocumented items";
2124 function toggleClicked() {
2125 if (hasClass(this, "collapsed")) {
2126 removeClass(this, "collapsed");
2127 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2128 if (hasClass(x, "content") === false) {
2129 removeClass(x, "hidden");
2133 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2134 "</span>] Hide undocumented items";
2136 addClass(this, "collapsed");
2137 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2138 if (hasClass(x, "content") === false) {
2139 addClass(x, "hidden");
2140 removeClass(x, "x");
2143 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2144 "</span>] Show hidden undocumented items";
2147 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2148 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2149 var hiddenElems = e.getElementsByClassName("hidden");
2150 var needToggle = false;
2152 var hlength = hiddenElems.length;
2153 for (var i = 0; i < hlength; ++i) {
2154 if (hasClass(hiddenElems[i], "content") === false &&
2155 hasClass(hiddenElems[i], "docblock") === false) {
2160 if (needToggle === true) {
2161 var inner_toggle = newToggle.cloneNode(true);
2162 inner_toggle.onclick = toggleClicked;
2163 e.insertBefore(inner_toggle, e.firstChild);
2164 impl_call(e, inner_toggle, pageId);
2168 function createToggle(otherMessage, fontSize, extraClass, show) {
2169 var span = document.createElement("span");
2170 span.className = "toggle-label";
2172 span.style.display = "none";
2174 if (!otherMessage) {
2175 span.innerHTML = " Expand description";
2177 span.innerHTML = otherMessage;
2181 span.style.fontSize = fontSize;
2184 var mainToggle = toggle.cloneNode(true);
2185 mainToggle.appendChild(span);
2187 var wrapper = document.createElement("div");
2188 wrapper.className = "toggle-wrapper";
2190 addClass(wrapper, "collapsed");
2191 var inner = mainToggle.getElementsByClassName("inner");
2192 if (inner && inner.length > 0) {
2193 inner[0].innerHTML = "+";
2197 addClass(wrapper, extraClass);
2199 wrapper.appendChild(mainToggle);
2203 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2204 function buildToggleWrapper(e) {
2205 if (hasClass(e, "autohide")) {
2206 var wrap = e.previousElementSibling;
2207 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2208 var inner_toggle = wrap.childNodes[0];
2209 var extra = e.childNodes[0].tagName === "H3";
2211 e.style.display = "none";
2212 addClass(wrap, "collapsed");
2213 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2214 e.innerHTML = labelForToggleButton(true);
2216 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2217 e.style.display = "inline-block";
2218 if (extra === true) {
2219 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2224 if (e.parentNode.id === "main") {
2225 var otherMessage = "";
2229 if (hasClass(e, "type-decl")) {
2231 otherMessage = " Show declaration";
2232 if (showItemDeclarations === false) {
2233 extraClass = "collapsed";
2235 } else if (hasClass(e, "sub-variant")) {
2236 otherMessage = " Show fields";
2237 } else if (hasClass(e, "non-exhaustive")) {
2238 otherMessage = " This ";
2239 if (hasClass(e, "non-exhaustive-struct")) {
2240 otherMessage += "struct";
2241 } else if (hasClass(e, "non-exhaustive-enum")) {
2242 otherMessage += "enum";
2243 } else if (hasClass(e, "non-exhaustive-type")) {
2244 otherMessage += "type";
2246 otherMessage += " is marked as non-exhaustive";
2247 } else if (hasClass(e.childNodes[0], "impl-items")) {
2248 extraClass = "marg-left";
2251 e.parentNode.insertBefore(
2252 createToggle(otherMessage,
2255 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2257 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2258 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2263 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2264 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2266 // In the search display, allows to switch between tabs.
2267 function printTab(nb) {
2268 if (nb === 0 || nb === 1 || nb === 2) {
2272 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2273 if (nb_copy === 0) {
2274 addClass(elem, "selected");
2276 removeClass(elem, "selected");
2280 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2282 elem.style.display = "";
2284 elem.style.display = "none";
2290 function createToggleWrapper(tog) {
2291 var span = document.createElement("span");
2292 span.className = "toggle-label";
2293 span.style.display = "none";
2294 span.innerHTML = " Expand attributes";
2295 tog.appendChild(span);
2297 var wrapper = document.createElement("div");
2298 wrapper.className = "toggle-wrapper toggle-attributes";
2299 wrapper.appendChild(tog);
2303 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2304 var itemAttributesFunc = function() {};
2305 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2306 itemAttributesFunc = function(x) {
2307 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2310 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2311 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2312 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2313 itemAttributesFunc(i_e);
2316 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2317 var lineNumbersFunc = function() {};
2318 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2319 lineNumbersFunc = function(x) {
2320 var count = x.textContent.split("\n").length;
2322 for (var i = 0; i < count; ++i) {
2325 var node = document.createElement("pre");
2326 addClass(node, "line-number");
2327 node.innerHTML = elems.join("\n");
2328 x.parentNode.insertBefore(node, x);
2331 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2332 if (hasClass(e, "compile_fail")) {
2333 e.addEventListener("mouseover", function(event) {
2334 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2336 e.addEventListener("mouseout", function(event) {
2337 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2339 } else if (hasClass(e, "ignore")) {
2340 e.addEventListener("mouseover", function(event) {
2341 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2343 e.addEventListener("mouseout", function(event) {
2344 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2350 function showModal(content) {
2351 var modal = document.createElement("div");
2352 modal.id = "important";
2353 addClass(modal, "modal");
2354 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2355 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2357 document.getElementsByTagName("body")[0].appendChild(modal);
2358 document.getElementById("modal-close").onclick = hideModal;
2359 modal.onclick = hideModal;
2362 function hideModal() {
2363 var modal = document.getElementById("important");
2365 modal.parentNode.removeChild(modal);
2369 onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2370 e.onclick = function() {
2371 showModal(e.lastElementChild.innerHTML);
2375 function putBackSearch(search_input) {
2376 if (search_input.value !== "") {
2377 addClass(main, "hidden");
2378 removeClass(document.getElementById("search"), "hidden");
2379 if (browserSupportsHistoryApi()) {
2380 history.replaceState(search_input.value,
2382 "?search=" + encodeURIComponent(search_input.value));
2388 search_input.onfocus = function() {
2389 putBackSearch(this);
2393 var params = getQueryStringParams();
2394 if (params && params.search) {
2395 addClass(main, "hidden");
2396 var search = document.getElementById("search");
2397 removeClass(search, "hidden");
2398 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2401 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2403 sidebar_menu.onclick = function() {
2404 var sidebar = document.getElementsByClassName("sidebar")[0];
2405 if (hasClass(sidebar, "mobile") === true) {
2413 window.onresize = function() {
2417 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2419 if (window.location.hash && window.location.hash.length > 0) {
2420 expandSection(window.location.hash.replace(/^#/, ""));
2424 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2427 onEachLazy(main.childNodes, function(e) {
2428 // Unhide the actual content once loading is complete. Headers get
2429 // flex treatment for their horizontal layout, divs get block treatment
2430 // for vertical layout (column-oriented flex layout for divs caused
2431 // errors in mobile browsers).
2432 if (e.tagName === "H2" || e.tagName === "H3") {
2433 var nextTagName = e.nextElementSibling.tagName;
2434 if (nextTagName == "H2" || nextTagName == "H3") {
2435 e.nextElementSibling.style.display = "flex";
2437 e.nextElementSibling.style.display = "block";
2443 function addSearchOptions(crates) {
2444 var elem = document.getElementById('crate-search');
2449 var crates_text = [];
2450 if (Object.keys(crates).length > 1) {
2451 for (var crate in crates) {
2452 if (crates.hasOwnProperty(crate)) {
2453 crates_text.push(crate);
2457 crates_text.sort(function(a, b) {
2458 var lower_a = a.toLowerCase();
2459 var lower_b = b.toLowerCase();
2461 if (lower_a < lower_b) {
2463 } else if (lower_a > lower_b) {
2468 for (var i = 0; i < crates_text.length; ++i) {
2469 var option = document.createElement("option");
2470 option.value = crates_text[i];
2471 option.innerText = crates_text[i];
2472 elem.appendChild(option);
2476 window.addSearchOptions = addSearchOptions;
2479 // Sets the focus on the search bar at the top of the page
2480 function focusSearchBar() {
2481 document.getElementsByClassName("search-input")[0].focus();
2484 // Removes the focus from the search bar
2485 function defocusSearchBar() {
2486 document.getElementsByClassName("search-input")[0].blur();