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",
47 var search_input = document.getElementsByClassName('search-input')[0];
49 // On the search screen, so you remain on the last tab you opened.
52 // 1 for "In Parameters"
53 // 2 for "In Return Types"
56 var themesWidth = null;
58 var titleBeforeSearch = document.title;
60 if (!String.prototype.startsWith) {
61 String.prototype.startsWith = function(searchString, position) {
62 position = position || 0;
63 return this.indexOf(searchString, position) === position;
66 if (!String.prototype.endsWith) {
67 String.prototype.endsWith = function(suffix, length) {
68 var l = length || this.length;
69 return this.indexOf(suffix, l - suffix.length) !== -1;
73 function getPageId() {
74 var id = document.location.href.split('#')[1];
76 return id.split('?')[0].split('&')[0];
81 function hasClass(elem, className) {
82 if (elem && className && elem.className) {
83 var elemClass = elem.className;
84 var start = elemClass.indexOf(className);
87 } else if (elemClass.length === className.length) {
90 if (start > 0 && elemClass[start - 1] !== ' ') {
93 var end = start + className.length;
94 return !(end < elemClass.length && elemClass[end] !== ' ');
100 function addClass(elem, className) {
101 if (elem && className && !hasClass(elem, className)) {
102 if (elem.className && elem.className.length > 0) {
103 elem.className += ' ' + className;
105 elem.className = className;
110 function removeClass(elem, className) {
111 if (elem && className && elem.className) {
112 elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
117 function isHidden(elem) {
118 return (elem.offsetParent === null)
121 function showSidebar() {
122 var elems = document.getElementsByClassName("sidebar-elems")[0];
124 addClass(elems, "show-it");
126 var sidebar = document.getElementsByClassName('sidebar')[0];
128 addClass(sidebar, 'mobile');
129 var filler = document.getElementById("sidebar-filler");
131 var div = document.createElement("div");
132 div.id = "sidebar-filler";
133 sidebar.appendChild(div);
136 var themePicker = document.getElementsByClassName("theme-picker");
137 if (themePicker && themePicker.length > 0) {
138 themePicker[0].style.display = "none";
142 function hideSidebar() {
143 var elems = document.getElementsByClassName("sidebar-elems")[0];
145 removeClass(elems, "show-it");
147 var sidebar = document.getElementsByClassName('sidebar')[0];
148 removeClass(sidebar, 'mobile');
149 var filler = document.getElementById("sidebar-filler");
153 document.getElementsByTagName("body")[0].style.marginTop = '';
154 var themePicker = document.getElementsByClassName("theme-picker");
155 if (themePicker && themePicker.length > 0) {
156 themePicker[0].style.display = null;
160 // used for special search precedence
161 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
162 var TY_KEYWORD = itemTypes.indexOf("keyword");
164 onEach(document.getElementsByClassName('js-only'), function(e) {
165 removeClass(e, 'js-only');
168 function getQueryStringParams() {
170 window.location.search.substring(1).split("&").
172 var pair = s.split("=");
173 params[decodeURIComponent(pair[0])] =
174 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
179 function browserSupportsHistoryApi() {
180 return document.location.protocol != "file:" &&
181 window.history && typeof window.history.pushState === "function";
184 function highlightSourceLines(ev) {
185 // If we're in mobile mode, we should add the sidebar in any case.
187 var search = document.getElementById("search");
188 var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
190 from = parseInt(match[1], 10);
191 to = Math.min(50000, parseInt(match[2] || match[1], 10));
192 from = Math.min(from, to);
193 var elem = document.getElementById(from);
198 var x = document.getElementById(from);
203 onEach(document.getElementsByClassName('line-numbers'), function(e) {
204 onEach(e.getElementsByTagName('span'), function(i_e) {
205 removeClass(i_e, 'line-highlighted');
208 for (i = from; i <= to; ++i) {
209 addClass(document.getElementById(i), 'line-highlighted');
211 } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
212 addClass(search, "hidden");
213 removeClass(document.getElementById("main"), "hidden");
214 var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
215 if (browserSupportsHistoryApi()) {
216 history.replaceState(hash, "", "?search=#" + hash);
218 var elem = document.getElementById(hash);
220 elem.scrollIntoView();
225 function expandSection(id) {
226 var elem = document.getElementById(id);
227 if (elem && isHidden(elem)) {
228 var h3 = elem.parentNode.previousSibling;
229 if (h3 && h3.tagName !== 'H3') {
230 h3 = h3.previousSibling; // skip div.docblock
234 var collapses = h3.getElementsByClassName("collapse-toggle");
235 if (collapses.length > 0) {
236 // The element is not visible, we need to make it appear!
237 collapseDocs(collapses[0], "show");
243 highlightSourceLines(null);
244 window.onhashchange = highlightSourceLines;
246 // Gets the human-readable string for the virtual-key code of the
247 // given KeyboardEvent, ev.
249 // This function is meant as a polyfill for KeyboardEvent#key,
250 // since it is not supported in Trident. We also test for
251 // KeyboardEvent#keyCode because the handleShortcut handler is
252 // also registered for the keydown event, because Blink doesn't fire
253 // keypress on hitting the Escape key.
255 // So I guess you could say things are getting pretty interoperable.
256 function getVirtualKey(ev) {
257 if ("key" in ev && typeof ev.key != "undefined")
260 var c = ev.charCode || ev.keyCode;
263 return String.fromCharCode(c);
266 function displayHelp(display, ev) {
267 if (display === true) {
268 if (hasClass(help, "hidden")) {
270 removeClass(help, "hidden");
271 addClass(document.body, "blur");
273 } else if (!hasClass(help, "hidden")) {
275 addClass(help, "hidden");
276 removeClass(document.body, "blur");
280 function handleEscape(ev, help) {
282 var search = document.getElementById("search");
283 if (!hasClass(help, "hidden")) {
284 displayHelp(false, ev);
285 } else if (!hasClass(search, "hidden")) {
287 addClass(search, "hidden");
288 removeClass(document.getElementById("main"), "hidden");
289 document.title = titleBeforeSearch;
294 function handleShortcut(ev) {
295 // Don't interfere with browser shortcuts
296 if (ev.ctrlKey || ev.altKey || ev.metaKey) {
300 var help = document.getElementById("help");
301 if (document.activeElement.tagName === "INPUT") {
302 switch (getVirtualKey(ev)) {
304 handleEscape(ev, help);
308 switch (getVirtualKey(ev)) {
310 handleEscape(ev, help);
315 displayHelp(false, ev);
330 displayHelp(true, ev);
337 function findParentElement(elem, tagName) {
339 if (elem && elem.tagName === tagName) {
342 } while (elem = elem.parentNode);
346 document.onkeypress = handleShortcut;
347 document.onkeydown = handleShortcut;
348 document.onclick = function(ev) {
349 if (hasClass(ev.target, 'collapse-toggle')) {
350 collapseDocs(ev.target, "toggle");
351 } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
352 collapseDocs(ev.target.parentNode, "toggle");
353 } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
356 var set_fragment = function(name) {
357 if (browserSupportsHistoryApi()) {
358 history.replaceState(null, null, '#' + name);
361 location.replace('#' + name);
365 var cur_id = parseInt(ev.target.id, 10);
367 if (ev.shiftKey && prev_id) {
368 if (prev_id > cur_id) {
374 set_fragment(prev_id + '-' + cur_id);
378 set_fragment(cur_id);
380 } else if (!hasClass(document.getElementById("help"), "hidden")) {
381 addClass(document.getElementById("help"), "hidden");
382 removeClass(document.body, "blur");
384 // Making a collapsed element visible on onhashchange seems
386 var a = findParentElement(ev.target, 'A');
388 expandSection(a.hash.replace(/^#/, ''));
393 var x = document.getElementsByClassName('version-selector');
395 x[0].onchange = function() {
397 url = document.location.href,
399 len = rootPath.match(/\.\.\//g).length + 1;
401 for (i = 0; i < len; ++i) {
402 match = url.match(/\/[^\/]*$/);
404 stripped = match[0] + stripped;
406 url = url.substring(0, url.length - match[0].length);
409 url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
411 document.location.href = url;
416 * A function to compute the Levenshtein distance between two strings
417 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
418 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
419 * This code is an unmodified version of the code written by Marco de Wit
420 * and was found at http://stackoverflow.com/a/18514751/745719
422 var levenshtein_row2 = [];
423 function levenshtein(s1, s2) {
427 var s1_len = s1.length, s2_len = s2.length;
428 if (s1_len && s2_len) {
429 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
430 while (i1 < s1_len) {
433 while (i2 < s2_len) {
434 c2 = s2.charCodeAt(i2);
438 for (i1 = 0; i1 < s1_len; ++i1) {
439 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
441 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
447 return s1_len + s2_len;
450 function initSearch(rawSearchIndex) {
451 var currentResults, index, searchIndex;
452 var MAX_LEV_DISTANCE = 3;
453 var MAX_RESULTS = 200;
454 var GENERICS_DATA = 1;
458 var params = getQueryStringParams();
460 // Populate search bar with query string search term when provided,
461 // but only if the input bar is empty. This avoid the obnoxious issue
462 // where you start trying to do a search, and the index loads, and
463 // suddenly your search is gone!
464 if (search_input.value === "") {
465 search_input.value = params.search || '';
469 * Executes the query and builds an index of results
470 * @param {[Object]} query [The user query]
471 * @param {[type]} searchWords [The list of search words to query
473 * @return {[type]} [A search index of results]
475 function execQuery(query, searchWords) {
476 function itemTypeFromName(typename) {
477 for (var i = 0; i < itemTypes.length; ++i) {
478 if (itemTypes[i] === typename) {
485 var valLower = query.query.toLowerCase(),
487 typeFilter = itemTypeFromName(query.type),
488 results = {}, results_in_args = {}, results_returned = {},
489 split = valLower.split("::");
491 for (var z = 0; z < split.length; ++z) {
492 if (split[z] === "") {
498 function transformResults(results, isType) {
500 for (i = 0; i < results.length; ++i) {
501 if (results[i].id > -1) {
502 var obj = searchIndex[results[i].id];
503 obj.lev = results[i].lev;
504 if (isType !== true || obj.type) {
505 var res = buildHrefAndPath(obj);
506 obj.displayPath = pathSplitter(res[0]);
507 obj.fullPath = obj.displayPath + obj.name;
508 // To be sure than it some items aren't considered as duplicate.
509 obj.fullPath += '|' + obj.ty;
512 if (out.length >= MAX_RESULTS) {
521 function sortResults(results, isType) {
523 for (var entry in results) {
524 if (results.hasOwnProperty(entry)) {
525 ar.push(results[entry]);
529 var nresults = results.length;
530 for (var i = 0; i < nresults; ++i) {
531 results[i].word = searchWords[results[i].id];
532 results[i].item = searchIndex[results[i].id] || {};
534 // if there are no results then return to default and fail
535 if (results.length === 0) {
539 results.sort(function(aaa, bbb) {
542 // Sort by non levenshtein results and then levenshtein results by the distance
543 // (less changes required to match means higher rankings)
546 if (a !== b) { return a - b; }
548 // sort by crate (non-current crate goes later)
549 a = (aaa.item.crate !== window.currentCrate);
550 b = (bbb.item.crate !== window.currentCrate);
551 if (a !== b) { return a - b; }
553 // sort by exact match (mismatch goes later)
554 a = (aaa.word !== valLower);
555 b = (bbb.word !== valLower);
556 if (a !== b) { return a - b; }
558 // sort by item name length (longer goes later)
561 if (a !== b) { return a - b; }
563 // sort by item name (lexicographically larger goes later)
566 if (a !== b) { return (a > b ? +1 : -1); }
568 // sort by index of keyword in item name (no literal occurrence goes later)
571 if (a !== b) { return a - b; }
572 // (later literal occurrence, if any, goes later)
575 if (a !== b) { return a - b; }
577 // special precedence for primitive and keyword pages
578 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
579 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
582 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
583 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
587 // sort by description (no description goes later)
588 a = (aaa.item.desc === '');
589 b = (bbb.item.desc === '');
590 if (a !== b) { return a - b; }
592 // sort by type (later occurrence in `itemTypes` goes later)
595 if (a !== b) { return a - b; }
597 // sort by path (lexicographically larger goes later)
600 if (a !== b) { return (a > b ? +1 : -1); }
606 for (var i = 0; i < results.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 for (var y = 0; y < val.generics.length; ++y) {
654 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
655 for (var x = 0; x < elems.length; ++x) {
656 var tmp_lev = levenshtein(elems[x], val.generics[y]);
657 if (tmp_lev < lev.lev) {
662 if (lev.pos !== -1) {
663 elems.splice(lev.pos, 1);
664 lev_distance = Math.min(lev.lev, lev_distance);
668 return MAX_LEV_DISTANCE + 1;
671 return lev_distance;//Math.ceil(total / done);
674 return MAX_LEV_DISTANCE + 1;
677 // Check for type name and type generics (if any).
678 function checkType(obj, val, literalSearch) {
679 var lev_distance = MAX_LEV_DISTANCE + 1;
680 if (obj[NAME] === val.name) {
681 if (literalSearch === true) {
682 if (val.generics && val.generics.length !== 0) {
683 if (obj.length > GENERICS_DATA &&
684 obj[GENERICS_DATA].length >= val.generics.length) {
685 var elems = obj[GENERICS_DATA].slice(0);
689 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
691 for (x = 0; allFound === false && x < elems.length; ++x) {
692 allFound = elems[x] === val.generics[y];
694 if (allFound === true) {
695 elems.splice(x - 1, 1);
698 if (allFound === true) {
707 // If the type has generics but don't match, then it won't return at this point.
708 // Otherwise, `checkGenerics` will return 0 and it'll return.
709 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
710 var tmp_lev = checkGenerics(obj, val);
711 if (tmp_lev <= MAX_LEV_DISTANCE) {
718 // Names didn't match so let's check if one of the generic types could.
719 if (literalSearch === true) {
720 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
721 for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
722 if (obj[GENERICS_DATA][x] === val.name) {
729 var lev_distance = Math.min(levenshtein(obj[NAME], val.name),
731 if (lev_distance <= MAX_LEV_DISTANCE) {
732 lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
733 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
734 // We can check if the type we're looking for is inside the generics!
735 for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
736 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
740 // Now whatever happens, the returned distance is "less good" so we should mark it
741 // as such, and so we add 1 to the distance to make it "less good".
742 return lev_distance + 1;
745 function findArg(obj, val, literalSearch) {
746 var lev_distance = MAX_LEV_DISTANCE + 1;
748 if (obj && obj.type && obj.type[INPUTS_DATA] &&
749 obj.type[INPUTS_DATA].length > 0) {
750 for (var i = 0; i < obj.type[INPUTS_DATA].length; i++) {
751 var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
752 if (literalSearch === true && tmp === true) {
755 lev_distance = Math.min(tmp, lev_distance);
756 if (lev_distance === 0) {
761 return literalSearch === true ? false : lev_distance;
764 function checkReturned(obj, val, literalSearch) {
765 var lev_distance = MAX_LEV_DISTANCE + 1;
767 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
768 var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
769 if (literalSearch === true && tmp === true) {
772 lev_distance = Math.min(tmp, lev_distance);
773 if (lev_distance === 0) {
777 return literalSearch === true ? false : lev_distance;
780 function checkPath(contains, lastElem, ty) {
781 if (contains.length === 0) {
784 var ret_lev = MAX_LEV_DISTANCE + 1;
785 var path = ty.path.split("::");
787 if (ty.parent && ty.parent.name) {
788 path.push(ty.parent.name.toLowerCase());
791 if (contains.length > path.length) {
792 return MAX_LEV_DISTANCE + 1;
794 for (var i = 0; i < path.length; ++i) {
795 if (i + contains.length > path.length) {
800 for (var x = 0; x < contains.length; ++x) {
801 var lev = levenshtein(path[i + x], contains[x]);
802 if (lev > MAX_LEV_DISTANCE) {
808 if (aborted === false) {
809 ret_lev = Math.min(ret_lev, Math.round(lev_total / contains.length));
815 function typePassesFilter(filter, type) {
817 if (filter < 0) return true;
820 if (filter === type) return true;
822 // Match related items
823 var name = itemTypes[type];
824 switch (itemTypes[filter]) {
826 return (name == "associatedconstant");
828 return (name == "method" || name == "tymethod");
830 return (name == "primitive" || name == "keyword");
837 function generateId(ty) {
838 if (ty.parent && ty.parent.name) {
839 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
841 return itemTypes[ty.ty] + ty.path + ty.name;
844 // quoted values mean literal search
845 var nSearchWords = searchWords.length;
846 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
847 val.charAt(val.length - 1) === val.charAt(0))
849 val = extractGenerics(val.substr(1, val.length - 2));
850 for (var i = 0; i < nSearchWords; ++i) {
851 var in_args = findArg(searchIndex[i], val, true);
852 var returned = checkReturned(searchIndex[i], val, true);
853 var ty = searchIndex[i];
854 var fullId = generateId(ty);
856 if (searchWords[i] === val.name) {
857 // filter type: ... queries
858 if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
859 results[fullId] === undefined)
861 results[fullId] = {id: i, index: -1};
863 } else if ((in_args === true || returned === true) &&
864 typePassesFilter(typeFilter, searchIndex[i].ty)) {
865 if (in_args === true || returned === true) {
866 if (in_args === true) {
867 results_in_args[fullId] = {
873 if (returned === true) {
874 results_returned[fullId] = {
889 query.inputs = [val];
893 } else if (val.search("->") > -1) {
894 var trimmer = function(s) { return s.trim(); };
895 var parts = val.split("->").map(trimmer);
896 var input = parts[0];
897 // sort inputs so that order does not matter
898 var inputs = input.split(",").map(trimmer).sort();
899 for (var i = 0; i < inputs.length; ++i) {
900 inputs[i] = extractGenerics(inputs[i]);
902 var output = extractGenerics(parts[1]);
904 for (var i = 0; i < nSearchWords; ++i) {
905 var type = searchIndex[i].type;
906 var ty = searchIndex[i];
910 var fullId = generateId(ty);
912 // allow searching for void (no output) functions as well
913 var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
914 var returned = checkReturned(ty, output, true);
915 if (output.name === "*" || returned === true) {
923 for (var it = 0; allFound === true && it < inputs.length; it++) {
924 allFound = checkType(type, inputs[it], true);
928 if (in_args === true) {
929 results_in_args[fullId] = {
935 if (returned === true) {
936 results_returned[fullId] = {
942 if (module === true) {
951 query.inputs = inputs.map(function(input) {
954 query.output = output.name;
956 query.inputs = [val];
959 // gather matching search results up to a certain maximum
960 val = val.replace(/\_/g, "");
962 var valGenerics = extractGenerics(val);
964 var paths = valLower.split("::");
966 for (j = 0; j < paths.length; ++j) {
967 if (paths[j] === "") {
972 val = paths[paths.length - 1];
973 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
975 for (j = 0; j < nSearchWords; ++j) {
977 var ty = searchIndex[j];
982 if (paths.length > 1) {
983 var lev = checkPath(contains, paths[paths.length - 1], ty);
984 if (lev > MAX_LEV_DISTANCE) {
986 } else if (lev > 0) {
991 var returned = MAX_LEV_DISTANCE + 1;
992 var in_args = MAX_LEV_DISTANCE + 1;
994 // we want lev results to go lower than others
995 var lev = MAX_LEV_DISTANCE + 1;
996 var fullId = generateId(ty);
998 if (searchWords[j].indexOf(split[i]) > -1 ||
999 searchWords[j].indexOf(val) > -1 ||
1000 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1002 // filter type: ... queries
1003 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1004 index = searchWords[j].replace(/_/g, "").indexOf(val);
1007 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1008 if (typePassesFilter(typeFilter, ty.ty) === false) {
1009 lev = MAX_LEV_DISTANCE + 1;
1014 if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1015 if (typePassesFilter(typeFilter, ty.ty) === false) {
1016 in_args = MAX_LEV_DISTANCE + 1;
1019 if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1020 if (typePassesFilter(typeFilter, ty.ty) === false) {
1021 returned = MAX_LEV_DISTANCE + 1;
1026 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1027 if (val.length < 6) {
1033 if (in_args <= MAX_LEV_DISTANCE) {
1034 if (results_in_args[fullId] === undefined) {
1035 results_in_args[fullId] = {
1041 results_in_args[fullId].lev =
1042 Math.min(results_in_args[fullId].lev, in_args);
1044 if (returned <= MAX_LEV_DISTANCE) {
1045 if (results_returned[fullId] === undefined) {
1046 results_returned[fullId] = {
1052 results_returned[fullId].lev =
1053 Math.min(results_returned[fullId].lev, returned);
1055 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1056 if (index !== -1 && paths.length < 2) {
1059 if (results[fullId] === undefined) {
1066 results[fullId].lev = Math.min(results[fullId].lev, lev);
1072 'in_args': sortResults(results_in_args, true),
1073 'returned': sortResults(results_returned, true),
1074 'others': sortResults(results),
1076 if (ALIASES && ALIASES[window.currentCrate] &&
1077 ALIASES[window.currentCrate][query.raw]) {
1078 var aliases = ALIASES[window.currentCrate][query.raw];
1079 for (var i = 0; i < aliases.length; ++i) {
1080 aliases[i].is_alias = true;
1081 aliases[i].alias = query.raw;
1082 aliases[i].path = aliases[i].p;
1083 var res = buildHrefAndPath(aliases[i]);
1084 aliases[i].displayPath = pathSplitter(res[0]);
1085 aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1086 aliases[i].href = res[1];
1087 ret['others'].unshift(aliases[i]);
1088 if (ret['others'].length > MAX_RESULTS) {
1089 ret['others'].pop();
1097 * Validate performs the following boolean logic. For example:
1098 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1099 * exists in (name || path || parent) OR => ("file" && "open") exists in
1102 * This could be written functionally, but I wanted to minimise
1103 * functions on stack.
1105 * @param {[string]} name [The name of the result]
1106 * @param {[string]} path [The path of the result]
1107 * @param {[string]} keys [The keys to be used (["file", "open"])]
1108 * @param {[object]} parent [The parent of the result]
1109 * @return {[boolean]} [Whether the result is valid or not]
1111 function validateResult(name, path, keys, parent) {
1112 for (var i = 0; i < keys.length; ++i) {
1113 // each check is for validation so we negate the conditions and invalidate
1115 // check for an exact name match
1116 name.indexOf(keys[i]) > -1 ||
1117 // then an exact path match
1118 path.indexOf(keys[i]) > -1 ||
1119 // next if there is a parent, check for exact parent match
1120 (parent !== undefined &&
1121 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1122 // lastly check to see if the name was a levenshtein match
1123 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1130 function getQuery(raw) {
1131 var matches, type, query;
1134 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1136 type = matches[1].replace(/^const$/, 'constant');
1137 query = query.substring(matches[0].length);
1148 function initSearchNav() {
1151 var click_func = function(e) {
1153 // to retrieve the real "owner" of the event.
1154 while (el.tagName !== 'TR') {
1157 var dst = e.target.getElementsByTagName('a');
1158 if (dst.length < 1) {
1162 if (window.location.pathname === dst.pathname) {
1163 addClass(document.getElementById('search'), 'hidden');
1164 removeClass(document.getElementById('main'), 'hidden');
1165 document.location.href = dst.href;
1168 var mouseover_func = function(e) {
1170 // to retrieve the real "owner" of the event.
1171 while (el.tagName !== 'TR') {
1174 clearTimeout(hoverTimeout);
1175 hoverTimeout = setTimeout(function() {
1176 onEach(document.getElementsByClassName('search-results'), function(e) {
1177 onEach(e.getElementsByClassName('result'), function(i_e) {
1178 removeClass(i_e, 'highlighted');
1181 addClass(el, 'highlighted');
1184 onEach(document.getElementsByClassName('search-results'), function(e) {
1185 onEach(e.getElementsByClassName('result'), function(i_e) {
1186 i_e.onclick = click_func;
1187 i_e.onmouseover = mouseover_func;
1191 search_input.onkeydown = function(e) {
1192 // "actives" references the currently highlighted item in each search tab.
1193 // Each array in "actives" represents a tab.
1194 var actives = [[], [], []];
1195 // "current" is used to know which tab we're looking into.
1197 onEach(document.getElementsByClassName('search-results'), function(e) {
1198 onEach(e.getElementsByClassName('highlighted'), function(e) {
1199 actives[current].push(e);
1204 if (e.which === 38) { // up
1205 if (!actives[currentTab].length ||
1206 !actives[currentTab][0].previousElementSibling) {
1210 addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
1211 removeClass(actives[currentTab][0], 'highlighted');
1212 } else if (e.which === 40) { // down
1213 if (!actives[currentTab].length) {
1214 var results = document.getElementsByClassName('search-results');
1215 if (results.length > 0) {
1216 var res = results[currentTab].getElementsByClassName('result');
1217 if (res.length > 0) {
1218 addClass(res[0], 'highlighted');
1221 } else if (actives[currentTab][0].nextElementSibling) {
1222 addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
1223 removeClass(actives[currentTab][0], 'highlighted');
1225 } else if (e.which === 13) { // return
1226 if (actives[currentTab].length) {
1227 document.location.href =
1228 actives[currentTab][0].getElementsByTagName('a')[0].href;
1230 } else if (e.which === 9) { // tab
1232 printTab(currentTab > 0 ? currentTab - 1 : 2);
1234 printTab(currentTab > 1 ? 0 : currentTab + 1);
1237 } else if (e.which === 16) { // shift
1238 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1239 } else if (e.which === 27) { // escape
1240 removeClass(actives[currentTab][0], 'highlighted');
1241 search_input.value = '';
1243 } else if (actives[currentTab].length > 0) {
1244 removeClass(actives[currentTab][0], 'highlighted');
1249 function buildHrefAndPath(item) {
1252 var type = itemTypes[item.ty];
1253 var name = item.name;
1255 if (type === 'mod') {
1256 displayPath = item.path + '::';
1257 href = rootPath + item.path.replace(/::/g, '/') + '/' +
1258 name + '/index.html';
1259 } else if (type === "primitive" || type === "keyword") {
1261 href = rootPath + item.path.replace(/::/g, '/') +
1262 '/' + type + '.' + name + '.html';
1263 } else if (type === "externcrate") {
1265 href = rootPath + name + '/index.html';
1266 } else if (item.parent !== undefined) {
1267 var myparent = item.parent;
1268 var anchor = '#' + type + '.' + name;
1269 var parentType = itemTypes[myparent.ty];
1270 if (parentType === "primitive") {
1271 displayPath = myparent.name + '::';
1273 displayPath = item.path + '::' + myparent.name + '::';
1275 href = rootPath + item.path.replace(/::/g, '/') +
1277 '.' + myparent.name +
1280 displayPath = item.path + '::';
1281 href = rootPath + item.path.replace(/::/g, '/') +
1282 '/' + type + '.' + name + '.html';
1284 return [displayPath, href];
1287 function escape(content) {
1288 var h1 = document.createElement('h1');
1289 h1.textContent = content;
1290 return h1.innerHTML;
1293 function pathSplitter(path) {
1294 var tmp = '<span>' + path.replace(/::/g, '::</span><span>');
1295 if (tmp.endsWith("<span>")) {
1296 return tmp.slice(0, tmp.length - 6);
1301 function addTab(array, query, display) {
1302 var extraStyle = '';
1303 if (display === false) {
1304 extraStyle = ' style="display: none;"';
1308 var duplicates = {};
1310 if (array.length > 0) {
1311 output = '<table class="search-results"' + extraStyle + '>';
1313 array.forEach(function(item) {
1317 type = itemTypes[item.ty];
1319 if (item.is_alias !== true) {
1320 if (duplicates[item.fullPath]) {
1323 duplicates[item.fullPath] = true;
1327 output += '<tr class="' + type + ' result"><td>' +
1328 '<a href="' + item.href + '">' +
1329 (item.is_alias === true ?
1330 ('<span class="alias"><b>' + item.alias + ' </b></span><span ' +
1331 'class="grey"><i> - see </i></span>') : '') +
1332 item.displayPath + '<span class="' + type + '">' +
1333 name + '</span></a></td><td>' +
1334 '<a href="' + item.href + '">' +
1335 '<span class="desc">' + escape(item.desc) +
1336 ' </span></a></td></tr>';
1338 output += '</table>';
1340 output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
1341 'Try on <a href="https://duckduckgo.com/?q=' +
1342 encodeURIComponent('rust ' + query.query) +
1343 '">DuckDuckGo</a>?</div>';
1345 return [output, length];
1348 function makeTabHeader(tabNb, text, nbElems) {
1349 if (currentTab === tabNb) {
1350 return '<div class="selected">' + text +
1351 ' <div class="count">(' + nbElems + ')</div></div>';
1353 return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
1356 function showResults(results) {
1357 if (results['others'].length === 1 &&
1358 getCurrentValue('rustdoc-go-to-only-result') === "true") {
1359 var elem = document.createElement('a');
1360 elem.href = results['others'][0].href;
1361 elem.style.display = 'none';
1362 // For firefox, we need the element to be in the DOM so it can be clicked.
1363 document.body.appendChild(elem);
1366 var query = getQuery(search_input.value);
1368 currentResults = query.id;
1370 var ret_others = addTab(results['others'], query);
1371 var ret_in_args = addTab(results['in_args'], query, false);
1372 var ret_returned = addTab(results['returned'], query, false);
1374 var output = '<h1>Results for ' + escape(query.query) +
1375 (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>' +
1376 '<div id="titles">' +
1377 makeTabHeader(0, "In Names", ret_others[1]) +
1378 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1379 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1380 '</div><div id="results">' +
1381 ret_others[0] + ret_in_args[0] + ret_returned[0] + '</div>';
1383 addClass(document.getElementById('main'), 'hidden');
1384 var search = document.getElementById('search');
1385 removeClass(search, 'hidden');
1386 search.innerHTML = output;
1387 var tds = search.getElementsByTagName('td');
1389 if (tds.length > 0) {
1390 td_width = tds[0].offsetWidth;
1392 var width = search.offsetWidth - 40 - td_width;
1393 onEach(search.getElementsByClassName('desc'), function(e) {
1394 e.style.width = width + 'px';
1397 var elems = document.getElementById('titles').childNodes;
1398 elems[0].onclick = function() { printTab(0); };
1399 elems[1].onclick = function() { printTab(1); };
1400 elems[2].onclick = function() { printTab(2); };
1401 printTab(currentTab);
1404 function execSearch(query, searchWords) {
1405 var queries = query.raw.split(",");
1412 for (var i = 0; i < queries.length; ++i) {
1413 var query = queries[i].trim();
1414 if (query.length !== 0) {
1415 var tmp = execQuery(getQuery(query), searchWords);
1417 results['in_args'].push(tmp['in_args']);
1418 results['returned'].push(tmp['returned']);
1419 results['others'].push(tmp['others']);
1422 if (queries.length > 1) {
1423 function getSmallest(arrays, positions, notDuplicates) {
1426 for (var it = 0; it < positions.length; ++it) {
1427 if (arrays[it].length > positions[it] &&
1428 (start === null || start > arrays[it][positions[it]].lev) &&
1429 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1430 start = arrays[it][positions[it]].lev;
1436 function mergeArrays(arrays) {
1439 var notDuplicates = {};
1441 for (var x = 0; x < arrays.length; ++x) {
1444 while (ret.length < MAX_RESULTS) {
1445 var smallest = getSmallest(arrays, positions, notDuplicates);
1447 if (smallest === null) {
1450 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1451 if (arrays[x].length > positions[x] &&
1452 arrays[x][positions[x]].lev === smallest &&
1453 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1454 ret.push(arrays[x][positions[x]]);
1455 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1464 'in_args': mergeArrays(results['in_args']),
1465 'returned': mergeArrays(results['returned']),
1466 'others': mergeArrays(results['others']),
1470 'in_args': results['in_args'][0],
1471 'returned': results['returned'][0],
1472 'others': results['others'][0],
1477 function search(e) {
1478 var params = getQueryStringParams();
1479 var query = getQuery(search_input.value.trim());
1485 if (query.query.length === 0 || query.id === currentResults) {
1486 if (query.query.length > 0) {
1487 putBackSearch(search_input);
1492 // Update document title to maintain a meaningful browser history
1493 document.title = "Results for " + query.query + " - Rust";
1495 // Because searching is incremental by character, only the most
1496 // recent search query is added to the browser history.
1497 if (browserSupportsHistoryApi()) {
1498 if (!history.state && !params.search) {
1499 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1501 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1505 showResults(execSearch(query, index));
1508 function buildIndex(rawSearchIndex) {
1510 var searchWords = [];
1511 for (var crate in rawSearchIndex) {
1512 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1514 searchWords.push(crate);
1517 ty: 1, // == ExternCrate
1520 desc: rawSearchIndex[crate].doc,
1524 // an array of [(Number) item type,
1526 // (String) full path or empty string for previous path,
1527 // (String) description,
1528 // (Number | null) the parent path index to `paths`]
1529 // (Object | null) the type of the function (if any)
1530 var items = rawSearchIndex[crate].items;
1531 // an array of [(Number) item type,
1533 var paths = rawSearchIndex[crate].paths;
1535 // convert `paths` into an object form
1536 var len = paths.length;
1537 for (var i = 0; i < len; ++i) {
1538 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1541 // convert `items` into an object form, and construct word indices.
1543 // before any analysis is performed lets gather the search terms to
1544 // search against apart from the rest of the data. This is a quick
1545 // operation that is cached for the life of the page state so that
1546 // all other search operations have access to this cached data for
1547 // faster analysis operations
1548 var len = items.length;
1550 for (var i = 0; i < len; ++i) {
1551 var rawRow = items[i];
1552 var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1553 path: rawRow[2] || lastPath, desc: rawRow[3],
1554 parent: paths[rawRow[4]], type: rawRow[5]};
1555 searchIndex.push(row);
1556 if (typeof row.name === "string") {
1557 var word = row.name.toLowerCase();
1558 searchWords.push(word);
1560 searchWords.push("");
1562 lastPath = row.path;
1568 function startSearch() {
1570 var callback = function() {
1571 clearTimeout(searchTimeout);
1572 if (search_input.value.length === 0) {
1573 if (browserSupportsHistoryApi()) {
1574 history.replaceState("", "std - Rust", "?search=");
1576 var main = document.getElementById('main');
1577 if (hasClass(main, 'content')) {
1578 removeClass(main, 'hidden');
1580 var search_c = document.getElementById('search');
1581 if (hasClass(search_c, 'content')) {
1582 addClass(search_c, 'hidden');
1585 searchTimeout = setTimeout(search, 500);
1588 search_input.onkeyup = callback;
1589 search_input.oninput = callback;
1590 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1592 clearTimeout(searchTimeout);
1595 search_input.onchange = function(e) {
1596 // Do NOT e.preventDefault() here. It will prevent pasting.
1597 clearTimeout(searchTimeout);
1598 // zero-timeout necessary here because at the time of event handler execution the
1599 // pasted content is not in the input field yet. Shouldn’t make any difference for
1601 setTimeout(search, 0);
1603 search_input.onpaste = search_input.onchange;
1605 // Push and pop states are used to add search results to the browser
1607 if (browserSupportsHistoryApi()) {
1608 // Store the previous <title> so we can revert back to it later.
1609 var previousTitle = document.title;
1611 window.onpopstate = function(e) {
1612 var params = getQueryStringParams();
1613 // When browsing back from search results the main page
1614 // visibility must be reset.
1615 if (!params.search) {
1616 var main = document.getElementById('main');
1617 if (hasClass(main, 'content')) {
1618 removeClass(main, 'hidden');
1620 var search_c = document.getElementById('search');
1621 if (hasClass(search_c, 'content')) {
1622 addClass(search_c, 'hidden');
1625 // Revert to the previous title manually since the History
1626 // API ignores the title parameter.
1627 document.title = previousTitle;
1628 // When browsing forward to search results the previous
1629 // search will be repeated, so the currentResults are
1630 // cleared to ensure the search is successful.
1631 currentResults = null;
1632 // Synchronize search bar with query string state and
1633 // perform the search. This will empty the bar if there's
1634 // nothing there, which lets you really go back to a
1635 // previous state with nothing in the bar.
1636 if (params.search) {
1637 search_input.value = params.search;
1639 search_input.value = '';
1641 // Some browsers fire 'onpopstate' for every page load
1642 // (Chrome), while others fire the event only when actually
1643 // popping a state (Firefox), which is why search() is
1644 // called both here and at the end of the startSearch()
1652 index = buildIndex(rawSearchIndex);
1655 // Draw a convenient sidebar of known crates if we have a listing
1656 if (rootPath === '../' || rootPath === "./") {
1657 var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1659 var div = document.createElement('div');
1660 div.className = 'block crate';
1661 div.innerHTML = '<h3>Crates</h3>';
1662 var ul = document.createElement('ul');
1663 div.appendChild(ul);
1666 for (var crate in rawSearchIndex) {
1667 if (!rawSearchIndex.hasOwnProperty(crate)) {
1673 for (var i = 0; i < crates.length; ++i) {
1674 var klass = 'crate';
1675 if (rootPath !== "./" && crates[i] === window.currentCrate) {
1676 klass += ' current';
1678 var link = document.createElement('a');
1679 link.href = rootPath + crates[i] + '/index.html';
1680 link.title = rawSearchIndex[crates[i]].doc;
1681 link.className = klass;
1682 link.textContent = crates[i];
1684 var li = document.createElement('li');
1685 li.appendChild(link);
1688 sidebar.appendChild(div);
1693 window.initSearch = initSearch;
1695 // delayed sidebar rendering.
1696 function initSidebarItems(items) {
1697 var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1698 var current = window.sidebarCurrent;
1700 function block(shortty, longty) {
1701 var filtered = items[shortty];
1702 if (!filtered) { return; }
1704 var div = document.createElement('div');
1705 div.className = 'block ' + shortty;
1706 var h3 = document.createElement('h3');
1707 h3.textContent = longty;
1708 div.appendChild(h3);
1709 var ul = document.createElement('ul');
1711 for (var i = 0; i < filtered.length; ++i) {
1712 var item = filtered[i];
1714 var desc = item[1]; // can be null
1716 var klass = shortty;
1717 if (name === current.name && shortty === current.ty) {
1718 klass += ' current';
1721 if (shortty === 'mod') {
1722 path = name + '/index.html';
1724 path = shortty + '.' + name + '.html';
1726 var link = document.createElement('a');
1727 link.href = current.relpath + path;
1729 link.className = klass;
1730 link.textContent = name;
1731 var li = document.createElement('li');
1732 li.appendChild(link);
1735 div.appendChild(ul);
1737 sidebar.appendChild(div);
1741 block("primitive", "Primitive Types");
1742 block("mod", "Modules");
1743 block("macro", "Macros");
1744 block("struct", "Structs");
1745 block("enum", "Enums");
1746 block("union", "Unions");
1747 block("constant", "Constants");
1748 block("static", "Statics");
1749 block("trait", "Traits");
1750 block("fn", "Functions");
1751 block("type", "Type Definitions");
1752 block("foreigntype", "Foreign Types");
1753 block("keyword", "Keywords");
1756 window.initSidebarItems = initSidebarItems;
1758 window.register_implementors = function(imp) {
1759 var implementors = document.getElementById('implementors-list');
1760 var synthetic_implementors = document.getElementById('synthetic-implementors-list');
1762 var libs = Object.getOwnPropertyNames(imp);
1763 for (var i = 0; i < libs.length; ++i) {
1764 if (libs[i] === currentCrate) { continue; }
1765 var structs = imp[libs[i]];
1768 for (var j = 0; j < structs.length; ++j) {
1769 var struct = structs[j];
1771 var list = struct.synthetic ? synthetic_implementors : implementors;
1773 if (struct.synthetic) {
1774 for (var k = 0; k < struct.types.length; k++) {
1775 if (window.inlined_types.has(struct.types[k])) {
1776 continue struct_loop;
1778 window.inlined_types.add(struct.types[k]);
1782 var code = document.createElement('code');
1783 code.innerHTML = struct.text;
1785 var x = code.getElementsByTagName('a');
1786 for (var k = 0; k < x.length; k++) {
1787 var href = x[k].getAttribute('href');
1788 if (href && href.indexOf('http') !== 0) {
1789 x[k].setAttribute('href', rootPath + href);
1792 var display = document.createElement('h3');
1793 addClass(display, "impl");
1794 display.innerHTML = '<span class="in-band"><table class="table-display"><tbody>\
1795 <tr><td><code>' + code.outerHTML + '</code></td><td></td></tr></tbody></table>\
1797 list.appendChild(display);
1801 if (window.pending_implementors) {
1802 window.register_implementors(window.pending_implementors);
1805 function labelForToggleButton(sectionIsCollapsed) {
1806 if (sectionIsCollapsed) {
1807 // button will expand the section
1810 // button will collapse the section
1811 // note that this text is also set in the HTML template in render.rs
1812 return "\u2212"; // "\u2212" is '−' minus sign
1815 function onEveryMatchingChild(elem, className, func) {
1816 if (elem && className && func) {
1817 for (var i = 0; i < elem.childNodes.length; i++) {
1818 if (hasClass(elem.childNodes[i], className)) {
1819 func(elem.childNodes[i]);
1821 onEveryMatchingChild(elem.childNodes[i], className, func);
1827 function toggleAllDocs(pageId, fromAutoCollapse) {
1828 var toggle = document.getElementById("toggle-all-docs");
1832 if (hasClass(toggle, "will-expand")) {
1833 updateLocalStorage("rustdoc-collapse", "false");
1834 removeClass(toggle, "will-expand");
1835 onEveryMatchingChild(toggle, "inner", function(e) {
1836 e.innerHTML = labelForToggleButton(false);
1838 toggle.title = "collapse all docs";
1839 if (fromAutoCollapse !== true) {
1840 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1841 collapseDocs(e, "show");
1845 updateLocalStorage("rustdoc-collapse", "true");
1846 addClass(toggle, "will-expand");
1847 onEveryMatchingChild(toggle, "inner", function(e) {
1848 e.innerHTML = labelForToggleButton(true);
1850 toggle.title = "expand all docs";
1851 if (fromAutoCollapse !== true) {
1852 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1853 collapseDocs(e, "hide", pageId);
1859 function collapseDocs(toggle, mode, pageId) {
1860 if (!toggle || !toggle.parentNode) {
1864 function adjustToggle(arg) {
1865 return function(e) {
1866 if (hasClass(e, 'toggle-label')) {
1868 e.style.display = 'inline-block';
1870 e.style.display = 'none';
1873 if (hasClass(e, 'inner')) {
1874 e.innerHTML = labelForToggleButton(arg);
1879 if (!hasClass(toggle.parentNode, "impl")) {
1880 var relatedDoc = toggle.parentNode.nextElementSibling;
1881 if (hasClass(relatedDoc, "stability")) {
1882 relatedDoc = relatedDoc.nextElementSibling;
1884 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1886 if (action === "toggle") {
1887 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1893 if (action === "hide") {
1894 addClass(relatedDoc, "hidden-by-usual-hider");
1895 onEach(toggle.childNodes, adjustToggle(true));
1896 addClass(toggle.parentNode, 'collapsed');
1897 } else if (action === "show") {
1898 removeClass(relatedDoc, "hidden-by-usual-hider");
1899 removeClass(toggle.parentNode, 'collapsed');
1900 onEach(toggle.childNodes, adjustToggle(false));
1904 // we are collapsing the impl block
1905 function implHider(addOrRemove) {
1906 return function(n) {
1907 var is_method = hasClass(n, "method");
1908 if (is_method || hasClass(n, "type")) {
1909 if (is_method === true) {
1911 addClass(n, "hidden-by-impl-hider");
1913 removeClass(n, "hidden-by-impl-hider");
1916 var ns = n.nextElementSibling;
1919 hasClass(ns, "docblock") ||
1920 hasClass(ns, "stability"))) {
1922 addClass(ns, "hidden-by-impl-hider");
1924 removeClass(ns, "hidden-by-impl-hider");
1926 ns = ns.nextElementSibling;
1935 var parentElem = toggle.parentNode;
1936 var relatedDoc = parentElem;
1937 var docblock = relatedDoc.nextElementSibling;
1939 while (!hasClass(relatedDoc, "impl-items")) {
1940 relatedDoc = relatedDoc.nextElementSibling;
1943 if ((!relatedDoc && !hasClass(docblock, "docblock")) ||
1944 (pageId && onEach(relatedDoc.childNodes, function(e) {
1945 return e.id === pageId;
1950 // Hide all functions, but not associated types/consts
1953 if (action === "toggle") {
1954 if (hasClass(relatedDoc, "fns-now-collapsed") ||
1955 hasClass(docblock, "hidden-by-impl-hider")) {
1962 if (action === "show") {
1963 removeClass(relatedDoc, "fns-now-collapsed");
1964 removeClass(docblock, "hidden-by-usual-hider");
1965 onEach(toggle.childNodes, adjustToggle(false));
1966 onEach(relatedDoc.childNodes, implHider(false));
1967 } else if (action === "hide") {
1968 addClass(relatedDoc, "fns-now-collapsed");
1969 addClass(docblock, "hidden-by-usual-hider");
1970 onEach(toggle.childNodes, adjustToggle(true));
1971 onEach(relatedDoc.childNodes, implHider(true));
1976 function autoCollapse(pageId, collapse) {
1978 toggleAllDocs(pageId, true);
1980 var collapser = function(e) {
1981 // inherent impl ids are like 'impl' or impl-<number>'.
1982 // they will never be hidden by default.
1983 var n = e.parentElement;
1984 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
1985 // Automatically minimize all non-inherent impls
1986 if (collapse || hasClass(n, 'impl')) {
1987 collapseDocs(e, "hide", pageId);
1991 if (getCurrentValue('rustdoc-trait-implementations') !== "false") {
1992 var impl_list = document.getElementById('implementations-list');
1994 if (impl_list !== null) {
1995 onEach(impl_list.getElementsByClassName("collapse-toggle"), collapser);
1998 if (getCurrentValue('rustdoc-method-docs') !== "false") {
1999 var implItems = document.getElementsByClassName('impl-items');
2001 if (implItems && implItems.length > 0) {
2002 onEach(implItems, function(elem) {
2003 onEach(elem.getElementsByClassName("collapse-toggle"), collapser);
2009 var x = document.getElementById('toggle-all-docs');
2011 x.onclick = toggleAllDocs;
2014 function insertAfter(newNode, referenceNode) {
2015 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2018 function checkIfThereAreMethods(elems) {
2019 var areThereMethods = false;
2021 onEach(elems, function(e) {
2022 if (hasClass(e, "method")) {
2023 areThereMethods = true;
2027 return areThereMethods;
2030 var toggle = document.createElement('a');
2031 toggle.href = 'javascript:void(0)';
2032 toggle.className = 'collapse-toggle';
2033 toggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) + "</span>]";
2035 var func = function(e) {
2036 var next = e.nextElementSibling;
2037 if (hasClass(e, 'impl') && next && hasClass(next, 'docblock')) {
2038 next = next.nextElementSibling;
2043 if ((hasClass(e, 'method') || hasClass(e, 'associatedconstant') ||
2044 checkIfThereAreMethods(next.childNodes)) &&
2045 (hasClass(next, 'docblock') ||
2046 hasClass(e, 'impl') ||
2047 (hasClass(next, 'stability') &&
2048 hasClass(next.nextElementSibling, 'docblock')))) {
2049 insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2052 onEach(document.getElementsByClassName('method'), func);
2053 onEach(document.getElementsByClassName('associatedconstant'), func);
2054 onEach(document.getElementsByClassName('impl'), func);
2056 function createToggle(otherMessage, fontSize, extraClass, show) {
2057 var span = document.createElement('span');
2058 span.className = 'toggle-label';
2060 span.style.display = 'none';
2062 if (!otherMessage) {
2063 span.innerHTML = ' Expand description';
2065 span.innerHTML = otherMessage;
2069 span.style.fontSize = fontSize;
2072 var mainToggle = toggle.cloneNode(true);
2073 mainToggle.appendChild(span);
2075 var wrapper = document.createElement('div');
2076 wrapper.className = 'toggle-wrapper';
2078 addClass(wrapper, 'collapsed');
2079 var inner = mainToggle.getElementsByClassName('inner');
2080 if (inner && inner.length > 0) {
2081 inner[0].innerHTML = '+';
2085 addClass(wrapper, extraClass);
2087 wrapper.appendChild(mainToggle);
2091 var hideItemDeclarations = getCurrentValue('rustdoc-item-declarations') === "false";
2092 function buildToggleWrapper(e) {
2093 if (hasClass(e, 'autohide')) {
2094 var wrap = e.previousElementSibling;
2095 if (wrap && hasClass(wrap, 'toggle-wrapper')) {
2096 var toggle = wrap.childNodes[0];
2097 var extra = 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") {
2113 var otherMessage = '';
2117 if (hasClass(e, "type-decl")) {
2119 otherMessage = ' Show declaration';
2120 if (hideItemDeclarations === false) {
2121 extraClass = 'collapsed';
2123 } else if (hasClass(e, "sub-variant")) {
2124 otherMessage = ' Show fields';
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,
2142 hideItemDeclarations),
2144 if (otherMessage.length > 0 && hideItemDeclarations === true) {
2145 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2150 onEach(document.getElementsByClassName('docblock'), buildToggleWrapper);
2151 onEach(document.getElementsByClassName('sub-variant'), buildToggleWrapper);
2153 function createToggleWrapper(tog) {
2154 var span = document.createElement('span');
2155 span.className = 'toggle-label';
2156 span.style.display = 'none';
2157 span.innerHTML = ' Expand attributes';
2158 tog.appendChild(span);
2160 var wrapper = document.createElement('div');
2161 wrapper.className = 'toggle-wrapper toggle-attributes';
2162 wrapper.appendChild(tog);
2166 // In the search display, allows to switch between tabs.
2167 function printTab(nb) {
2168 if (nb === 0 || nb === 1 || nb === 2) {
2172 onEach(document.getElementById('titles').childNodes, function(elem) {
2173 if (nb_copy === 0) {
2174 addClass(elem, 'selected');
2176 removeClass(elem, 'selected');
2180 onEach(document.getElementById('results').childNodes, function(elem) {
2182 elem.style.display = '';
2184 elem.style.display = 'none';
2190 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2191 var itemAttributesFunc = function() {};
2192 if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2193 itemAttributesFunc = function(x) {
2194 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2197 onEach(document.getElementById('main').getElementsByClassName('attributes'), function(i_e) {
2198 i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
2199 itemAttributesFunc(i_e);
2202 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2203 var lineNumbersFunc = function() {};
2204 if (getCurrentValue("rustdoc-line-numbers") === "true") {
2205 lineNumbersFunc = function(x) {
2206 var count = x.textContent.split('\n').length;
2208 for (var i = 0; i < count; ++i) {
2211 var node = document.createElement('pre');
2212 addClass(node, 'line-number');
2213 node.innerHTML = elems.join('\n');
2214 x.parentNode.insertBefore(node, x);
2217 onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
2218 if (hasClass(e, 'compile_fail')) {
2219 e.addEventListener("mouseover", function(event) {
2220 e.previousElementSibling.childNodes[0].style.color = '#f00';
2222 e.addEventListener("mouseout", function(event) {
2223 e.previousElementSibling.childNodes[0].style.color = '';
2225 } else if (hasClass(e, 'ignore')) {
2226 e.addEventListener("mouseover", function(event) {
2227 e.previousElementSibling.childNodes[0].style.color = '#ff9200';
2229 e.addEventListener("mouseout", function(event) {
2230 e.previousElementSibling.childNodes[0].style.color = '';
2236 function showModal(content) {
2237 var modal = document.createElement('div');
2238 modal.id = "important";
2239 addClass(modal, 'modal');
2240 modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
2241 '<div class="whiter"></div><span class="docblock">' + content +
2243 document.getElementsByTagName('body')[0].appendChild(modal);
2244 document.getElementById('modal-close').onclick = hideModal;
2245 modal.onclick = hideModal;
2248 function hideModal() {
2249 var modal = document.getElementById("important");
2251 modal.parentNode.removeChild(modal);
2255 onEach(document.getElementsByClassName('important-traits'), function(e) {
2256 e.onclick = function() {
2257 showModal(e.lastElementChild.innerHTML);
2261 function putBackSearch(search_input) {
2262 if (search_input.value !== "") {
2263 addClass(document.getElementById("main"), "hidden");
2264 removeClass(document.getElementById("search"), "hidden");
2265 if (browserSupportsHistoryApi()) {
2266 history.replaceState(search_input.value,
2268 "?search=" + encodeURIComponent(search_input.value));
2274 search_input.onfocus = function() {
2275 putBackSearch(this);
2279 var params = getQueryStringParams();
2280 if (params && params.search) {
2281 addClass(document.getElementById("main"), "hidden");
2282 var search = document.getElementById("search");
2283 removeClass(search, "hidden");
2284 search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
2287 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2289 sidebar_menu.onclick = function() {
2290 var sidebar = document.getElementsByClassName('sidebar')[0];
2291 if (hasClass(sidebar, "mobile") === true) {
2299 window.onresize = function() {
2303 autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2305 if (window.location.hash && window.location.hash.length > 0) {
2306 expandSection(window.location.hash.replace(/^#/, ''));
2310 // Sets the focus on the search bar at the top of the page
2311 function focusSearchBar() {
2312 document.getElementsByClassName('search-input')[0].focus();
2315 // Removes the focus from the search bar
2316 function defocusSearchBar() {
2317 document.getElementsByClassName('search-input')[0].blur();