2 * Copyright 2014 The Rust Project Developers. See the COPYRIGHT
3 * file at the top-level directory of this distribution and at
4 * http://rust-lang.org/COPYRIGHT.
6 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 * option. This file may not be copied, modified, or distributed
10 * except according to those terms.
14 /* global ALIASES, currentCrate, rootPath */
16 // Local js definitions:
17 /* global addClass, getCurrentValue, hasClass */
18 /* global isHidden onEach, removeClass, updateLocalStorage */
20 if (!String.prototype.startsWith) {
21 String.prototype.startsWith = function(searchString, position) {
22 position = position || 0;
23 return this.indexOf(searchString, position) === position;
26 if (!String.prototype.endsWith) {
27 String.prototype.endsWith = function(suffix, length) {
28 var l = length || this.length;
29 return this.indexOf(suffix, l - suffix.length) !== -1;
33 if (!DOMTokenList.prototype.add) {
34 DOMTokenList.prototype.add = function(className) {
35 if (className && !hasClass(this, className)) {
36 if (this.className && this.className.length > 0) {
37 this.className += " " + className;
39 this.className = className;
45 if (!DOMTokenList.prototype.remove) {
46 DOMTokenList.prototype.remove = function(className) {
47 if (className && this.className) {
48 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
57 // This mapping table should match the discriminants of
58 // `rustdoc::html::item_type::ItemType` type in Rust.
59 var itemTypes = ["mod",
85 var start = Date.now();
87 var search_input = document.getElementsByClassName("search-input")[0];
89 // On the search screen, so you remain on the last tab you opened.
92 // 1 for "In Parameters"
93 // 2 for "In Return Types"
96 var themesWidth = null;
98 var titleBeforeSearch = document.title;
100 function getPageId() {
101 var id = document.location.href.split("#")[1];
103 return id.split("?")[0].split("&")[0];
108 function showSidebar() {
109 var elems = document.getElementsByClassName("sidebar-elems")[0];
111 addClass(elems, "show-it");
113 var sidebar = document.getElementsByClassName("sidebar")[0];
115 addClass(sidebar, "mobile");
116 var filler = document.getElementById("sidebar-filler");
118 var div = document.createElement("div");
119 div.id = "sidebar-filler";
120 sidebar.appendChild(div);
123 var themePicker = document.getElementsByClassName("theme-picker");
124 if (themePicker && themePicker.length > 0) {
125 themePicker[0].style.display = "none";
129 function hideSidebar() {
130 var elems = document.getElementsByClassName("sidebar-elems")[0];
132 removeClass(elems, "show-it");
134 var sidebar = document.getElementsByClassName("sidebar")[0];
135 removeClass(sidebar, "mobile");
136 var filler = document.getElementById("sidebar-filler");
140 document.getElementsByTagName("body")[0].style.marginTop = "";
141 var themePicker = document.getElementsByClassName("theme-picker");
142 if (themePicker && themePicker.length > 0) {
143 themePicker[0].style.display = null;
147 // used for special search precedence
148 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
149 var TY_KEYWORD = itemTypes.indexOf("keyword");
151 onEach(Array.prototype.slice.call(document.getElementsByClassName("js-only")), function(e) {
152 removeClass(e, "js-only");
155 function getQueryStringParams() {
157 window.location.search.substring(1).split("&").
159 var pair = s.split("=");
160 params[decodeURIComponent(pair[0])] =
161 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
166 function browserSupportsHistoryApi() {
167 return document.location.protocol != "file:" &&
168 window.history && typeof window.history.pushState === "function";
171 var main = document.getElementById("main");
173 function highlightSourceLines(ev) {
174 // If we're in mobile mode, we should add the sidebar in any case.
177 var search = document.getElementById("search");
178 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
180 from = parseInt(match[1], 10);
181 to = Math.min(50000, parseInt(match[2] || match[1], 10));
182 from = Math.min(from, to);
183 elem = document.getElementById(from);
188 var x = document.getElementById(from);
193 onEach(Array.prototype.slice.call(document.getElementsByClassName("line-numbers")),
195 onEach(Array.prototype.slice.call(e.getElementsByTagName("span")), function(i_e) {
196 removeClass(i_e, "line-highlighted");
199 for (i = from; i <= to; ++i) {
200 addClass(document.getElementById(i), "line-highlighted");
202 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
203 addClass(search, "hidden");
204 removeClass(main, "hidden");
205 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
206 if (browserSupportsHistoryApi()) {
207 history.replaceState(hash, "", "?search=#" + hash);
209 elem = document.getElementById(hash);
211 elem.scrollIntoView();
216 function expandSection(id) {
217 var elem = document.getElementById(id);
218 if (elem && isHidden(elem)) {
219 var h3 = elem.parentNode.previousSibling;
220 if (h3 && h3.tagName !== "H3") {
221 h3 = h3.previousSibling; // skip div.docblock
225 var collapses = h3.getElementsByClassName("collapse-toggle");
226 if (collapses.length > 0) {
227 // The element is not visible, we need to make it appear!
228 collapseDocs(collapses[0], "show");
234 highlightSourceLines(null);
235 window.onhashchange = highlightSourceLines;
237 // Gets the human-readable string for the virtual-key code of the
238 // given KeyboardEvent, ev.
240 // This function is meant as a polyfill for KeyboardEvent#key,
241 // since it is not supported in Trident. We also test for
242 // KeyboardEvent#keyCode because the handleShortcut handler is
243 // also registered for the keydown event, because Blink doesn't fire
244 // keypress on hitting the Escape key.
246 // So I guess you could say things are getting pretty interoperable.
247 function getVirtualKey(ev) {
248 if ("key" in ev && typeof ev.key != "undefined") {
252 var c = ev.charCode || ev.keyCode;
256 return String.fromCharCode(c);
259 function displayHelp(display, ev) {
260 if (display === true) {
261 if (hasClass(help, "hidden")) {
263 removeClass(help, "hidden");
264 addClass(document.body, "blur");
266 } else if (hasClass(help, "hidden") === false) {
268 addClass(help, "hidden");
269 removeClass(document.body, "blur");
273 function handleEscape(ev, help) {
275 var search = document.getElementById("search");
276 if (hasClass(help, "hidden") === false) {
277 displayHelp(false, ev);
278 } else if (hasClass(search, "hidden") === false) {
280 addClass(search, "hidden");
281 removeClass(main, "hidden");
282 document.title = titleBeforeSearch;
287 function handleShortcut(ev) {
288 // Don't interfere with browser shortcuts
289 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
293 var help = document.getElementById("help");
294 if (document.activeElement.tagName === "INPUT") {
295 switch (getVirtualKey(ev)) {
297 handleEscape(ev, help);
301 switch (getVirtualKey(ev)) {
303 handleEscape(ev, help);
308 displayHelp(false, ev);
323 displayHelp(true, ev);
330 function findParentElement(elem, tagName) {
332 if (elem && elem.tagName === tagName) {
335 elem = elem.parentNode;
340 document.onkeypress = handleShortcut;
341 document.onkeydown = handleShortcut;
342 document.onclick = function(ev) {
343 if (hasClass(ev.target, "collapse-toggle")) {
344 collapseDocs(ev.target, "toggle");
345 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
346 collapseDocs(ev.target.parentNode, "toggle");
347 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
350 var set_fragment = function(name) {
351 if (browserSupportsHistoryApi()) {
352 history.replaceState(null, null, "#" + name);
355 location.replace("#" + name);
359 var cur_id = parseInt(ev.target.id, 10);
361 if (ev.shiftKey && prev_id) {
362 if (prev_id > cur_id) {
368 set_fragment(prev_id + "-" + cur_id);
372 set_fragment(cur_id);
374 } else if (hasClass(document.getElementById("help"), "hidden") === false) {
375 addClass(document.getElementById("help"), "hidden");
376 removeClass(document.body, "blur");
378 // Making a collapsed element visible on onhashchange seems
380 var a = findParentElement(ev.target, "A");
382 expandSection(a.hash.replace(/^#/, ""));
387 var x = document.getElementsByClassName("version-selector");
389 x[0].onchange = function() {
391 url = document.location.href,
393 len = rootPath.match(/\.\.\//g).length + 1;
395 for (i = 0; i < len; ++i) {
396 match = url.match(/\/[^\/]*$/);
398 stripped = match[0] + stripped;
400 url = url.substring(0, url.length - match[0].length);
403 url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
405 document.location.href = url;
410 * A function to compute the Levenshtein distance between two strings
411 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
412 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
413 * This code is an unmodified version of the code written by Marco de Wit
414 * and was found at http://stackoverflow.com/a/18514751/745719
416 var levenshtein_row2 = [];
417 function levenshtein(s1, s2) {
421 var s1_len = s1.length, s2_len = s2.length;
422 if (s1_len && s2_len) {
423 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
424 while (i1 < s1_len) {
427 while (i2 < s2_len) {
428 c2 = s2.charCodeAt(i2);
432 for (i1 = 0; i1 < s1_len; ++i1) {
433 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
435 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
441 return s1_len + s2_len;
444 function initSearch(rawSearchIndex) {
445 var currentResults, index, searchIndex;
446 var MAX_LEV_DISTANCE = 3;
447 var MAX_RESULTS = 200;
448 var GENERICS_DATA = 1;
452 var params = getQueryStringParams();
454 // Populate search bar with query string search term when provided,
455 // but only if the input bar is empty. This avoid the obnoxious issue
456 // where you start trying to do a search, and the index loads, and
457 // suddenly your search is gone!
458 if (search_input.value === "") {
459 search_input.value = params.search || "";
463 * Executes the query and builds an index of results
464 * @param {[Object]} query [The user query]
465 * @param {[type]} searchWords [The list of search words to query
467 * @param {[type]} filterCrates [Crate to search in if defined]
468 * @return {[type]} [A search index of results]
470 function execQuery(query, searchWords, filterCrates) {
471 function itemTypeFromName(typename) {
472 var length = itemTypes.length;
473 for (var i = 0; i < length; ++i) {
474 if (itemTypes[i] === typename) {
481 var valLower = query.query.toLowerCase(),
483 typeFilter = itemTypeFromName(query.type),
484 results = {}, results_in_args = {}, results_returned = {},
485 split = valLower.split("::");
487 var length = split.length;
488 for (var z = 0; z < length; ++z) {
489 if (split[z] === "") {
495 function transformResults(results, isType) {
497 var length = results.length;
498 for (var i = 0; i < length; ++i) {
499 if (results[i].id > -1) {
500 var obj = searchIndex[results[i].id];
501 obj.lev = results[i].lev;
502 if (isType !== true || obj.type) {
503 var res = buildHrefAndPath(obj);
504 obj.displayPath = pathSplitter(res[0]);
505 obj.fullPath = obj.displayPath + obj.name;
506 // To be sure than it some items aren't considered as duplicate.
507 obj.fullPath += "|" + obj.ty;
510 if (out.length >= MAX_RESULTS) {
519 function sortResults(results, isType) {
521 for (var entry in results) {
522 if (results.hasOwnProperty(entry)) {
523 ar.push(results[entry]);
528 var nresults = results.length;
529 for (i = 0; i < nresults; ++i) {
530 results[i].word = searchWords[results[i].id];
531 results[i].item = searchIndex[results[i].id] || {};
533 // if there are no results then return to default and fail
534 if (results.length === 0) {
538 results.sort(function(aaa, bbb) {
541 // Sort by non levenshtein results and then levenshtein results by the distance
542 // (less changes required to match means higher rankings)
545 if (a !== b) { return a - b; }
547 // sort by crate (non-current crate goes later)
548 a = (aaa.item.crate !== window.currentCrate);
549 b = (bbb.item.crate !== window.currentCrate);
550 if (a !== b) { return a - b; }
552 // sort by exact match (mismatch goes later)
553 a = (aaa.word !== valLower);
554 b = (bbb.word !== valLower);
555 if (a !== b) { return a - b; }
557 // sort by item name length (longer goes later)
560 if (a !== b) { return a - b; }
562 // sort by item name (lexicographically larger goes later)
565 if (a !== b) { return (a > b ? +1 : -1); }
567 // sort by index of keyword in item name (no literal occurrence goes later)
570 if (a !== b) { return a - b; }
571 // (later literal occurrence, if any, goes later)
574 if (a !== b) { return a - b; }
576 // special precedence for primitive and keyword pages
577 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
578 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
581 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
582 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
586 // sort by description (no description goes later)
587 a = (aaa.item.desc === "");
588 b = (bbb.item.desc === "");
589 if (a !== b) { return a - b; }
591 // sort by type (later occurrence in `itemTypes` goes later)
594 if (a !== b) { return a - b; }
596 // sort by path (lexicographically larger goes later)
599 if (a !== b) { return (a > b ? +1 : -1); }
605 var length = results.length;
606 for (i = 0; i < length; ++i) {
607 var result = results[i];
609 // this validation does not make sense when searching by types
610 if (result.dontValidate) {
613 var name = result.item.name.toLowerCase(),
614 path = result.item.path.toLowerCase(),
615 parent = result.item.parent;
617 if (isType !== true &&
618 validateResult(name, path, split, parent) === false)
623 return transformResults(results);
626 function extractGenerics(val) {
627 val = val.toLowerCase();
628 if (val.indexOf("<") !== -1) {
629 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
631 name: val.substring(0, val.indexOf("<")),
632 generics: values.split(/\s*,\s*/),
641 function checkGenerics(obj, val) {
642 // The names match, but we need to be sure that all generics kinda
644 var lev_distance = MAX_LEV_DISTANCE + 1;
645 if (val.generics.length > 0) {
646 if (obj.length > GENERICS_DATA &&
647 obj[GENERICS_DATA].length >= val.generics.length) {
648 var elems = obj[GENERICS_DATA].slice(0);
651 // We need to find the type that matches the most to remove it in order
653 var vlength = val.generics.length;
654 for (var y = 0; y < vlength; ++y) {
655 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
656 var elength = elems.length;
657 for (var x = 0; x < elength; ++x) {
658 var tmp_lev = levenshtein(elems[x], val.generics[y]);
659 if (tmp_lev < lev.lev) {
664 if (lev.pos !== -1) {
665 elems.splice(lev.pos, 1);
666 lev_distance = Math.min(lev.lev, lev_distance);
670 return MAX_LEV_DISTANCE + 1;
673 return lev_distance;//Math.ceil(total / done);
676 return MAX_LEV_DISTANCE + 1;
679 // Check for type name and type generics (if any).
680 function checkType(obj, val, literalSearch) {
681 var lev_distance = MAX_LEV_DISTANCE + 1;
683 if (obj[NAME] === val.name) {
684 if (literalSearch === true) {
685 if (val.generics && val.generics.length !== 0) {
686 if (obj.length > GENERICS_DATA &&
687 obj[GENERICS_DATA].length >= val.generics.length) {
688 var elems = obj[GENERICS_DATA].slice(0);
691 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
693 for (x = 0; allFound === false && x < elems.length; ++x) {
694 allFound = elems[x] === val.generics[y];
696 if (allFound === true) {
697 elems.splice(x - 1, 1);
700 if (allFound === true) {
709 // If the type has generics but don't match, then it won't return at this point.
710 // Otherwise, `checkGenerics` will return 0 and it'll return.
711 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
712 var tmp_lev = checkGenerics(obj, val);
713 if (tmp_lev <= MAX_LEV_DISTANCE) {
720 // Names didn't match so let's check if one of the generic types could.
721 if (literalSearch === true) {
722 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
723 var length = obj[GENERICS_DATA].length;
724 for (x = 0; x < length; ++x) {
725 if (obj[GENERICS_DATA][x] === val.name) {
732 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
733 if (lev_distance <= MAX_LEV_DISTANCE) {
734 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
735 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
736 // We can check if the type we're looking for is inside the generics!
737 var olength = obj[GENERICS_DATA].length;
738 for (x = 0; x < olength; ++x) {
739 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
743 // Now whatever happens, the returned distance is "less good" so we should mark it
744 // as such, and so we add 1 to the distance to make it "less good".
745 return lev_distance + 1;
748 function findArg(obj, val, literalSearch) {
749 var lev_distance = MAX_LEV_DISTANCE + 1;
751 if (obj && obj.type && obj.type[INPUTS_DATA] &&
752 obj.type[INPUTS_DATA].length > 0) {
753 var length = obj.type[INPUTS_DATA].length;
754 for (var i = 0; i < length; i++) {
755 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
756 if (literalSearch === true && tmp === true) {
759 lev_distance = Math.min(tmp, lev_distance);
760 if (lev_distance === 0) {
765 return literalSearch === true ? false : lev_distance;
768 function checkReturned(obj, val, literalSearch) {
769 var lev_distance = MAX_LEV_DISTANCE + 1;
771 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
772 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
773 if (literalSearch === true && tmp === true) {
776 lev_distance = Math.min(tmp, lev_distance);
777 if (lev_distance === 0) {
781 return literalSearch === true ? false : lev_distance;
784 function checkPath(contains, lastElem, ty) {
785 if (contains.length === 0) {
788 var ret_lev = MAX_LEV_DISTANCE + 1;
789 var path = ty.path.split("::");
791 if (ty.parent && ty.parent.name) {
792 path.push(ty.parent.name.toLowerCase());
795 var length = path.length;
796 var clength = contains.length;
797 if (clength > length) {
798 return MAX_LEV_DISTANCE + 1;
800 for (var i = 0; i < length; ++i) {
801 if (i + clength > length) {
806 for (var x = 0; x < clength; ++x) {
807 var lev = levenshtein(path[i + x], contains[x]);
808 if (lev > MAX_LEV_DISTANCE) {
814 if (aborted === false) {
815 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
821 function typePassesFilter(filter, type) {
823 if (filter < 0) return true;
826 if (filter === type) return true;
828 // Match related items
829 var name = itemTypes[type];
830 switch (itemTypes[filter]) {
832 return (name == "associatedconstant");
834 return (name == "method" || name == "tymethod");
836 return (name == "primitive" || name == "keyword");
843 function generateId(ty) {
844 if (ty.parent && ty.parent.name) {
845 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
847 return itemTypes[ty.ty] + ty.path + ty.name;
850 // quoted values mean literal search
851 var nSearchWords = searchWords.length;
857 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
858 val.charAt(val.length - 1) === val.charAt(0))
860 val = extractGenerics(val.substr(1, val.length - 2));
861 for (i = 0; i < nSearchWords; ++i) {
862 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
865 in_args = findArg(searchIndex[i], val, true);
866 returned = checkReturned(searchIndex[i], val, true);
868 fullId = generateId(ty);
870 if (searchWords[i] === val.name) {
871 // filter type: ... queries
872 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
873 results[fullId] === undefined)
875 results[fullId] = {id: i, index: -1};
877 } else if ((in_args === true || returned === true) &&
878 typePassesFilter(typeFilter, searchIndex[i].ty)) {
879 if (in_args === true || returned === true) {
880 if (in_args === true) {
881 results_in_args[fullId] = {
887 if (returned === true) {
888 results_returned[fullId] = {
903 query.inputs = [val];
907 } else if (val.search("->") > -1) {
908 var trimmer = function(s) { return s.trim(); };
909 var parts = val.split("->").map(trimmer);
910 var input = parts[0];
911 // sort inputs so that order does not matter
912 var inputs = input.split(",").map(trimmer).sort();
913 for (i = 0; i < inputs.length; ++i) {
914 inputs[i] = extractGenerics(inputs[i]);
916 var output = extractGenerics(parts[1]);
918 for (i = 0; i < nSearchWords; ++i) {
919 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
922 var type = searchIndex[i].type;
927 fullId = generateId(ty);
929 // allow searching for void (no output) functions as well
930 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
931 returned = checkReturned(ty, output, true);
932 if (output.name === "*" || returned === true) {
940 for (var it = 0; allFound === true && it < inputs.length; it++) {
941 allFound = checkType(type, inputs[it], true);
945 if (in_args === true) {
946 results_in_args[fullId] = {
952 if (returned === true) {
953 results_returned[fullId] = {
959 if (module === true) {
968 query.inputs = inputs.map(function(input) {
971 query.output = output.name;
973 query.inputs = [val];
976 // gather matching search results up to a certain maximum
977 val = val.replace(/\_/g, "");
979 var valGenerics = extractGenerics(val);
981 var paths = valLower.split("::");
983 for (j = 0; j < paths.length; ++j) {
984 if (paths[j] === "") {
989 val = paths[paths.length - 1];
990 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
992 for (j = 0; j < nSearchWords; ++j) {
996 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1001 if (paths.length > 1) {
1002 lev = checkPath(contains, paths[paths.length - 1], ty);
1003 if (lev > MAX_LEV_DISTANCE) {
1005 } else if (lev > 0) {
1010 returned = MAX_LEV_DISTANCE + 1;
1011 in_args = MAX_LEV_DISTANCE + 1;
1013 // we want lev results to go lower than others
1014 lev = MAX_LEV_DISTANCE + 1;
1015 fullId = generateId(ty);
1017 if (searchWords[j].indexOf(split[i]) > -1 ||
1018 searchWords[j].indexOf(val) > -1 ||
1019 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1021 // filter type: ... queries
1022 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1023 index = searchWords[j].replace(/_/g, "").indexOf(val);
1026 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1027 if (typePassesFilter(typeFilter, ty.ty) === false) {
1028 lev = MAX_LEV_DISTANCE + 1;
1033 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1034 if (typePassesFilter(typeFilter, ty.ty) === false) {
1035 in_args = MAX_LEV_DISTANCE + 1;
1038 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1039 if (typePassesFilter(typeFilter, ty.ty) === false) {
1040 returned = MAX_LEV_DISTANCE + 1;
1045 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1046 if (val.length < 6) {
1052 if (in_args <= MAX_LEV_DISTANCE) {
1053 if (results_in_args[fullId] === undefined) {
1054 results_in_args[fullId] = {
1060 results_in_args[fullId].lev =
1061 Math.min(results_in_args[fullId].lev, in_args);
1063 if (returned <= MAX_LEV_DISTANCE) {
1064 if (results_returned[fullId] === undefined) {
1065 results_returned[fullId] = {
1071 results_returned[fullId].lev =
1072 Math.min(results_returned[fullId].lev, returned);
1074 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1075 if (index !== -1 && paths.length < 2) {
1078 if (results[fullId] === undefined) {
1085 results[fullId].lev = Math.min(results[fullId].lev, lev);
1091 "in_args": sortResults(results_in_args, true),
1092 "returned": sortResults(results_returned, true),
1093 "others": sortResults(results),
1095 if (ALIASES && ALIASES[window.currentCrate] &&
1096 ALIASES[window.currentCrate][query.raw]) {
1097 var aliases = ALIASES[window.currentCrate][query.raw];
1098 for (i = 0; i < aliases.length; ++i) {
1099 aliases[i].is_alias = true;
1100 aliases[i].alias = query.raw;
1101 aliases[i].path = aliases[i].p;
1102 var res = buildHrefAndPath(aliases[i]);
1103 aliases[i].displayPath = pathSplitter(res[0]);
1104 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1105 aliases[i].href = res[1];
1106 retothers.unshift(aliases[i]);
1107 if (ret.others.length > MAX_RESULTS) {
1116 * Validate performs the following boolean logic. For example:
1117 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1118 * exists in (name || path || parent) OR => ("file" && "open") exists in
1121 * This could be written functionally, but I wanted to minimise
1122 * functions on stack.
1124 * @param {[string]} name [The name of the result]
1125 * @param {[string]} path [The path of the result]
1126 * @param {[string]} keys [The keys to be used (["file", "open"])]
1127 * @param {[object]} parent [The parent of the result]
1128 * @return {[boolean]} [Whether the result is valid or not]
1130 function validateResult(name, path, keys, parent) {
1131 for (var i = 0; i < keys.length; ++i) {
1132 // each check is for validation so we negate the conditions and invalidate
1134 // check for an exact name match
1135 name.indexOf(keys[i]) > -1 ||
1136 // then an exact path match
1137 path.indexOf(keys[i]) > -1 ||
1138 // next if there is a parent, check for exact parent match
1139 (parent !== undefined &&
1140 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1141 // lastly check to see if the name was a levenshtein match
1142 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1149 function getQuery(raw) {
1150 var matches, type, query;
1153 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1155 type = matches[1].replace(/^const$/, "constant");
1156 query = query.substring(matches[0].length);
1167 function initSearchNav() {
1170 var click_func = function(e) {
1172 // to retrieve the real "owner" of the event.
1173 while (el.tagName !== "TR") {
1176 var dst = e.target.getElementsByTagName("a");
1177 if (dst.length < 1) {
1181 if (window.location.pathname === dst.pathname) {
1182 addClass(document.getElementById("search"), "hidden");
1183 removeClass(main, "hidden");
1184 document.location.href = dst.href;
1187 var mouseover_func = function(e) {
1189 // to retrieve the real "owner" of the event.
1190 while (el.tagName !== "TR") {
1193 clearTimeout(hoverTimeout);
1194 hoverTimeout = setTimeout(function() {
1195 onEach(document.getElementsByClassName("search-results"), function(e) {
1196 onEach(e.getElementsByClassName("result"), function(i_e) {
1197 removeClass(i_e, "highlighted");
1200 addClass(el, "highlighted");
1203 onEach(document.getElementsByClassName("search-results"), function(e) {
1204 onEach(e.getElementsByClassName("result"), function(i_e) {
1205 i_e.onclick = click_func;
1206 i_e.onmouseover = mouseover_func;
1210 search_input.onkeydown = function(e) {
1211 // "actives" references the currently highlighted item in each search tab.
1212 // Each array in "actives" represents a tab.
1213 var actives = [[], [], []];
1214 // "current" is used to know which tab we're looking into.
1216 onEach(document.getElementsByClassName("search-results"), function(e) {
1217 onEach(e.getElementsByClassName("highlighted"), function(e) {
1218 actives[current].push(e);
1223 if (e.which === 38) { // up
1224 if (!actives[currentTab].length ||
1225 !actives[currentTab][0].previousElementSibling) {
1229 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1230 removeClass(actives[currentTab][0], "highlighted");
1231 } else if (e.which === 40) { // down
1232 if (!actives[currentTab].length) {
1233 var results = document.getElementsByClassName("search-results");
1234 if (results.length > 0) {
1235 var res = results[currentTab].getElementsByClassName("result");
1236 if (res.length > 0) {
1237 addClass(res[0], "highlighted");
1240 } else if (actives[currentTab][0].nextElementSibling) {
1241 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1242 removeClass(actives[currentTab][0], "highlighted");
1244 } else if (e.which === 13) { // return
1245 if (actives[currentTab].length) {
1246 document.location.href =
1247 actives[currentTab][0].getElementsByTagName("a")[0].href;
1249 } else if (e.which === 9) { // tab
1251 printTab(currentTab > 0 ? currentTab - 1 : 2);
1253 printTab(currentTab > 1 ? 0 : currentTab + 1);
1256 } else if (e.which === 16) { // shift
1257 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1258 } else if (e.which === 27) { // escape
1259 removeClass(actives[currentTab][0], "highlighted");
1260 search_input.value = "";
1262 } else if (actives[currentTab].length > 0) {
1263 removeClass(actives[currentTab][0], "highlighted");
1268 function buildHrefAndPath(item) {
1271 var type = itemTypes[item.ty];
1272 var name = item.name;
1274 if (type === "mod") {
1275 displayPath = item.path + "::";
1276 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1277 name + "/index.html";
1278 } else if (type === "primitive" || type === "keyword") {
1280 href = rootPath + item.path.replace(/::/g, "/") +
1281 "/" + type + "." + name + ".html";
1282 } else if (type === "externcrate") {
1284 href = rootPath + name + "/index.html";
1285 } else if (item.parent !== undefined) {
1286 var myparent = item.parent;
1287 var anchor = "#" + type + "." + name;
1288 var parentType = itemTypes[myparent.ty];
1289 if (parentType === "primitive") {
1290 displayPath = myparent.name + "::";
1292 displayPath = item.path + "::" + myparent.name + "::";
1294 href = rootPath + item.path.replace(/::/g, "/") +
1296 "." + myparent.name +
1299 displayPath = item.path + "::";
1300 href = rootPath + item.path.replace(/::/g, "/") +
1301 "/" + type + "." + name + ".html";
1303 return [displayPath, href];
1306 function escape(content) {
1307 var h1 = document.createElement("h1");
1308 h1.textContent = content;
1309 return h1.innerHTML;
1312 function pathSplitter(path) {
1313 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1314 if (tmp.endsWith("<span>")) {
1315 return tmp.slice(0, tmp.length - 6);
1320 function addTab(array, query, display) {
1321 var extraStyle = "";
1322 if (display === false) {
1323 extraStyle = " style=\"display: none;\"";
1327 var duplicates = {};
1329 if (array.length > 0) {
1330 output = "<table class=\"search-results\"" + extraStyle + ">";
1332 array.forEach(function(item) {
1336 type = itemTypes[item.ty];
1338 if (item.is_alias !== true) {
1339 if (duplicates[item.fullPath]) {
1342 duplicates[item.fullPath] = true;
1346 output += "<tr class=\"" + type + " result\"><td>" +
1347 "<a href=\"" + item.href + "\">" +
1348 (item.is_alias === true ?
1349 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1350 "class=\"grey\"><i> - see </i></span>") : "") +
1351 item.displayPath + "<span class=\"" + type + "\">" +
1352 name + "</span></a></td><td>" +
1353 "<a href=\"" + item.href + "\">" +
1354 "<span class=\"desc\">" + escape(item.desc) +
1355 " </span></a></td></tr>";
1357 output += "</table>";
1359 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1360 "Try on <a href=\"https://duckduckgo.com/?q=" +
1361 encodeURIComponent("rust " + query.query) +
1362 "\">DuckDuckGo</a>?<br/><br/>" +
1363 "Or try looking in one of these:<ul><li>The <a " +
1364 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1365 " for technical details about the language.</li><li><a " +
1366 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1367 "Example</a> for expository code examples.</a></li><li>The <a " +
1368 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1369 "introductions to language features and the language itself.</li><li><a " +
1370 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1371 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1373 return [output, length];
1376 function makeTabHeader(tabNb, text, nbElems) {
1377 if (currentTab === tabNb) {
1378 return "<div class=\"selected\">" + text +
1379 " <div class=\"count\">(" + nbElems + ")</div></div>";
1381 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1384 function showResults(results) {
1385 if (results.others.length === 1 &&
1386 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1387 var elem = document.createElement("a");
1388 elem.href = results.others[0].href;
1389 elem.style.display = "none";
1390 // For firefox, we need the element to be in the DOM so it can be clicked.
1391 document.body.appendChild(elem);
1394 var query = getQuery(search_input.value);
1396 currentResults = query.id;
1398 var ret_others = addTab(results.others, query);
1399 var ret_in_args = addTab(results.in_args, query, false);
1400 var ret_returned = addTab(results.returned, query, false);
1402 var output = "<h1>Results for " + escape(query.query) +
1403 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1404 "<div id=\"titles\">" +
1405 makeTabHeader(0, "In Names", ret_others[1]) +
1406 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1407 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1408 "</div><div id=\"results\">" +
1409 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1411 addClass(main, "hidden");
1412 var search = document.getElementById("search");
1413 removeClass(search, "hidden");
1414 search.innerHTML = output;
1415 var tds = search.getElementsByTagName("td");
1417 if (tds.length > 0) {
1418 td_width = tds[0].offsetWidth;
1420 var width = search.offsetWidth - 40 - td_width;
1421 onEach(Array.prototype.slice.call(search.getElementsByClassName("desc")), function(e) {
1422 e.style.width = width + "px";
1425 var elems = document.getElementById("titles").childNodes;
1426 elems[0].onclick = function() { printTab(0); };
1427 elems[1].onclick = function() { printTab(1); };
1428 elems[2].onclick = function() { printTab(2); };
1429 printTab(currentTab);
1432 function execSearch(query, searchWords, filterCrates) {
1433 function getSmallest(arrays, positions, notDuplicates) {
1436 for (var it = 0; it < positions.length; ++it) {
1437 if (arrays[it].length > positions[it] &&
1438 (start === null || start > arrays[it][positions[it]].lev) &&
1439 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1440 start = arrays[it][positions[it]].lev;
1446 function mergeArrays(arrays) {
1449 var notDuplicates = {};
1451 for (var x = 0; x < arrays.length; ++x) {
1454 while (ret.length < MAX_RESULTS) {
1455 var smallest = getSmallest(arrays, positions, notDuplicates);
1457 if (smallest === null) {
1460 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1461 if (arrays[x].length > positions[x] &&
1462 arrays[x][positions[x]].lev === smallest &&
1463 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1464 ret.push(arrays[x][positions[x]]);
1465 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1473 var queries = query.raw.split(",");
1480 for (var i = 0; i < queries.length; ++i) {
1481 query = queries[i].trim();
1482 if (query.length !== 0) {
1483 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1485 results.in_args.push(tmp.in_args);
1486 results.returned.push(tmp.returned);
1487 results.others.push(tmp.others);
1490 if (queries.length > 1) {
1492 "in_args": mergeArrays(results.in_args),
1493 "returned": mergeArrays(results.returned),
1494 "others": mergeArrays(results.others),
1498 "in_args": results.in_args[0],
1499 "returned": results.returned[0],
1500 "others": results.others[0],
1505 function getFilterCrates() {
1506 var elem = document.getElementById("crate-search");
1508 if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1514 function search(e, forced) {
1515 var params = getQueryStringParams();
1516 var query = getQuery(search_input.value.trim());
1522 if (query.query.length === 0) {
1525 if (forced !== true && query.id === currentResults) {
1526 if (query.query.length > 0) {
1527 putBackSearch(search_input);
1532 // Update document title to maintain a meaningful browser history
1533 document.title = "Results for " + query.query + " - Rust";
1535 // Because searching is incremental by character, only the most
1536 // recent search query is added to the browser history.
1537 if (browserSupportsHistoryApi()) {
1538 if (!history.state && !params.search) {
1539 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1541 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1545 var filterCrates = getFilterCrates();
1546 showResults(execSearch(query, index, filterCrates), filterCrates);
1549 function buildIndex(rawSearchIndex) {
1551 var searchWords = [];
1554 for (var crate in rawSearchIndex) {
1555 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1557 searchWords.push(crate);
1560 ty: 1, // == ExternCrate
1563 desc: rawSearchIndex[crate].doc,
1567 // an array of [(Number) item type,
1569 // (String) full path or empty string for previous path,
1570 // (String) description,
1571 // (Number | null) the parent path index to `paths`]
1572 // (Object | null) the type of the function (if any)
1573 var items = rawSearchIndex[crate].items;
1574 // an array of [(Number) item type,
1576 var paths = rawSearchIndex[crate].paths;
1578 // convert `paths` into an object form
1579 var len = paths.length;
1580 for (i = 0; i < len; ++i) {
1581 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1584 // convert `items` into an object form, and construct word indices.
1586 // before any analysis is performed lets gather the search terms to
1587 // search against apart from the rest of the data. This is a quick
1588 // operation that is cached for the life of the page state so that
1589 // all other search operations have access to this cached data for
1590 // faster analysis operations
1593 for (i = 0; i < len; ++i) {
1594 var rawRow = items[i];
1595 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1596 path: rawRow[2] || lastPath, desc: rawRow[3],
1597 parent: paths[rawRow[4]], type: rawRow[5]};
1598 searchIndex.push(row);
1599 if (typeof row.name === "string") {
1600 var word = row.name.toLowerCase();
1601 searchWords.push(word);
1603 searchWords.push("");
1605 lastPath = row.path;
1611 function startSearch() {
1613 var callback = function() {
1614 clearTimeout(searchTimeout);
1615 if (search_input.value.length === 0) {
1616 if (browserSupportsHistoryApi()) {
1617 history.replaceState("", "std - Rust", "?search=");
1619 if (hasClass(main, "content")) {
1620 removeClass(main, "hidden");
1622 var search_c = document.getElementById("search");
1623 if (hasClass(search_c, "content")) {
1624 addClass(search_c, "hidden");
1627 searchTimeout = setTimeout(search, 500);
1630 search_input.onkeyup = callback;
1631 search_input.oninput = callback;
1632 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1634 clearTimeout(searchTimeout);
1637 search_input.onchange = function(e) {
1638 // Do NOT e.preventDefault() here. It will prevent pasting.
1639 clearTimeout(searchTimeout);
1640 // zero-timeout necessary here because at the time of event handler execution the
1641 // pasted content is not in the input field yet. Shouldn’t make any difference for
1643 setTimeout(search, 0);
1645 search_input.onpaste = search_input.onchange;
1647 var selectCrate = document.getElementById('crate-search');
1649 selectCrate.onchange = function() {
1650 search(undefined, true);
1654 // Push and pop states are used to add search results to the browser
1656 if (browserSupportsHistoryApi()) {
1657 // Store the previous <title> so we can revert back to it later.
1658 var previousTitle = document.title;
1660 window.onpopstate = function(e) {
1661 var params = getQueryStringParams();
1662 // When browsing back from search results the main page
1663 // visibility must be reset.
1664 if (!params.search) {
1665 if (hasClass(main, "content")) {
1666 removeClass(main, "hidden");
1668 var search_c = document.getElementById("search");
1669 if (hasClass(search_c, "content")) {
1670 addClass(search_c, "hidden");
1673 // Revert to the previous title manually since the History
1674 // API ignores the title parameter.
1675 document.title = previousTitle;
1676 // When browsing forward to search results the previous
1677 // search will be repeated, so the currentResults are
1678 // cleared to ensure the search is successful.
1679 currentResults = null;
1680 // Synchronize search bar with query string state and
1681 // perform the search. This will empty the bar if there's
1682 // nothing there, which lets you really go back to a
1683 // previous state with nothing in the bar.
1684 if (params.search) {
1685 search_input.value = params.search;
1687 search_input.value = "";
1689 // Some browsers fire "onpopstate" for every page load
1690 // (Chrome), while others fire the event only when actually
1691 // popping a state (Firefox), which is why search() is
1692 // called both here and at the end of the startSearch()
1700 index = buildIndex(rawSearchIndex);
1703 // Draw a convenient sidebar of known crates if we have a listing
1704 if (rootPath === "../" || rootPath === "./") {
1705 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1707 var div = document.createElement("div");
1708 div.className = "block crate";
1709 div.innerHTML = "<h3>Crates</h3>";
1710 var ul = document.createElement("ul");
1711 div.appendChild(ul);
1714 for (var crate in rawSearchIndex) {
1715 if (!rawSearchIndex.hasOwnProperty(crate)) {
1721 for (var i = 0; i < crates.length; ++i) {
1722 var klass = "crate";
1723 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1724 klass += " current";
1726 var link = document.createElement("a");
1727 link.href = rootPath + crates[i] + "/index.html";
1728 link.title = rawSearchIndex[crates[i]].doc;
1729 link.className = klass;
1730 link.textContent = crates[i];
1732 var li = document.createElement("li");
1733 li.appendChild(link);
1736 sidebar.appendChild(div);
1741 window.initSearch = initSearch;
1743 // delayed sidebar rendering.
1744 function initSidebarItems(items) {
1745 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1746 var current = window.sidebarCurrent;
1748 function block(shortty, longty) {
1749 var filtered = items[shortty];
1754 var div = document.createElement("div");
1755 div.className = "block " + shortty;
1756 var h3 = document.createElement("h3");
1757 h3.textContent = longty;
1758 div.appendChild(h3);
1759 var ul = document.createElement("ul");
1761 var length = filtered.length;
1762 for (var i = 0; i < length; ++i) {
1763 var item = filtered[i];
1765 var desc = item[1]; // can be null
1767 var klass = shortty;
1768 if (name === current.name && shortty === current.ty) {
1769 klass += " current";
1772 if (shortty === "mod") {
1773 path = name + "/index.html";
1775 path = shortty + "." + name + ".html";
1777 var link = document.createElement("a");
1778 link.href = current.relpath + path;
1780 link.className = klass;
1781 link.textContent = name;
1782 var li = document.createElement("li");
1783 li.appendChild(link);
1786 div.appendChild(ul);
1788 sidebar.appendChild(div);
1792 block("primitive", "Primitive Types");
1793 block("mod", "Modules");
1794 block("macro", "Macros");
1795 block("struct", "Structs");
1796 block("enum", "Enums");
1797 block("union", "Unions");
1798 block("constant", "Constants");
1799 block("static", "Statics");
1800 block("trait", "Traits");
1801 block("fn", "Functions");
1802 block("type", "Type Definitions");
1803 block("foreigntype", "Foreign Types");
1804 block("keyword", "Keywords");
1807 window.initSidebarItems = initSidebarItems;
1809 window.register_implementors = function(imp) {
1810 var implementors = document.getElementById("implementors-list");
1811 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1813 var libs = Object.getOwnPropertyNames(imp);
1814 var llength = libs.length;
1815 for (var i = 0; i < llength; ++i) {
1816 if (libs[i] === currentCrate) { continue; }
1817 var structs = imp[libs[i]];
1819 var slength = structs.length;
1821 for (var j = 0; j < slength; ++j) {
1822 var struct = structs[j];
1824 var list = struct.synthetic ? synthetic_implementors : implementors;
1826 if (struct.synthetic) {
1827 var stlength = struct.types.length;
1828 for (var k = 0; k < stlength; k++) {
1829 if (window.inlined_types.has(struct.types[k])) {
1830 continue struct_loop;
1832 window.inlined_types.add(struct.types[k]);
1836 var code = document.createElement("code");
1837 code.innerHTML = struct.text;
1839 var x = code.getElementsByTagName("a");
1840 var xlength = x.length;
1841 for (var it = 0; it < xlength; it++) {
1842 var href = x[it].getAttribute("href");
1843 if (href && href.indexOf("http") !== 0) {
1844 x[it].setAttribute("href", rootPath + href);
1847 var display = document.createElement("h3");
1848 addClass(display, "impl");
1849 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1850 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1851 "</tbody></table></span>";
1852 list.appendChild(display);
1856 if (window.pending_implementors) {
1857 window.register_implementors(window.pending_implementors);
1860 function labelForToggleButton(sectionIsCollapsed) {
1861 if (sectionIsCollapsed) {
1862 // button will expand the section
1865 // button will collapse the section
1866 // note that this text is also set in the HTML template in render.rs
1867 return "\u2212"; // "\u2212" is "−" minus sign
1870 function onEveryMatchingChild(elem, className, func) {
1871 if (elem && className && func) {
1872 var length = elem.childNodes.length;
1873 var nodes = elem.childNodes;
1874 for (var i = 0; i < length; ++i) {
1875 if (hasClass(nodes[i], className)) {
1878 onEveryMatchingChild(nodes[i], className, func);
1884 function toggleAllDocs(pageId, fromAutoCollapse) {
1885 var innerToggle = document.getElementById("toggle-all-docs");
1889 if (hasClass(innerToggle, "will-expand")) {
1890 updateLocalStorage("rustdoc-collapse", "false");
1891 removeClass(innerToggle, "will-expand");
1892 onEveryMatchingChild(innerToggle, "inner", function(e) {
1893 e.innerHTML = labelForToggleButton(false);
1895 innerToggle.title = "collapse all docs";
1896 if (fromAutoCollapse !== true) {
1897 onEach(Array.prototype.slice.call(
1898 document.getElementsByClassName("collapse-toggle")),
1900 collapseDocs(e, "show");
1904 updateLocalStorage("rustdoc-collapse", "true");
1905 addClass(innerToggle, "will-expand");
1906 onEveryMatchingChild(innerToggle, "inner", function(e) {
1907 e.innerHTML = labelForToggleButton(true);
1909 innerToggle.title = "expand all docs";
1910 if (fromAutoCollapse !== true) {
1911 onEach(Array.prototype.slice.call(
1912 document.getElementsByClassName("collapse-toggle")),
1914 collapseDocs(e, "hide", pageId);
1920 function collapseDocs(toggle, mode, pageId) {
1921 if (!toggle || !toggle.parentNode) {
1925 function adjustToggle(arg) {
1926 return function(e) {
1927 if (hasClass(e, "toggle-label")) {
1929 e.style.display = "inline-block";
1931 e.style.display = "none";
1934 if (hasClass(e, "inner")) {
1935 e.innerHTML = labelForToggleButton(arg);
1940 function implHider(addOrRemove) {
1941 return function(n) {
1942 var is_method = hasClass(n, "method");
1943 if (is_method || hasClass(n, "type")) {
1944 if (is_method === true) {
1946 addClass(n, "hidden-by-impl-hider");
1948 removeClass(n, "hidden-by-impl-hider");
1951 var ns = n.nextElementSibling;
1954 hasClass(ns, "docblock") ||
1955 hasClass(ns, "stability"))) {
1957 addClass(ns, "hidden-by-impl-hider");
1959 removeClass(ns, "hidden-by-impl-hider");
1961 ns = ns.nextElementSibling;
1972 if (hasClass(toggle.parentNode, "impl") === false) {
1973 relatedDoc = toggle.parentNode.nextElementSibling;
1974 if (hasClass(relatedDoc, "stability")) {
1975 relatedDoc = relatedDoc.nextElementSibling;
1977 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1978 if (mode === "toggle") {
1979 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1985 if (action === "hide") {
1986 addClass(relatedDoc, "hidden-by-usual-hider");
1987 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
1988 addClass(toggle.parentNode, "collapsed");
1989 } else if (action === "show") {
1990 removeClass(relatedDoc, "hidden-by-usual-hider");
1991 removeClass(toggle.parentNode, "collapsed");
1992 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
1996 // we are collapsing the impl block
1998 var parentElem = toggle.parentNode;
1999 relatedDoc = parentElem;
2000 var docblock = relatedDoc.nextElementSibling;
2002 while (hasClass(relatedDoc, "impl-items") === false) {
2003 relatedDoc = relatedDoc.nextElementSibling;
2006 if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2007 (pageId && relatedDoc.getElementById(pageId))) {
2011 // Hide all functions, but not associated types/consts
2013 if (mode === "toggle") {
2014 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2015 hasClass(docblock, "hidden-by-impl-hider")) {
2022 if (action === "show") {
2023 removeClass(relatedDoc, "fns-now-collapsed");
2024 removeClass(docblock, "hidden-by-usual-hider");
2025 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
2026 onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(false));
2027 } else if (action === "hide") {
2028 addClass(relatedDoc, "fns-now-collapsed");
2029 addClass(docblock, "hidden-by-usual-hider");
2030 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
2031 onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(true));
2036 function collapser(e) {
2037 // inherent impl ids are like "impl" or impl-<number>'.
2038 // they will never be hidden by default.
2039 var n = e.parentElement;
2040 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2041 // Automatically minimize all non-inherent impls
2042 if (collapse || hasClass(n, "impl")) {
2043 collapseDocs(e, "hide", pageId);
2048 function autoCollapse(pageId, collapse) {
2050 toggleAllDocs(pageId, true);
2051 } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2052 var impl_list = document.getElementById("implementations-list");
2054 if (impl_list !== null) {
2055 onEach(Array.prototype.slice.call(
2056 impl_list.getElementsByClassName("collapse-toggle")),
2062 var toggles = document.getElementById("toggle-all-docs");
2064 toggles.onclick = toggleAllDocs;
2067 function insertAfter(newNode, referenceNode) {
2068 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2071 function createSimpleToggle(sectionIsCollapsed) {
2072 var toggle = document.createElement("a");
2073 toggle.href = "javascript:void(0)";
2074 toggle.className = "collapse-toggle";
2075 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2080 var toggle = createSimpleToggle(false);
2082 var func = function(e) {
2083 var next = e.nextElementSibling;
2087 if (hasClass(next, "docblock") ||
2088 (hasClass(next, "stability") &&
2089 hasClass(next.nextElementSibling, "docblock"))) {
2090 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2094 var funcImpl = function(e) {
2095 var next = e.nextElementSibling;
2096 if (next && hasClass(next, "docblock")) {
2097 next = next.nextElementSibling;
2102 if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2103 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2107 onEach(Array.prototype.slice.call(document.getElementsByClassName("method")), func);
2108 onEach(Array.prototype.slice.call(document.getElementsByClassName("associatedconstant")), func);
2109 onEach(Array.prototype.slice.call(document.getElementsByClassName("impl")), funcImpl);
2110 var impl_call = function() {};
2111 if (getCurrentValue("rustdoc-method-docs") !== "false") {
2112 impl_call = function(e, newToggle, pageId) {
2113 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2114 // Automatically minimize all non-inherent impls
2115 if (hasClass(e, "impl")) {
2116 collapseDocs(newToggle, "hide", pageId);
2121 var pageId = getPageId();
2122 var newToggle = document.createElement("a");
2123 newToggle.href = "javascript:void(0)";
2124 newToggle.className = "collapse-toggle hidden-default collapsed";
2125 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2126 "</span>] Show hidden undocumented items";
2127 function toggleClicked() {
2128 if (hasClass(this, "collapsed")) {
2129 removeClass(this, "collapsed");
2130 onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("hidden")),
2132 if (hasClass(x, "content") === false) {
2133 removeClass(x, "hidden");
2137 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2138 "</span>] Hide undocumented items";
2140 addClass(this, "collapsed");
2141 onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("x")),
2143 if (hasClass(x, "content") === false) {
2144 addClass(x, "hidden");
2145 removeClass(x, "x");
2148 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2149 "</span>] Show hidden undocumented items";
2152 onEach(Array.prototype.slice.call(document.getElementsByClassName("impl-items")), function(e) {
2153 onEach(Array.prototype.slice.call(e.getElementsByClassName("associatedconstant")), func);
2154 var hiddenElems = e.getElementsByClassName("hidden");
2155 var needToggle = false;
2157 var hlength = hiddenElems.length;
2158 for (var i = 0; i < hlength; ++i) {
2159 if (hasClass(hiddenElems[i], "content") === false &&
2160 hasClass(hiddenElems[i], "docblock") === false) {
2165 if (needToggle === true) {
2166 var inner_toggle = newToggle.cloneNode(true);
2167 inner_toggle.onclick = toggleClicked;
2168 e.insertBefore(inner_toggle, e.firstChild);
2169 impl_call(e, inner_toggle, pageId);
2173 function createToggle(otherMessage, fontSize, extraClass, show) {
2174 var span = document.createElement("span");
2175 span.className = "toggle-label";
2177 span.style.display = "none";
2179 if (!otherMessage) {
2180 span.innerHTML = " Expand description";
2182 span.innerHTML = otherMessage;
2186 span.style.fontSize = fontSize;
2189 var mainToggle = toggle.cloneNode(true);
2190 mainToggle.appendChild(span);
2192 var wrapper = document.createElement("div");
2193 wrapper.className = "toggle-wrapper";
2195 addClass(wrapper, "collapsed");
2196 var inner = mainToggle.getElementsByClassName("inner");
2197 if (inner && inner.length > 0) {
2198 inner[0].innerHTML = "+";
2202 addClass(wrapper, extraClass);
2204 wrapper.appendChild(mainToggle);
2208 var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2209 function buildToggleWrapper(e) {
2210 if (hasClass(e, "autohide")) {
2211 var wrap = e.previousElementSibling;
2212 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2213 var inner_toggle = wrap.childNodes[0];
2214 var extra = e.childNodes[0].tagName === "H3";
2216 e.style.display = "none";
2217 addClass(wrap, "collapsed");
2218 onEach(Array.prototype.slice.call(inner_toggle.getElementsByClassName("inner")),
2220 e.innerHTML = labelForToggleButton(true);
2222 onEach(Array.prototype.slice.call(
2223 inner_toggle.getElementsByClassName("toggle-label")),
2225 e.style.display = "inline-block";
2226 if (extra === true) {
2227 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2232 if (e.parentNode.id === "main") {
2233 var otherMessage = "";
2237 if (hasClass(e, "type-decl")) {
2239 otherMessage = " Show declaration";
2240 if (showItemDeclarations === false) {
2241 extraClass = "collapsed";
2243 } else if (hasClass(e, "sub-variant")) {
2244 otherMessage = " Show fields";
2245 } else if (hasClass(e, "non-exhaustive")) {
2246 otherMessage = " This ";
2247 if (hasClass(e, "non-exhaustive-struct")) {
2248 otherMessage += "struct";
2249 } else if (hasClass(e, "non-exhaustive-enum")) {
2250 otherMessage += "enum";
2251 } else if (hasClass(e, "non-exhaustive-type")) {
2252 otherMessage += "type";
2254 otherMessage += " is marked as non-exhaustive";
2255 } else if (hasClass(e.childNodes[0], "impl-items")) {
2256 extraClass = "marg-left";
2259 e.parentNode.insertBefore(
2260 createToggle(otherMessage,
2263 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2265 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2266 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2271 onEach(Array.prototype.slice.call(document.getElementsByClassName("docblock")),
2272 buildToggleWrapper);
2273 onEach(Array.prototype.slice.call(document.getElementsByClassName("sub-variant")),
2274 buildToggleWrapper);
2276 // In the search display, allows to switch between tabs.
2277 function printTab(nb) {
2278 if (nb === 0 || nb === 1 || nb === 2) {
2282 onEach(Array.prototype.slice.call(document.getElementById("titles").childNodes),
2284 if (nb_copy === 0) {
2285 addClass(elem, "selected");
2287 removeClass(elem, "selected");
2291 onEach(Array.prototype.slice.call(document.getElementById("results").childNodes),
2294 elem.style.display = "";
2296 elem.style.display = "none";
2302 function createToggleWrapper(tog) {
2303 var span = document.createElement("span");
2304 span.className = "toggle-label";
2305 span.style.display = "none";
2306 span.innerHTML = " Expand attributes";
2307 tog.appendChild(span);
2309 var wrapper = document.createElement("div");
2310 wrapper.className = "toggle-wrapper toggle-attributes";
2311 wrapper.appendChild(tog);
2315 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2316 var itemAttributesFunc = function() {};
2317 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2318 itemAttributesFunc = function(x) {
2319 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2322 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2323 onEach(Array.prototype.slice.call(main.getElementsByClassName("attributes")), function(i_e) {
2324 i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2325 itemAttributesFunc(i_e);
2328 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2329 var lineNumbersFunc = function() {};
2330 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2331 lineNumbersFunc = function(x) {
2332 var count = x.textContent.split("\n").length;
2334 for (var i = 0; i < count; ++i) {
2337 var node = document.createElement("pre");
2338 addClass(node, "line-number");
2339 node.innerHTML = elems.join("\n");
2340 x.parentNode.insertBefore(node, x);
2343 onEach(Array.prototype.slice.call(document.getElementsByClassName("rust-example-rendered")),
2345 if (hasClass(e, "compile_fail")) {
2346 e.addEventListener("mouseover", function(event) {
2347 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2349 e.addEventListener("mouseout", function(event) {
2350 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2352 } else if (hasClass(e, "ignore")) {
2353 e.addEventListener("mouseover", function(event) {
2354 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2356 e.addEventListener("mouseout", function(event) {
2357 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2363 function showModal(content) {
2364 var modal = document.createElement("div");
2365 modal.id = "important";
2366 addClass(modal, "modal");
2367 modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2368 "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2370 document.getElementsByTagName("body")[0].appendChild(modal);
2371 document.getElementById("modal-close").onclick = hideModal;
2372 modal.onclick = hideModal;
2375 function hideModal() {
2376 var modal = document.getElementById("important");
2378 modal.parentNode.removeChild(modal);
2382 onEach(Array.prototype.slice.call(document.getElementsByClassName("important-traits")),
2384 e.onclick = function() {
2385 showModal(e.lastElementChild.innerHTML);
2389 function putBackSearch(search_input) {
2390 if (search_input.value !== "") {
2391 addClass(main, "hidden");
2392 removeClass(document.getElementById("search"), "hidden");
2393 if (browserSupportsHistoryApi()) {
2394 history.replaceState(search_input.value,
2396 "?search=" + encodeURIComponent(search_input.value));
2402 search_input.onfocus = function() {
2403 putBackSearch(this);
2407 var params = getQueryStringParams();
2408 if (params && params.search) {
2409 addClass(main, "hidden");
2410 var search = document.getElementById("search");
2411 removeClass(search, "hidden");
2412 search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2415 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2417 sidebar_menu.onclick = function() {
2418 var sidebar = document.getElementsByClassName("sidebar")[0];
2419 if (hasClass(sidebar, "mobile") === true) {
2427 window.onresize = function() {
2431 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2433 if (window.location.hash && window.location.hash.length > 0) {
2434 expandSection(window.location.hash.replace(/^#/, ""));
2438 onEach(Array.prototype.slice.call(main.childNodes), function(e) {
2439 if (e.tagName === "H2" || e.tagName === "H3") {
2440 e.nextElementSibling.style.display = "block";
2445 function addSearchOptions(crates) {
2446 var elem = document.getElementById('crate-search');
2451 var crates_text = [];
2452 for (var crate in crates) {
2453 if (crates.hasOwnProperty(crate)) {
2454 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();