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.
13 /*jslint browser: true, es5: true */
14 /*globals $: true, rootPath: true */
19 // This mapping table should match the discriminants of
20 // `rustdoc::html::item_type::ItemType` type in Rust.
21 var itemTypes = ["mod",
44 var search_input = document.getElementsByClassName('search-input')[0];
46 // On the search screen, so you remain on the last tab you opened.
49 // 1 for "In Parameters"
50 // 2 for "In Return Types"
53 var themesWidth = null;
55 var titleBeforeSearch = document.title;
57 if (!String.prototype.startsWith) {
58 String.prototype.startsWith = function(searchString, position) {
59 position = position || 0;
60 return this.indexOf(searchString, position) === position;
63 if (!String.prototype.endsWith) {
64 String.prototype.endsWith = function(suffix, length) {
65 var l = length || this.length;
66 return this.indexOf(suffix, l - suffix.length) !== -1;
70 function getPageId() {
71 var id = document.location.href.split('#')[1];
73 return id.split('?')[0].split('&')[0];
78 function hasClass(elem, className) {
79 if (elem && className && elem.className) {
80 var elemClass = elem.className;
81 var start = elemClass.indexOf(className);
84 } else if (elemClass.length === className.length) {
87 if (start > 0 && elemClass[start - 1] !== ' ') {
90 var end = start + className.length;
91 return !(end < elemClass.length && elemClass[end] !== ' ');
93 if (start > 0 && elemClass[start - 1] !== ' ') {
96 var end = start + className.length;
97 return !(end < elemClass.length && elemClass[end] !== ' ');
102 function addClass(elem, className) {
103 if (elem && className && !hasClass(elem, className)) {
104 if (elem.className && elem.className.length > 0) {
105 elem.className += ' ' + className;
107 elem.className = className;
112 function removeClass(elem, className) {
113 if (elem && className && elem.className) {
114 elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
119 function isHidden(elem) {
120 return (elem.offsetParent === null)
123 function showSidebar() {
124 var elems = document.getElementsByClassName("sidebar-elems")[0];
126 addClass(elems, "show-it");
128 var sidebar = document.getElementsByClassName('sidebar')[0];
130 addClass(sidebar, 'mobile');
131 var filler = document.getElementById("sidebar-filler");
133 var div = document.createElement("div");
134 div.id = "sidebar-filler";
135 sidebar.appendChild(div);
138 var themePicker = document.getElementsByClassName("theme-picker");
139 if (themePicker && themePicker.length > 0) {
140 themePicker[0].style.display = "none";
144 function hideSidebar() {
145 var elems = document.getElementsByClassName("sidebar-elems")[0];
147 removeClass(elems, "show-it");
149 var sidebar = document.getElementsByClassName('sidebar')[0];
150 removeClass(sidebar, 'mobile');
151 var filler = document.getElementById("sidebar-filler");
155 document.getElementsByTagName("body")[0].style.marginTop = '';
156 var themePicker = document.getElementsByClassName("theme-picker");
157 if (themePicker && themePicker.length > 0) {
158 themePicker[0].style.display = null;
162 // used for special search precedence
163 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
164 var TY_KEYWORD = itemTypes.indexOf("keyword");
166 onEach(document.getElementsByClassName('js-only'), function(e) {
167 removeClass(e, 'js-only');
170 function getQueryStringParams() {
172 window.location.search.substring(1).split("&").
174 var pair = s.split("=");
175 params[decodeURIComponent(pair[0])] =
176 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
181 function browserSupportsHistoryApi() {
182 return document.location.protocol != "file:" &&
183 window.history && typeof window.history.pushState === "function";
186 function highlightSourceLines(ev) {
187 // If we're in mobile mode, we should add the sidebar in any case.
189 var search = document.getElementById("search");
190 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
192 from = parseInt(match[1], 10);
193 to = Math.min(50000, parseInt(match[2] || match[1], 10));
194 from = Math.min(from, to);
195 var elem = document.getElementById(from);
200 var x = document.getElementById(from);
205 onEach(document.getElementsByClassName('line-numbers'), function(e) {
206 onEach(e.getElementsByTagName('span'), function(i_e) {
207 removeClass(i_e, 'line-highlighted');
210 for (i = from; i <= to; ++i) {
211 addClass(document.getElementById(i), 'line-highlighted');
213 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
214 addClass(search, "hidden");
215 removeClass(document.getElementById("main"), "hidden");
216 var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
217 if (browserSupportsHistoryApi()) {
218 history.replaceState(hash, "", "?search=#" + hash);
220 var elem = document.getElementById(hash);
222 elem.scrollIntoView();
227 function expandSection(id) {
228 var elem = document.getElementById(id);
229 if (elem && isHidden(elem)) {
230 var h3 = elem.parentNode.previousSibling;
231 if (h3 && h3.tagName !== 'H3') {
232 h3 = h3.previousSibling; // skip div.docblock
236 var collapses = h3.getElementsByClassName("collapse-toggle");
237 if (collapses.length > 0) {
238 // The element is not visible, we need to make it appear!
239 collapseDocs(collapses[0], "show");
245 highlightSourceLines(null);
246 window.onhashchange = highlightSourceLines;
248 // Gets the human-readable string for the virtual-key code of the
249 // given KeyboardEvent, ev.
251 // This function is meant as a polyfill for KeyboardEvent#key,
252 // since it is not supported in Trident. We also test for
253 // KeyboardEvent#keyCode because the handleShortcut handler is
254 // also registered for the keydown event, because Blink doesn't fire
255 // keypress on hitting the Escape key.
257 // So I guess you could say things are getting pretty interoperable.
258 function getVirtualKey(ev) {
259 if ("key" in ev && typeof ev.key != "undefined")
262 var c = ev.charCode || ev.keyCode;
265 return String.fromCharCode(c);
268 function displayHelp(display, ev) {
269 if (display === true) {
270 if (hasClass(help, "hidden")) {
272 removeClass(help, "hidden");
273 addClass(document.body, "blur");
275 } else if (!hasClass(help, "hidden")) {
277 addClass(help, "hidden");
278 removeClass(document.body, "blur");
282 function handleEscape(ev, help) {
284 var search = document.getElementById("search");
285 if (!hasClass(help, "hidden")) {
286 displayHelp(false, ev);
287 } else if (!hasClass(search, "hidden")) {
289 addClass(search, "hidden");
290 removeClass(document.getElementById("main"), "hidden");
291 document.title = titleBeforeSearch;
296 function handleShortcut(ev) {
297 // Don't interfere with browser shortcuts
298 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
302 var help = document.getElementById("help");
303 if (document.activeElement.tagName === "INPUT") {
304 switch (getVirtualKey(ev)) {
306 handleEscape(ev, help);
310 switch (getVirtualKey(ev)) {
312 handleEscape(ev, help);
317 displayHelp(false, ev);
332 displayHelp(true, ev);
339 function findParentElement(elem, tagName) {
341 if (elem && elem.tagName === tagName) {
344 } while (elem = elem.parentNode);
348 document.onkeypress = handleShortcut;
349 document.onkeydown = handleShortcut;
350 document.onclick = function(ev) {
351 if (hasClass(ev.target, 'collapse-toggle')) {
352 collapseDocs(ev.target, "toggle");
353 } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
354 collapseDocs(ev.target.parentNode, "toggle");
355 } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
358 var set_fragment = function(name) {
359 if (browserSupportsHistoryApi()) {
360 history.replaceState(null, null, '#' + name);
363 location.replace('#' + name);
367 var cur_id = parseInt(ev.target.id, 10);
369 if (ev.shiftKey && prev_id) {
370 if (prev_id > cur_id) {
376 set_fragment(prev_id + '-' + cur_id);
380 set_fragment(cur_id);
382 } else if (!hasClass(document.getElementById("help"), "hidden")) {
383 addClass(document.getElementById("help"), "hidden");
384 removeClass(document.body, "blur");
386 // Making a collapsed element visible on onhashchange seems
388 var a = findParentElement(ev.target, 'A');
390 expandSection(a.hash.replace(/^#/, ''));
395 var x = document.getElementsByClassName('version-selector');
397 x[0].onchange = function() {
399 url = document.location.href,
401 len = rootPath.match(/\.\.\//g).length + 1;
403 for (i = 0; i < len; ++i) {
404 match = url.match(/\/[^\/]*$/);
406 stripped = match[0] + stripped;
408 url = url.substring(0, url.length - match[0].length);
411 url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
413 document.location.href = url;
418 * A function to compute the Levenshtein distance between two strings
419 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
420 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
421 * This code is an unmodified version of the code written by Marco de Wit
422 * and was found at http://stackoverflow.com/a/18514751/745719
424 var levenshtein_row2 = [];
425 function levenshtein(s1, s2) {
429 var s1_len = s1.length, s2_len = s2.length;
430 if (s1_len && s2_len) {
431 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
432 while (i1 < s1_len) {
435 while (i2 < s2_len) {
436 c2 = s2.charCodeAt(i2);
440 for (i1 = 0; i1 < s1_len; ++i1) {
441 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
443 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
449 return s1_len + s2_len;
452 function initSearch(rawSearchIndex) {
453 var currentResults, index, searchIndex;
454 var MAX_LEV_DISTANCE = 3;
455 var MAX_RESULTS = 200;
456 var GENERICS_DATA = 1;
460 var params = getQueryStringParams();
462 // Populate search bar with query string search term when provided,
463 // but only if the input bar is empty. This avoid the obnoxious issue
464 // where you start trying to do a search, and the index loads, and
465 // suddenly your search is gone!
466 if (search_input.value === "") {
467 search_input.value = params.search || '';
471 * Executes the query and builds an index of results
472 * @param {[Object]} query [The user query]
473 * @param {[type]} searchWords [The list of search words to query
475 * @return {[type]} [A search index of results]
477 function execQuery(query, searchWords) {
478 function itemTypeFromName(typename) {
479 for (var i = 0; i < itemTypes.length; ++i) {
480 if (itemTypes[i] === typename) {
487 var valLower = query.query.toLowerCase(),
489 typeFilter = itemTypeFromName(query.type),
490 results = {}, results_in_args = {}, results_returned = {},
491 split = valLower.split("::");
493 for (var z = 0; z < split.length; ++z) {
494 if (split[z] === "") {
500 function transformResults(results, isType) {
502 for (i = 0; i < results.length; ++i) {
503 if (results[i].id > -1) {
504 var obj = searchIndex[results[i].id];
505 obj.lev = results[i].lev;
506 if (isType !== true || obj.type) {
507 var res = buildHrefAndPath(obj);
508 obj.displayPath = pathSplitter(res[0]);
509 obj.fullPath = obj.displayPath + obj.name;
510 // To be sure than it some items aren't considered as duplicate.
511 obj.fullPath += '|' + obj.ty;
514 if (out.length >= MAX_RESULTS) {
523 function sortResults(results, isType) {
525 for (var entry in results) {
526 if (results.hasOwnProperty(entry)) {
527 ar.push(results[entry]);
531 var nresults = results.length;
532 for (var i = 0; i < nresults; ++i) {
533 results[i].word = searchWords[results[i].id];
534 results[i].item = searchIndex[results[i].id] || {};
536 // if there are no results then return to default and fail
537 if (results.length === 0) {
541 results.sort(function(aaa, bbb) {
544 // Sort by non levenshtein results and then levenshtein results by the distance
545 // (less changes required to match means higher rankings)
548 if (a !== b) { return a - b; }
550 // sort by crate (non-current crate goes later)
551 a = (aaa.item.crate !== window.currentCrate);
552 b = (bbb.item.crate !== window.currentCrate);
553 if (a !== b) { return a - b; }
555 // sort by exact match (mismatch goes later)
556 a = (aaa.word !== valLower);
557 b = (bbb.word !== valLower);
558 if (a !== b) { return a - b; }
560 // sort by item name length (longer goes later)
563 if (a !== b) { return a - b; }
565 // sort by item name (lexicographically larger goes later)
568 if (a !== b) { return (a > b ? +1 : -1); }
570 // sort by index of keyword in item name (no literal occurrence goes later)
573 if (a !== b) { return a - b; }
574 // (later literal occurrence, if any, goes later)
577 if (a !== b) { return a - b; }
579 // special precedence for primitive and keyword pages
580 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
581 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
584 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
585 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
589 // sort by description (no description goes later)
590 a = (aaa.item.desc === '');
591 b = (bbb.item.desc === '');
592 if (a !== b) { return a - b; }
594 // sort by type (later occurrence in `itemTypes` goes later)
597 if (a !== b) { return a - b; }
599 // sort by path (lexicographically larger goes later)
602 if (a !== b) { return (a > b ? +1 : -1); }
608 for (var i = 0; i < results.length; ++i) {
609 var result = results[i];
611 // this validation does not make sense when searching by types
612 if (result.dontValidate) {
615 var name = result.item.name.toLowerCase(),
616 path = result.item.path.toLowerCase(),
617 parent = result.item.parent;
619 if (isType !== true &&
620 validateResult(name, path, split, parent) === false)
625 return transformResults(results);
628 function extractGenerics(val) {
629 val = val.toLowerCase();
630 if (val.indexOf('<') !== -1) {
631 var values = val.substring(val.indexOf('<') + 1, val.lastIndexOf('>'));
633 name: val.substring(0, val.indexOf('<')),
634 generics: values.split(/\s*,\s*/),
643 function checkGenerics(obj, val) {
644 // The names match, but we need to be sure that all generics kinda
646 var lev_distance = MAX_LEV_DISTANCE + 1;
647 if (val.generics.length > 0) {
648 if (obj.length > GENERICS_DATA &&
649 obj[GENERICS_DATA].length >= val.generics.length) {
650 var elems = obj[GENERICS_DATA].slice(0);
653 // We need to find the type that matches the most to remove it in order
655 for (var y = 0; y < val.generics.length; ++y) {
656 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
657 for (var x = 0; x < elems.length; ++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;
682 if (obj[NAME] === val.name) {
683 if (literalSearch === true) {
684 if (val.generics && val.generics.length !== 0) {
685 if (obj.length > GENERICS_DATA &&
686 obj[GENERICS_DATA].length >= val.generics.length) {
687 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 for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
724 if (obj[GENERICS_DATA][x] === val.name) {
731 var lev_distance = Math.min(levenshtein(obj[NAME], val.name),
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 for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
738 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
742 // Now whatever happens, the returned distance is "less good" so we should mark it
743 // as such, and so we add 1 to the distance to make it "less good".
744 return lev_distance + 1;
747 function findArg(obj, val, literalSearch) {
748 var lev_distance = MAX_LEV_DISTANCE + 1;
750 if (obj && obj.type && obj.type[INPUTS_DATA] &&
751 obj.type[INPUTS_DATA].length > 0) {
752 for (var i = 0; i < obj.type[INPUTS_DATA].length; i++) {
753 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
754 if (literalSearch === true && tmp === true) {
757 lev_distance = Math.min(tmp, lev_distance);
758 if (lev_distance === 0) {
763 return literalSearch === true ? false : lev_distance;
766 function checkReturned(obj, val, literalSearch) {
767 var lev_distance = MAX_LEV_DISTANCE + 1;
769 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
770 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
771 if (literalSearch === true && tmp === true) {
774 lev_distance = Math.min(tmp, lev_distance);
775 if (lev_distance === 0) {
779 return literalSearch === true ? false : lev_distance;
782 function checkPath(contains, lastElem, ty) {
783 if (contains.length === 0) {
786 var ret_lev = MAX_LEV_DISTANCE + 1;
787 var path = ty.path.split("::");
789 if (ty.parent && ty.parent.name) {
790 path.push(ty.parent.name.toLowerCase());
793 if (contains.length > path.length) {
794 return MAX_LEV_DISTANCE + 1;
796 for (var i = 0; i < path.length; ++i) {
797 if (i + contains.length > path.length) {
802 for (var x = 0; x < contains.length; ++x) {
803 var lev = levenshtein(path[i + x], contains[x]);
804 if (lev > MAX_LEV_DISTANCE) {
810 if (aborted === false) {
811 ret_lev = Math.min(ret_lev, Math.round(lev_total / contains.length));
817 function typePassesFilter(filter, type) {
819 if (filter < 0) return true;
822 if (filter === type) return true;
824 // Match related items
825 var name = itemTypes[type];
826 switch (itemTypes[filter]) {
828 return (name == "associatedconstant");
830 return (name == "method" || name == "tymethod");
832 return (name == "primitive" || name == "keyword");
839 function generateId(ty) {
840 if (ty.parent && ty.parent.name) {
841 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
843 return itemTypes[ty.ty] + ty.path + ty.name;
846 // quoted values mean literal search
847 var nSearchWords = searchWords.length;
848 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
849 val.charAt(val.length - 1) === val.charAt(0))
851 val = extractGenerics(val.substr(1, val.length - 2));
852 for (var i = 0; i < nSearchWords; ++i) {
853 var in_args = findArg(searchIndex[i], val, true);
854 var returned = checkReturned(searchIndex[i], val, true);
855 var ty = searchIndex[i];
856 var fullId = generateId(ty);
858 if (searchWords[i] === val.name) {
859 // filter type: ... queries
860 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
861 results[fullId] === undefined)
863 results[fullId] = {id: i, index: -1};
865 } else if ((in_args === true || returned === true) &&
866 typePassesFilter(typeFilter, searchIndex[i].ty)) {
867 if (in_args === true || returned === true) {
868 if (in_args === true) {
869 results_in_args[fullId] = {
875 if (returned === true) {
876 results_returned[fullId] = {
891 query.inputs = [val];
895 } else if (val.search("->") > -1) {
896 var trimmer = function(s) { return s.trim(); };
897 var parts = val.split("->").map(trimmer);
898 var input = parts[0];
899 // sort inputs so that order does not matter
900 var inputs = input.split(",").map(trimmer).sort();
901 for (var i = 0; i < inputs.length; ++i) {
902 inputs[i] = extractGenerics(inputs[i]);
904 var output = extractGenerics(parts[1]);
906 for (var i = 0; i < nSearchWords; ++i) {
907 var type = searchIndex[i].type;
908 var ty = searchIndex[i];
912 var fullId = generateId(ty);
914 // allow searching for void (no output) functions as well
915 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
916 var returned = checkReturned(ty, output, true);
917 if (output.name === "*" || returned === true) {
925 for (var it = 0; allFound === true && it < inputs.length; it++) {
926 allFound = checkType(type, inputs[it], true);
930 if (in_args === true) {
931 results_in_args[fullId] = {
937 if (returned === true) {
938 results_returned[fullId] = {
944 if (module === true) {
953 query.inputs = inputs.map(function(input) {
956 query.output = output.name;
958 query.inputs = [val];
961 // gather matching search results up to a certain maximum
962 val = val.replace(/\_/g, "");
964 var valGenerics = extractGenerics(val);
966 var paths = valLower.split("::");
968 for (j = 0; j < paths.length; ++j) {
969 if (paths[j] === "") {
974 val = paths[paths.length - 1];
975 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
977 for (j = 0; j < nSearchWords; ++j) {
979 var ty = searchIndex[j];
984 if (paths.length > 1) {
985 var lev = checkPath(contains, paths[paths.length - 1], ty);
986 if (lev > MAX_LEV_DISTANCE) {
988 } else if (lev > 0) {
993 var returned = MAX_LEV_DISTANCE + 1;
994 var in_args = MAX_LEV_DISTANCE + 1;
996 // we want lev results to go lower than others
997 var lev = MAX_LEV_DISTANCE + 1;
998 var fullId = generateId(ty);
1000 if (searchWords[j].indexOf(split[i]) > -1 ||
1001 searchWords[j].indexOf(val) > -1 ||
1002 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1004 // filter type: ... queries
1005 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1006 index = searchWords[j].replace(/_/g, "").indexOf(val);
1009 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1010 if (typePassesFilter(typeFilter, ty.ty) === false) {
1011 lev = MAX_LEV_DISTANCE + 1;
1016 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1017 if (typePassesFilter(typeFilter, ty.ty) === false) {
1018 in_args = MAX_LEV_DISTANCE + 1;
1021 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1022 if (typePassesFilter(typeFilter, ty.ty) === false) {
1023 returned = MAX_LEV_DISTANCE + 1;
1028 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1029 if (val.length < 6) {
1035 if (in_args <= MAX_LEV_DISTANCE) {
1036 if (results_in_args[fullId] === undefined) {
1037 results_in_args[fullId] = {
1043 results_in_args[fullId].lev =
1044 Math.min(results_in_args[fullId].lev, in_args);
1046 if (returned <= MAX_LEV_DISTANCE) {
1047 if (results_returned[fullId] === undefined) {
1048 results_returned[fullId] = {
1054 results_returned[fullId].lev =
1055 Math.min(results_returned[fullId].lev, returned);
1057 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1058 if (index !== -1 && paths.length < 2) {
1061 if (results[fullId] === undefined) {
1068 results[fullId].lev = Math.min(results[fullId].lev, lev);
1074 'in_args': sortResults(results_in_args, true),
1075 'returned': sortResults(results_returned, true),
1076 'others': sortResults(results),
1078 if (ALIASES && ALIASES[window.currentCrate] &&
1079 ALIASES[window.currentCrate][query.raw]) {
1080 var aliases = ALIASES[window.currentCrate][query.raw];
1081 for (var i = 0; i < aliases.length; ++i) {
1082 aliases[i].is_alias = true;
1083 aliases[i].alias = query.raw;
1084 aliases[i].path = aliases[i].p;
1085 var res = buildHrefAndPath(aliases[i]);
1086 aliases[i].displayPath = pathSplitter(res[0]);
1087 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1088 aliases[i].href = res[1];
1089 ret['others'].unshift(aliases[i]);
1090 if (ret['others'].length > MAX_RESULTS) {
1091 ret['others'].pop();
1099 * Validate performs the following boolean logic. For example:
1100 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1101 * exists in (name || path || parent) OR => ("file" && "open") exists in
1104 * This could be written functionally, but I wanted to minimise
1105 * functions on stack.
1107 * @param {[string]} name [The name of the result]
1108 * @param {[string]} path [The path of the result]
1109 * @param {[string]} keys [The keys to be used (["file", "open"])]
1110 * @param {[object]} parent [The parent of the result]
1111 * @return {[boolean]} [Whether the result is valid or not]
1113 function validateResult(name, path, keys, parent) {
1114 for (var i = 0; i < keys.length; ++i) {
1115 // each check is for validation so we negate the conditions and invalidate
1117 // check for an exact name match
1118 name.indexOf(keys[i]) > -1 ||
1119 // then an exact path match
1120 path.indexOf(keys[i]) > -1 ||
1121 // next if there is a parent, check for exact parent match
1122 (parent !== undefined &&
1123 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1124 // lastly check to see if the name was a levenshtein match
1125 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1132 function getQuery(raw) {
1133 var matches, type, query;
1136 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1138 type = matches[1].replace(/^const$/, 'constant');
1139 query = query.substring(matches[0].length);
1150 function initSearchNav() {
1153 var click_func = function(e) {
1155 // to retrieve the real "owner" of the event.
1156 while (el.tagName !== 'TR') {
1159 var dst = e.target.getElementsByTagName('a');
1160 if (dst.length < 1) {
1164 if (window.location.pathname === dst.pathname) {
1165 addClass(document.getElementById('search'), 'hidden');
1166 removeClass(document.getElementById('main'), 'hidden');
1167 document.location.href = dst.href;
1170 var mouseover_func = function(e) {
1172 // to retrieve the real "owner" of the event.
1173 while (el.tagName !== 'TR') {
1176 clearTimeout(hoverTimeout);
1177 hoverTimeout = setTimeout(function() {
1178 onEach(document.getElementsByClassName('search-results'), function(e) {
1179 onEach(e.getElementsByClassName('result'), function(i_e) {
1180 removeClass(i_e, 'highlighted');
1183 addClass(el, 'highlighted');
1186 onEach(document.getElementsByClassName('search-results'), function(e) {
1187 onEach(e.getElementsByClassName('result'), function(i_e) {
1188 i_e.onclick = click_func;
1189 i_e.onmouseover = mouseover_func;
1193 search_input.onkeydown = function(e) {
1194 // "actives" references the currently highlighted item in each search tab.
1195 // Each array in "actives" represents a tab.
1196 var actives = [[], [], []];
1197 // "current" is used to know which tab we're looking into.
1199 onEach(document.getElementsByClassName('search-results'), function(e) {
1200 onEach(e.getElementsByClassName('highlighted'), function(e) {
1201 actives[current].push(e);
1206 if (e.which === 38) { // up
1207 if (!actives[currentTab].length ||
1208 !actives[currentTab][0].previousElementSibling) {
1212 addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
1213 removeClass(actives[currentTab][0], 'highlighted');
1214 } else if (e.which === 40) { // down
1215 if (!actives[currentTab].length) {
1216 var results = document.getElementsByClassName('search-results');
1217 if (results.length > 0) {
1218 var res = results[currentTab].getElementsByClassName('result');
1219 if (res.length > 0) {
1220 addClass(res[0], 'highlighted');
1223 } else if (actives[currentTab][0].nextElementSibling) {
1224 addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
1225 removeClass(actives[currentTab][0], 'highlighted');
1227 } else if (e.which === 13) { // return
1228 if (actives[currentTab].length) {
1229 document.location.href =
1230 actives[currentTab][0].getElementsByTagName('a')[0].href;
1232 } else if (e.which === 9) { // tab
1234 printTab(currentTab > 0 ? currentTab - 1 : 2);
1236 printTab(currentTab > 1 ? 0 : currentTab + 1);
1239 } else if (e.which === 16) { // shift
1240 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1241 } else if (e.which === 27) { // escape
1242 removeClass(actives[currentTab][0], 'highlighted');
1243 search_input.value = '';
1245 } else if (actives[currentTab].length > 0) {
1246 removeClass(actives[currentTab][0], 'highlighted');
1251 function buildHrefAndPath(item) {
1254 var type = itemTypes[item.ty];
1255 var name = item.name;
1257 if (type === 'mod') {
1258 displayPath = item.path + '::';
1259 href = rootPath + item.path.replace(/::/g, '/') + '/' +
1260 name + '/index.html';
1261 } else if (type === "primitive" || type === "keyword") {
1263 href = rootPath + item.path.replace(/::/g, '/') +
1264 '/' + type + '.' + name + '.html';
1265 } else if (type === "externcrate") {
1267 href = rootPath + name + '/index.html';
1268 } else if (item.parent !== undefined) {
1269 var myparent = item.parent;
1270 var anchor = '#' + type + '.' + name;
1271 var parentType = itemTypes[myparent.ty];
1272 if (parentType === "primitive") {
1273 displayPath = myparent.name + '::';
1275 displayPath = item.path + '::' + myparent.name + '::';
1277 href = rootPath + item.path.replace(/::/g, '/') +
1279 '.' + myparent.name +
1282 displayPath = item.path + '::';
1283 href = rootPath + item.path.replace(/::/g, '/') +
1284 '/' + type + '.' + name + '.html';
1286 return [displayPath, href];
1289 function escape(content) {
1290 var h1 = document.createElement('h1');
1291 h1.textContent = content;
1292 return h1.innerHTML;
1295 function pathSplitter(path) {
1296 var tmp = '<span>' + path.replace(/::/g, '::</span><span>');
1297 if (tmp.endsWith("<span>")) {
1298 return tmp.slice(0, tmp.length - 6);
1303 function addTab(array, query, display) {
1304 var extraStyle = '';
1305 if (display === false) {
1306 extraStyle = ' style="display: none;"';
1310 var duplicates = {};
1312 if (array.length > 0) {
1313 output = '<table class="search-results"' + extraStyle + '>';
1315 array.forEach(function(item) {
1319 type = itemTypes[item.ty];
1321 if (item.is_alias !== true) {
1322 if (duplicates[item.fullPath]) {
1325 duplicates[item.fullPath] = true;
1329 output += '<tr class="' + type + ' result"><td>' +
1330 '<a href="' + item.href + '">' +
1331 (item.is_alias === true ?
1332 ('<span class="alias"><b>' + item.alias + ' </b></span><span ' +
1333 'class="grey"><i> - see </i></span>') : '') +
1334 item.displayPath + '<span class="' + type + '">' +
1335 name + '</span></a></td><td>' +
1336 '<a href="' + item.href + '">' +
1337 '<span class="desc">' + escape(item.desc) +
1338 ' </span></a></td></tr>';
1340 output += '</table>';
1342 output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
1343 'Try on <a href="https://duckduckgo.com/?q=' +
1344 encodeURIComponent('rust ' + query.query) +
1345 '">DuckDuckGo</a>?</div>';
1347 return [output, length];
1350 function makeTabHeader(tabNb, text, nbElems) {
1351 if (currentTab === tabNb) {
1352 return '<div class="selected">' + text +
1353 ' <div class="count">(' + nbElems + ')</div></div>';
1355 return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
1358 function showResults(results) {
1359 if (results['others'].length === 1 &&
1360 getCurrentValue('rustdoc-go-to-only-result') === "true") {
1361 var elem = document.createElement('a');
1362 elem.href = results['others'][0].href;
1363 elem.style.display = 'none';
1364 // For firefox, we need the element to be in the DOM so it can be clicked.
1365 document.body.appendChild(elem);
1368 var query = getQuery(search_input.value);
1370 currentResults = query.id;
1372 var ret_others = addTab(results['others'], query);
1373 var ret_in_args = addTab(results['in_args'], query, false);
1374 var ret_returned = addTab(results['returned'], query, false);
1376 var output = '<h1>Results for ' + escape(query.query) +
1377 (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>' +
1378 '<div id="titles">' +
1379 makeTabHeader(0, "In Names", ret_others[1]) +
1380 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1381 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1382 '</div><div id="results">' +
1383 ret_others[0] + ret_in_args[0] + ret_returned[0] + '</div>';
1385 addClass(document.getElementById('main'), 'hidden');
1386 var search = document.getElementById('search');
1387 removeClass(search, 'hidden');
1388 search.innerHTML = output;
1389 var tds = search.getElementsByTagName('td');
1391 if (tds.length > 0) {
1392 td_width = tds[0].offsetWidth;
1394 var width = search.offsetWidth - 40 - td_width;
1395 onEach(search.getElementsByClassName('desc'), function(e) {
1396 e.style.width = width + 'px';
1399 var elems = document.getElementById('titles').childNodes;
1400 elems[0].onclick = function() { printTab(0); };
1401 elems[1].onclick = function() { printTab(1); };
1402 elems[2].onclick = function() { printTab(2); };
1403 printTab(currentTab);
1406 function execSearch(query, searchWords) {
1407 var queries = query.raw.split(",");
1414 for (var i = 0; i < queries.length; ++i) {
1415 var query = queries[i].trim();
1416 if (query.length !== 0) {
1417 var tmp = execQuery(getQuery(query), searchWords);
1419 results['in_args'].push(tmp['in_args']);
1420 results['returned'].push(tmp['returned']);
1421 results['others'].push(tmp['others']);
1424 if (queries.length > 1) {
1425 function getSmallest(arrays, positions, notDuplicates) {
1428 for (var it = 0; it < positions.length; ++it) {
1429 if (arrays[it].length > positions[it] &&
1430 (start === null || start > arrays[it][positions[it]].lev) &&
1431 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1432 start = arrays[it][positions[it]].lev;
1438 function mergeArrays(arrays) {
1441 var notDuplicates = {};
1443 for (var x = 0; x < arrays.length; ++x) {
1446 while (ret.length < MAX_RESULTS) {
1447 var smallest = getSmallest(arrays, positions, notDuplicates);
1449 if (smallest === null) {
1452 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1453 if (arrays[x].length > positions[x] &&
1454 arrays[x][positions[x]].lev === smallest &&
1455 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1456 ret.push(arrays[x][positions[x]]);
1457 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1466 'in_args': mergeArrays(results['in_args']),
1467 'returned': mergeArrays(results['returned']),
1468 'others': mergeArrays(results['others']),
1472 'in_args': results['in_args'][0],
1473 'returned': results['returned'][0],
1474 'others': results['others'][0],
1479 function search(e) {
1480 var params = getQueryStringParams();
1481 var query = getQuery(search_input.value.trim());
1487 if (query.query.length === 0 || query.id === currentResults) {
1488 if (query.query.length > 0) {
1489 putBackSearch(search_input);
1494 // Update document title to maintain a meaningful browser history
1495 document.title = "Results for " + query.query + " - Rust";
1497 // Because searching is incremental by character, only the most
1498 // recent search query is added to the browser history.
1499 if (browserSupportsHistoryApi()) {
1500 if (!history.state && !params.search) {
1501 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1503 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1507 showResults(execSearch(query, index));
1510 function buildIndex(rawSearchIndex) {
1512 var searchWords = [];
1513 for (var crate in rawSearchIndex) {
1514 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1516 searchWords.push(crate);
1519 ty: 1, // == ExternCrate
1522 desc: rawSearchIndex[crate].doc,
1526 // an array of [(Number) item type,
1528 // (String) full path or empty string for previous path,
1529 // (String) description,
1530 // (Number | null) the parent path index to `paths`]
1531 // (Object | null) the type of the function (if any)
1532 var items = rawSearchIndex[crate].items;
1533 // an array of [(Number) item type,
1535 var paths = rawSearchIndex[crate].paths;
1537 // convert `paths` into an object form
1538 var len = paths.length;
1539 for (var i = 0; i < len; ++i) {
1540 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1543 // convert `items` into an object form, and construct word indices.
1545 // before any analysis is performed lets gather the search terms to
1546 // search against apart from the rest of the data. This is a quick
1547 // operation that is cached for the life of the page state so that
1548 // all other search operations have access to this cached data for
1549 // faster analysis operations
1550 var len = items.length;
1552 for (var i = 0; i < len; ++i) {
1553 var rawRow = items[i];
1554 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1555 path: rawRow[2] || lastPath, desc: rawRow[3],
1556 parent: paths[rawRow[4]], type: rawRow[5]};
1557 searchIndex.push(row);
1558 if (typeof row.name === "string") {
1559 var word = row.name.toLowerCase();
1560 searchWords.push(word);
1562 searchWords.push("");
1564 lastPath = row.path;
1570 function startSearch() {
1572 var callback = function() {
1573 clearTimeout(searchTimeout);
1574 if (search_input.value.length === 0) {
1575 if (browserSupportsHistoryApi()) {
1576 history.replaceState("", "std - Rust", "?search=");
1578 var main = document.getElementById('main');
1579 if (hasClass(main, 'content')) {
1580 removeClass(main, 'hidden');
1582 var search_c = document.getElementById('search');
1583 if (hasClass(search_c, 'content')) {
1584 addClass(search_c, 'hidden');
1587 searchTimeout = setTimeout(search, 500);
1590 search_input.onkeyup = callback;
1591 search_input.oninput = callback;
1592 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1594 clearTimeout(searchTimeout);
1597 search_input.onchange = function(e) {
1598 // Do NOT e.preventDefault() here. It will prevent pasting.
1599 clearTimeout(searchTimeout);
1600 // zero-timeout necessary here because at the time of event handler execution the
1601 // pasted content is not in the input field yet. Shouldn’t make any difference for
1603 setTimeout(search, 0);
1605 search_input.onpaste = search_input.onchange;
1607 // Push and pop states are used to add search results to the browser
1609 if (browserSupportsHistoryApi()) {
1610 // Store the previous <title> so we can revert back to it later.
1611 var previousTitle = document.title;
1613 window.onpopstate = function(e) {
1614 var params = getQueryStringParams();
1615 // When browsing back from search results the main page
1616 // visibility must be reset.
1617 if (!params.search) {
1618 var main = document.getElementById('main');
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 // Revert to the previous title manually since the History
1628 // API ignores the title parameter.
1629 document.title = previousTitle;
1630 // When browsing forward to search results the previous
1631 // search will be repeated, so the currentResults are
1632 // cleared to ensure the search is successful.
1633 currentResults = null;
1634 // Synchronize search bar with query string state and
1635 // perform the search. This will empty the bar if there's
1636 // nothing there, which lets you really go back to a
1637 // previous state with nothing in the bar.
1638 if (params.search) {
1639 search_input.value = params.search;
1641 search_input.value = '';
1643 // Some browsers fire 'onpopstate' for every page load
1644 // (Chrome), while others fire the event only when actually
1645 // popping a state (Firefox), which is why search() is
1646 // called both here and at the end of the startSearch()
1654 index = buildIndex(rawSearchIndex);
1657 // Draw a convenient sidebar of known crates if we have a listing
1658 if (rootPath === '../' || rootPath === "./") {
1659 var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1661 var div = document.createElement('div');
1662 div.className = 'block crate';
1663 div.innerHTML = '<h3>Crates</h3>';
1664 var ul = document.createElement('ul');
1665 div.appendChild(ul);
1668 for (var crate in rawSearchIndex) {
1669 if (!rawSearchIndex.hasOwnProperty(crate)) {
1675 for (var i = 0; i < crates.length; ++i) {
1676 var klass = 'crate';
1677 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1678 klass += ' current';
1680 var link = document.createElement('a');
1681 link.href = rootPath + crates[i] + '/index.html';
1682 link.title = rawSearchIndex[crates[i]].doc;
1683 link.className = klass;
1684 link.textContent = crates[i];
1686 var li = document.createElement('li');
1687 li.appendChild(link);
1690 sidebar.appendChild(div);
1695 window.initSearch = initSearch;
1697 // delayed sidebar rendering.
1698 function initSidebarItems(items) {
1699 var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1700 var current = window.sidebarCurrent;
1702 function block(shortty, longty) {
1703 var filtered = items[shortty];
1704 if (!filtered) { return; }
1706 var div = document.createElement('div');
1707 div.className = 'block ' + shortty;
1708 var h3 = document.createElement('h3');
1709 h3.textContent = longty;
1710 div.appendChild(h3);
1711 var ul = document.createElement('ul');
1713 for (var i = 0; i < filtered.length; ++i) {
1714 var item = filtered[i];
1716 var desc = item[1]; // can be null
1718 var klass = shortty;
1719 if (name === current.name && shortty === current.ty) {
1720 klass += ' current';
1723 if (shortty === 'mod') {
1724 path = name + '/index.html';
1726 path = shortty + '.' + name + '.html';
1728 var link = document.createElement('a');
1729 link.href = current.relpath + path;
1731 link.className = klass;
1732 link.textContent = name;
1733 var li = document.createElement('li');
1734 li.appendChild(link);
1737 div.appendChild(ul);
1739 sidebar.appendChild(div);
1743 block("primitive", "Primitive Types");
1744 block("mod", "Modules");
1745 block("macro", "Macros");
1746 block("struct", "Structs");
1747 block("enum", "Enums");
1748 block("union", "Unions");
1749 block("constant", "Constants");
1750 block("static", "Statics");
1751 block("trait", "Traits");
1752 block("fn", "Functions");
1753 block("type", "Type Definitions");
1754 block("foreigntype", "Foreign Types");
1755 block("keyword", "Keywords");
1758 window.initSidebarItems = initSidebarItems;
1760 window.register_implementors = function(imp) {
1761 var implementors = document.getElementById('implementors-list');
1762 var synthetic_implementors = document.getElementById('synthetic-implementors-list');
1764 var libs = Object.getOwnPropertyNames(imp);
1765 for (var i = 0; i < libs.length; ++i) {
1766 if (libs[i] === currentCrate) { continue; }
1767 var structs = imp[libs[i]];
1770 for (var j = 0; j < structs.length; ++j) {
1771 var struct = structs[j];
1773 var list = struct.synthetic ? synthetic_implementors : implementors;
1775 if (struct.synthetic) {
1776 for (var k = 0; k < struct.types.length; k++) {
1777 if (window.inlined_types.has(struct.types[k])) {
1778 continue struct_loop;
1780 window.inlined_types.add(struct.types[k]);
1784 var code = document.createElement('code');
1785 code.innerHTML = struct.text;
1787 var x = code.getElementsByTagName('a');
1788 for (var k = 0; k < x.length; k++) {
1789 var href = x[k].getAttribute('href');
1790 if (href && href.indexOf('http') !== 0) {
1791 x[k].setAttribute('href', rootPath + href);
1794 var display = document.createElement('h3');
1795 addClass(display, "impl");
1796 display.innerHTML = '<span class="in-band"><table class="table-display"><tbody>\
1797 <tr><td><code>' + code.outerHTML + '</code></td><td></td></tr></tbody></table>\
1799 list.appendChild(display);
1803 if (window.pending_implementors) {
1804 window.register_implementors(window.pending_implementors);
1807 function labelForToggleButton(sectionIsCollapsed) {
1808 if (sectionIsCollapsed) {
1809 // button will expand the section
1812 // button will collapse the section
1813 // note that this text is also set in the HTML template in render.rs
1814 return "\u2212"; // "\u2212" is '−' minus sign
1817 function onEveryMatchingChild(elem, className, func) {
1818 if (elem && className && func) {
1819 for (var i = 0; i < elem.childNodes.length; i++) {
1820 if (hasClass(elem.childNodes[i], className)) {
1821 func(elem.childNodes[i]);
1823 onEveryMatchingChild(elem.childNodes[i], className, func);
1829 function toggleAllDocs(pageId, fromAutoCollapse) {
1830 var toggle = document.getElementById("toggle-all-docs");
1834 if (hasClass(toggle, "will-expand")) {
1835 updateLocalStorage("rustdoc-collapse", "false");
1836 removeClass(toggle, "will-expand");
1837 onEveryMatchingChild(toggle, "inner", function(e) {
1838 e.innerHTML = labelForToggleButton(false);
1840 toggle.title = "collapse all docs";
1841 if (fromAutoCollapse !== true) {
1842 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1843 collapseDocs(e, "show");
1847 updateLocalStorage("rustdoc-collapse", "true");
1848 addClass(toggle, "will-expand");
1849 onEveryMatchingChild(toggle, "inner", function(e) {
1850 e.innerHTML = labelForToggleButton(true);
1852 toggle.title = "expand all docs";
1853 if (fromAutoCollapse !== true) {
1854 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1855 collapseDocs(e, "hide", pageId);
1861 function collapseDocs(toggle, mode, pageId) {
1862 if (!toggle || !toggle.parentNode) {
1866 function adjustToggle(arg) {
1867 return function(e) {
1868 if (hasClass(e, 'toggle-label')) {
1870 e.style.display = 'inline-block';
1872 e.style.display = 'none';
1875 if (hasClass(e, 'inner')) {
1876 e.innerHTML = labelForToggleButton(arg);
1881 if (!hasClass(toggle.parentNode, "impl")) {
1882 var relatedDoc = toggle.parentNode.nextElementSibling;
1883 if (hasClass(relatedDoc, "stability")) {
1884 relatedDoc = relatedDoc.nextElementSibling;
1886 if (hasClass(relatedDoc, "docblock")) {
1888 if (action === "toggle") {
1889 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1895 if (action === "hide") {
1896 addClass(relatedDoc, "hidden-by-usual-hider");
1897 onEach(toggle.childNodes, adjustToggle(true));
1898 addClass(toggle.parentNode, 'collapsed');
1899 } else if (action === "show") {
1900 removeClass(relatedDoc, "hidden-by-usual-hider");
1901 removeClass(toggle.parentNode, 'collapsed');
1902 onEach(toggle.childNodes, adjustToggle(false));
1906 // we are collapsing the impl block
1907 function implHider(addOrRemove) {
1908 return function(n) {
1909 var is_method = hasClass(n, "method");
1910 if (is_method || hasClass(n, "type")) {
1911 if (is_method === true) {
1913 addClass(n, "hidden-by-impl-hider");
1915 removeClass(n, "hidden-by-impl-hider");
1918 var ns = n.nextElementSibling;
1921 hasClass(ns, "docblock") ||
1922 hasClass(ns, "stability"))) {
1924 addClass(ns, "hidden-by-impl-hider");
1926 removeClass(ns, "hidden-by-impl-hider");
1928 ns = ns.nextElementSibling;
1937 var parentElem = toggle.parentNode;
1938 var relatedDoc = parentElem;
1939 var docblock = relatedDoc.nextElementSibling;
1941 while (!hasClass(relatedDoc, "impl-items")) {
1942 relatedDoc = relatedDoc.nextElementSibling;
1945 if ((!relatedDoc && !hasClass(docblock, "docblock")) ||
1946 (pageId && onEach(relatedDoc.childNodes, function(e) {
1947 return e.id === pageId;
1952 // Hide all functions, but not associated types/consts
1955 if (action === "toggle") {
1956 if (hasClass(relatedDoc, "fns-now-collapsed") ||
1957 hasClass(docblock, "hidden-by-impl-hider")) {
1964 if (action === "show") {
1965 removeClass(relatedDoc, "fns-now-collapsed");
1966 removeClass(docblock, "hidden-by-usual-hider");
1967 onEach(toggle.childNodes, adjustToggle(false));
1968 onEach(relatedDoc.childNodes, implHider(false));
1969 } else if (action === "hide") {
1970 addClass(relatedDoc, "fns-now-collapsed");
1971 addClass(docblock, "hidden-by-usual-hider");
1972 onEach(toggle.childNodes, adjustToggle(true));
1973 onEach(relatedDoc.childNodes, implHider(true));
1978 function autoCollapse(pageId, collapse) {
1980 toggleAllDocs(pageId, true);
1982 var collapser = function(e) {
1983 // inherent impl ids are like 'impl' or impl-<number>'.
1984 // they will never be hidden by default.
1985 var n = e.parentElement;
1986 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
1987 // Automatically minimize all non-inherent impls
1988 if (collapse || hasClass(n, 'impl')) {
1989 collapseDocs(e, "hide", pageId);
1993 if (getCurrentValue('rustdoc-trait-implementations') !== "false") {
1994 onEach(document.getElementById('implementations-list')
1995 .getElementsByClassName("collapse-toggle"), collapser);
1997 if (getCurrentValue('rustdoc-method-docs') !== "false") {
1998 var implItems = document.getElementsByClassName('impl-items');
2000 if (implItems && implItems.length > 0) {
2001 onEach(implItems, function(elem) {
2002 onEach(elem.getElementsByClassName("collapse-toggle"), collapser);
2008 var x = document.getElementById('toggle-all-docs');
2010 x.onclick = toggleAllDocs;
2013 function insertAfter(newNode, referenceNode) {
2014 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2017 function checkIfThereAreMethods(elems) {
2018 var areThereMethods = false;
2020 onEach(elems, function(e) {
2021 if (hasClass(e, "method")) {
2022 areThereMethods = true;
2026 return areThereMethods;
2029 var toggle = document.createElement('a');
2030 toggle.href = 'javascript:void(0)';
2031 toggle.className = 'collapse-toggle';
2032 toggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) + "</span>]";
2034 var func = function(e) {
2035 var next = e.nextElementSibling;
2036 if (hasClass(e, 'impl') && next && hasClass(next, 'docblock')) {
2037 next = next.nextElementSibling;
2042 if ((hasClass(e, 'method') || hasClass(e, 'associatedconstant') ||
2043 checkIfThereAreMethods(next.childNodes)) &&
2044 (hasClass(next, 'docblock') ||
2045 hasClass(e, 'impl') ||
2046 (hasClass(next, 'stability') &&
2047 hasClass(next.nextElementSibling, 'docblock')))) {
2048 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2051 onEach(document.getElementsByClassName('method'), func);
2052 onEach(document.getElementsByClassName('associatedconstant'), func);
2053 onEach(document.getElementsByClassName('impl'), func);
2055 function createToggle(otherMessage, fontSize, extraClass, show) {
2056 var span = document.createElement('span');
2057 span.className = 'toggle-label';
2059 span.style.display = 'none';
2061 if (!otherMessage) {
2062 span.innerHTML = ' Expand description';
2064 span.innerHTML = otherMessage;
2068 span.style.fontSize = fontSize;
2071 var mainToggle = toggle.cloneNode(true);
2072 mainToggle.appendChild(span);
2074 var wrapper = document.createElement('div');
2075 wrapper.className = 'toggle-wrapper';
2077 addClass(wrapper, 'collapsed');
2078 var inner = mainToggle.getElementsByClassName('inner');
2079 if (inner && inner.length > 0) {
2080 inner[0].innerHTML = '+';
2084 addClass(wrapper, extraClass);
2086 wrapper.appendChild(mainToggle);
2090 onEach(document.getElementsByClassName('docblock'), function(e) {
2091 if (hasClass(e, 'autohide')) {
2092 var wrap = e.previousElementSibling;
2093 if (wrap && hasClass(wrap, 'toggle-wrapper')) {
2094 var toggle = wrap.childNodes[0];
2096 if (e.childNodes[0].tagName === 'H3') {
2099 e.style.display = 'none';
2100 addClass(wrap, 'collapsed');
2101 onEach(toggle.getElementsByClassName('inner'), function(e) {
2102 e.innerHTML = labelForToggleButton(true);
2104 onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
2105 e.style.display = 'inline-block';
2106 if (extra === true) {
2107 i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2112 if (e.parentNode.id === "main") {
2118 if (hasClass(e, "type-decl")) {
2120 otherMessage = ' Show declaration';
2121 show = getCurrentValue('rustdoc-item-declarations') === "false";
2123 extraClass = 'collapsed';
2125 } else if (hasClass(e, "non-exhaustive")) {
2126 otherMessage = ' This ';
2127 if (hasClass(e, "non-exhaustive-struct")) {
2128 otherMessage += 'struct';
2129 } else if (hasClass(e, "non-exhaustive-enum")) {
2130 otherMessage += 'enum';
2131 } else if (hasClass(e, "non-exhaustive-type")) {
2132 otherMessage += 'type';
2134 otherMessage += ' is marked as non-exhaustive';
2135 } else if (hasClass(e.childNodes[0], "impl-items")) {
2136 extraClass = "marg-left";
2139 e.parentNode.insertBefore(createToggle(otherMessage, fontSize, extraClass, show), e);
2140 if (otherMessage && show) {
2141 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2146 function createToggleWrapper(tog) {
2147 var span = document.createElement('span');
2148 span.className = 'toggle-label';
2149 span.style.display = 'none';
2150 span.innerHTML = ' Expand attributes';
2151 tog.appendChild(span);
2153 var wrapper = document.createElement('div');
2154 wrapper.className = 'toggle-wrapper toggle-attributes';
2155 wrapper.appendChild(tog);
2159 // In the search display, allows to switch between tabs.
2160 function printTab(nb) {
2161 if (nb === 0 || nb === 1 || nb === 2) {
2165 onEach(document.getElementById('titles').childNodes, function(elem) {
2166 if (nb_copy === 0) {
2167 addClass(elem, 'selected');
2169 removeClass(elem, 'selected');
2173 onEach(document.getElementById('results').childNodes, function(elem) {
2175 elem.style.display = '';
2177 elem.style.display = 'none';
2183 onEach(document.getElementById('main').getElementsByClassName('attributes'), function(i_e) {
2184 i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
2185 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2186 collapseDocs(i_e.previousSibling.childNodes[0], "toggle");
2190 onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
2191 if (hasClass(e, 'compile_fail')) {
2192 e.addEventListener("mouseover", function(event) {
2193 e.previousElementSibling.childNodes[0].style.color = '#f00';
2195 e.addEventListener("mouseout", function(event) {
2196 e.previousElementSibling.childNodes[0].style.color = '';
2198 } else if (hasClass(e, 'ignore')) {
2199 e.addEventListener("mouseover", function(event) {
2200 e.previousElementSibling.childNodes[0].style.color = '#ff9200';
2202 e.addEventListener("mouseout", function(event) {
2203 e.previousElementSibling.childNodes[0].style.color = '';
2208 function showModal(content) {
2209 var modal = document.createElement('div');
2210 modal.id = "important";
2211 addClass(modal, 'modal');
2212 modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
2213 '<div class="whiter"></div><span class="docblock">' + content +
2215 document.getElementsByTagName('body')[0].appendChild(modal);
2216 document.getElementById('modal-close').onclick = hideModal;
2217 modal.onclick = hideModal;
2220 function hideModal() {
2221 var modal = document.getElementById("important");
2223 modal.parentNode.removeChild(modal);
2227 onEach(document.getElementsByClassName('important-traits'), function(e) {
2228 e.onclick = function() {
2229 showModal(e.lastElementChild.innerHTML);
2233 function putBackSearch(search_input) {
2234 if (search_input.value !== "") {
2235 addClass(document.getElementById("main"), "hidden");
2236 removeClass(document.getElementById("search"), "hidden");
2237 if (browserSupportsHistoryApi()) {
2238 history.replaceState(search_input.value,
2240 "?search=" + encodeURIComponent(search_input.value));
2246 search_input.onfocus = function() {
2247 putBackSearch(this);
2251 var params = getQueryStringParams();
2252 if (params && params.search) {
2253 addClass(document.getElementById("main"), "hidden");
2254 var search = document.getElementById("search");
2255 removeClass(search, "hidden");
2256 search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
2259 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2261 sidebar_menu.onclick = function() {
2262 var sidebar = document.getElementsByClassName('sidebar')[0];
2263 if (hasClass(sidebar, "mobile") === true) {
2271 window.onresize = function() {
2275 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2277 if (window.location.hash && window.location.hash.length > 0) {
2278 expandSection(window.location.hash.replace(/^#/, ''));
2282 // Sets the focus on the search bar at the top of the page
2283 function focusSearchBar() {
2284 document.getElementsByClassName('search-input')[0].focus();
2287 // Removes the focus from the search bar
2288 function defocusSearchBar() {
2289 document.getElementsByClassName('search-input')[0].blur();