]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
adc49da61da13ff9222fa6f101574d9fef831c5e
[rust.git] / src / librustdoc / html / static / main.js
1 /*!
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.
5  *
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.
11  */
12
13 // From rust:
14 /* global ALIASES, currentCrate, rootPath */
15
16 // Local js definitions:
17 /* global addClass, getCurrentValue, hasClass */
18 /* global isHidden onEach, removeClass, updateLocalStorage */
19
20 if (!String.prototype.startsWith) {
21     String.prototype.startsWith = function(searchString, position) {
22         position = position || 0;
23         return this.indexOf(searchString, position) === position;
24     };
25 }
26 if (!String.prototype.endsWith) {
27     String.prototype.endsWith = function(suffix, length) {
28         var l = length || this.length;
29         return this.indexOf(suffix, l - suffix.length) !== -1;
30     };
31 }
32
33 if (!DOMTokenList.prototype.add) {
34     DOMTokenList.prototype.add = function(className) {
35         if (className && !hasClass(this, className)) {
36             if (this.className && this.className.length > 0) {
37                 this.className += " " + className;
38             } else {
39                 this.className = className;
40             }
41         }
42     };
43 }
44
45 if (!DOMTokenList.prototype.remove) {
46     DOMTokenList.prototype.remove = function(className) {
47         if (className && this.className) {
48             this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
49                                                          .trim();
50         }
51     };
52 }
53
54 (function() {
55     "use strict";
56
57     // This mapping table should match the discriminants of
58     // `rustdoc::html::item_type::ItemType` type in Rust.
59     var itemTypes = ["mod",
60                      "externcrate",
61                      "import",
62                      "struct",
63                      "enum",
64                      "fn",
65                      "type",
66                      "static",
67                      "trait",
68                      "impl",
69                      "tymethod",
70                      "method",
71                      "structfield",
72                      "variant",
73                      "macro",
74                      "primitive",
75                      "associatedtype",
76                      "constant",
77                      "associatedconstant",
78                      "union",
79                      "foreigntype",
80                      "keyword",
81                      "existential",
82                      "attr",
83                      "derive"];
84
85     var start = Date.now();
86
87     var search_input = document.getElementsByClassName("search-input")[0];
88
89     // On the search screen, so you remain on the last tab you opened.
90     //
91     // 0 for "In Names"
92     // 1 for "In Parameters"
93     // 2 for "In Return Types"
94     var currentTab = 0;
95
96     var themesWidth = null;
97
98     var titleBeforeSearch = document.title;
99
100     function getPageId() {
101         var id = document.location.href.split("#")[1];
102         if (id) {
103             return id.split("?")[0].split("&")[0];
104         }
105         return null;
106     }
107
108     function showSidebar() {
109         var elems = document.getElementsByClassName("sidebar-elems")[0];
110         if (elems) {
111             addClass(elems, "show-it");
112         }
113         var sidebar = document.getElementsByClassName("sidebar")[0];
114         if (sidebar) {
115             addClass(sidebar, "mobile");
116             var filler = document.getElementById("sidebar-filler");
117             if (!filler) {
118                 var div = document.createElement("div");
119                 div.id = "sidebar-filler";
120                 sidebar.appendChild(div);
121             }
122         }
123         var themePicker = document.getElementsByClassName("theme-picker");
124         if (themePicker && themePicker.length > 0) {
125             themePicker[0].style.display = "none";
126         }
127     }
128
129     function hideSidebar() {
130         var elems = document.getElementsByClassName("sidebar-elems")[0];
131         if (elems) {
132             removeClass(elems, "show-it");
133         }
134         var sidebar = document.getElementsByClassName("sidebar")[0];
135         removeClass(sidebar, "mobile");
136         var filler = document.getElementById("sidebar-filler");
137         if (filler) {
138             filler.remove();
139         }
140         document.getElementsByTagName("body")[0].style.marginTop = "";
141         var themePicker = document.getElementsByClassName("theme-picker");
142         if (themePicker && themePicker.length > 0) {
143             themePicker[0].style.display = null;
144         }
145     }
146
147     // used for special search precedence
148     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
149     var TY_KEYWORD = itemTypes.indexOf("keyword");
150
151     onEach(Array.prototype.slice.call(document.getElementsByClassName("js-only")), function(e) {
152         removeClass(e, "js-only");
153     });
154
155     function getQueryStringParams() {
156         var params = {};
157         window.location.search.substring(1).split("&").
158             map(function(s) {
159                 var pair = s.split("=");
160                 params[decodeURIComponent(pair[0])] =
161                     typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
162             });
163         return params;
164     }
165
166     function browserSupportsHistoryApi() {
167         return document.location.protocol != "file:" &&
168           window.history && typeof window.history.pushState === "function";
169     }
170
171     var main = document.getElementById("main");
172
173     function highlightSourceLines(ev) {
174         // If we're in mobile mode, we should add the sidebar in any case.
175         hideSidebar();
176         var elem;
177         var search = document.getElementById("search");
178         var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
179         if (match) {
180             from = parseInt(match[1], 10);
181             to = Math.min(50000, parseInt(match[2] || match[1], 10));
182             from = Math.min(from, to);
183             elem = document.getElementById(from);
184             if (!elem) {
185                 return;
186             }
187             if (ev === null) {
188                 var x = document.getElementById(from);
189                 if (x) {
190                     x.scrollIntoView();
191                 }
192             }
193             onEach(Array.prototype.slice.call(document.getElementsByClassName("line-numbers")),
194                    function(e) {
195                 onEach(Array.prototype.slice.call(e.getElementsByTagName("span")), function(i_e) {
196                     removeClass(i_e, "line-highlighted");
197                 });
198             });
199             for (i = from; i <= to; ++i) {
200                 addClass(document.getElementById(i), "line-highlighted");
201             }
202         } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
203             addClass(search, "hidden");
204             removeClass(main, "hidden");
205             var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
206             if (browserSupportsHistoryApi()) {
207                 history.replaceState(hash, "", "?search=#" + hash);
208             }
209             elem = document.getElementById(hash);
210             if (elem) {
211                 elem.scrollIntoView();
212             }
213         }
214     }
215
216     function expandSection(id) {
217         var elem = document.getElementById(id);
218         if (elem && isHidden(elem)) {
219             var h3 = elem.parentNode.previousSibling;
220             if (h3 && h3.tagName !== "H3") {
221                 h3 = h3.previousSibling; // skip div.docblock
222             }
223
224             if (h3) {
225                 var collapses = h3.getElementsByClassName("collapse-toggle");
226                 if (collapses.length > 0) {
227                     // The element is not visible, we need to make it appear!
228                     collapseDocs(collapses[0], "show");
229                 }
230             }
231         }
232     }
233
234     highlightSourceLines(null);
235     window.onhashchange = highlightSourceLines;
236
237     // Gets the human-readable string for the virtual-key code of the
238     // given KeyboardEvent, ev.
239     //
240     // This function is meant as a polyfill for KeyboardEvent#key,
241     // since it is not supported in Trident.  We also test for
242     // KeyboardEvent#keyCode because the handleShortcut handler is
243     // also registered for the keydown event, because Blink doesn't fire
244     // keypress on hitting the Escape key.
245     //
246     // So I guess you could say things are getting pretty interoperable.
247     function getVirtualKey(ev) {
248         if ("key" in ev && typeof ev.key != "undefined") {
249             return ev.key;
250         }
251
252         var c = ev.charCode || ev.keyCode;
253         if (c == 27) {
254             return "Escape";
255         }
256         return String.fromCharCode(c);
257     }
258
259     function displayHelp(display, ev) {
260         if (display === true) {
261             if (hasClass(help, "hidden")) {
262                 ev.preventDefault();
263                 removeClass(help, "hidden");
264                 addClass(document.body, "blur");
265             }
266         } else if (hasClass(help, "hidden") === false) {
267             ev.preventDefault();
268             addClass(help, "hidden");
269             removeClass(document.body, "blur");
270         }
271     }
272
273     function handleEscape(ev, help) {
274         hideModal();
275         var search = document.getElementById("search");
276         if (hasClass(help, "hidden") === false) {
277             displayHelp(false, ev);
278         } else if (hasClass(search, "hidden") === false) {
279             ev.preventDefault();
280             addClass(search, "hidden");
281             removeClass(main, "hidden");
282             document.title = titleBeforeSearch;
283         }
284         defocusSearchBar();
285     }
286
287     function handleShortcut(ev) {
288         // Don't interfere with browser shortcuts
289         if (ev.ctrlKey || ev.altKey || ev.metaKey) {
290             return;
291         }
292
293         var help = document.getElementById("help");
294         if (document.activeElement.tagName === "INPUT") {
295             switch (getVirtualKey(ev)) {
296             case "Escape":
297                 handleEscape(ev, help);
298                 break;
299             }
300         } else {
301             switch (getVirtualKey(ev)) {
302             case "Escape":
303                 handleEscape(ev, help);
304                 break;
305
306             case "s":
307             case "S":
308                 displayHelp(false, ev);
309                 hideModal();
310                 ev.preventDefault();
311                 focusSearchBar();
312                 break;
313
314             case "+":
315             case "-":
316                 ev.preventDefault();
317                 toggleAllDocs();
318                 break;
319
320             case "?":
321                 if (ev.shiftKey) {
322                     hideModal();
323                     displayHelp(true, ev);
324                 }
325                 break;
326             }
327         }
328     }
329
330     function findParentElement(elem, tagName) {
331         do {
332             if (elem && elem.tagName === tagName) {
333                 return elem;
334             }
335             elem = elem.parentNode;
336         } while (elem);
337         return null;
338     }
339
340     document.onkeypress = handleShortcut;
341     document.onkeydown = handleShortcut;
342     document.onclick = function(ev) {
343         if (hasClass(ev.target, "collapse-toggle")) {
344             collapseDocs(ev.target, "toggle");
345         } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
346             collapseDocs(ev.target.parentNode, "toggle");
347         } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
348             var prev_id = 0;
349
350             var set_fragment = function(name) {
351                 if (browserSupportsHistoryApi()) {
352                     history.replaceState(null, null, "#" + name);
353                     window.hashchange();
354                 } else {
355                     location.replace("#" + name);
356                 }
357             };
358
359             var cur_id = parseInt(ev.target.id, 10);
360
361             if (ev.shiftKey && prev_id) {
362                 if (prev_id > cur_id) {
363                     var tmp = prev_id;
364                     prev_id = cur_id;
365                     cur_id = tmp;
366                 }
367
368                 set_fragment(prev_id + "-" + cur_id);
369             } else {
370                 prev_id = cur_id;
371
372                 set_fragment(cur_id);
373             }
374         } else if (hasClass(document.getElementById("help"), "hidden") === false) {
375             addClass(document.getElementById("help"), "hidden");
376             removeClass(document.body, "blur");
377         } else {
378             // Making a collapsed element visible on onhashchange seems
379             // too late
380             var a = findParentElement(ev.target, "A");
381             if (a && a.hash) {
382                 expandSection(a.hash.replace(/^#/, ""));
383             }
384         }
385     };
386
387     var x = document.getElementsByClassName("version-selector");
388     if (x.length > 0) {
389         x[0].onchange = function() {
390             var i, match,
391                 url = document.location.href,
392                 stripped = "",
393                 len = rootPath.match(/\.\.\//g).length + 1;
394
395             for (i = 0; i < len; ++i) {
396                 match = url.match(/\/[^\/]*$/);
397                 if (i < len - 1) {
398                     stripped = match[0] + stripped;
399                 }
400                 url = url.substring(0, url.length - match[0].length);
401             }
402
403             url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
404
405             document.location.href = url;
406         };
407     }
408
409     /**
410      * A function to compute the Levenshtein distance between two strings
411      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
412      * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
413      * This code is an unmodified version of the code written by Marco de Wit
414      * and was found at http://stackoverflow.com/a/18514751/745719
415      */
416     var levenshtein_row2 = [];
417     function levenshtein(s1, s2) {
418         if (s1 === s2) {
419             return 0;
420         }
421         var s1_len = s1.length, s2_len = s2.length;
422         if (s1_len && s2_len) {
423             var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
424             while (i1 < s1_len) {
425                 row[i1] = ++i1;
426             }
427             while (i2 < s2_len) {
428                 c2 = s2.charCodeAt(i2);
429                 a = i2;
430                 ++i2;
431                 b = i2;
432                 for (i1 = 0; i1 < s1_len; ++i1) {
433                     c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
434                     a = row[i1];
435                     b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
436                     row[i1] = b;
437                 }
438             }
439             return b;
440         }
441         return s1_len + s2_len;
442     }
443
444     function initSearch(rawSearchIndex) {
445         var currentResults, index, searchIndex;
446         var MAX_LEV_DISTANCE = 3;
447         var MAX_RESULTS = 200;
448         var GENERICS_DATA = 1;
449         var NAME = 0;
450         var INPUTS_DATA = 0;
451         var OUTPUT_DATA = 1;
452         var params = getQueryStringParams();
453
454         // Populate search bar with query string search term when provided,
455         // but only if the input bar is empty. This avoid the obnoxious issue
456         // where you start trying to do a search, and the index loads, and
457         // suddenly your search is gone!
458         if (search_input.value === "") {
459             search_input.value = params.search || "";
460         }
461
462         /**
463          * Executes the query and builds an index of results
464          * @param  {[Object]} query      [The user query]
465          * @param  {[type]} searchWords  [The list of search words to query
466          *                                against]
467          * @param  {[type]} filterCrates [Crate to search in if defined]
468          * @return {[type]}              [A search index of results]
469          */
470         function execQuery(query, searchWords, filterCrates) {
471             function itemTypeFromName(typename) {
472                 var length = itemTypes.length;
473                 for (var i = 0; i < length; ++i) {
474                     if (itemTypes[i] === typename) {
475                         return i;
476                     }
477                 }
478                 return -1;
479             }
480
481             var valLower = query.query.toLowerCase(),
482                 val = valLower,
483                 typeFilter = itemTypeFromName(query.type),
484                 results = {}, results_in_args = {}, results_returned = {},
485                 split = valLower.split("::");
486
487             var length = split.length;
488             for (var z = 0; z < length; ++z) {
489                 if (split[z] === "") {
490                     split.splice(z, 1);
491                     z -= 1;
492                 }
493             }
494
495             function transformResults(results, isType) {
496                 var out = [];
497                 var length = results.length;
498                 for (var i = 0; i < length; ++i) {
499                     if (results[i].id > -1) {
500                         var obj = searchIndex[results[i].id];
501                         obj.lev = results[i].lev;
502                         if (isType !== true || obj.type) {
503                             var res = buildHrefAndPath(obj);
504                             obj.displayPath = pathSplitter(res[0]);
505                             obj.fullPath = obj.displayPath + obj.name;
506                             // To be sure than it some items aren't considered as duplicate.
507                             obj.fullPath += "|" + obj.ty;
508                             obj.href = res[1];
509                             out.push(obj);
510                             if (out.length >= MAX_RESULTS) {
511                                 break;
512                             }
513                         }
514                     }
515                 }
516                 return out;
517             }
518
519             function sortResults(results, isType) {
520                 var ar = [];
521                 for (var entry in results) {
522                     if (results.hasOwnProperty(entry)) {
523                         ar.push(results[entry]);
524                     }
525                 }
526                 results = ar;
527                 var i;
528                 var nresults = results.length;
529                 for (i = 0; i < nresults; ++i) {
530                     results[i].word = searchWords[results[i].id];
531                     results[i].item = searchIndex[results[i].id] || {};
532                 }
533                 // if there are no results then return to default and fail
534                 if (results.length === 0) {
535                     return [];
536                 }
537
538                 results.sort(function(aaa, bbb) {
539                     var a, b;
540
541                     // Sort by non levenshtein results and then levenshtein results by the distance
542                     // (less changes required to match means higher rankings)
543                     a = (aaa.lev);
544                     b = (bbb.lev);
545                     if (a !== b) { return a - b; }
546
547                     // sort by crate (non-current crate goes later)
548                     a = (aaa.item.crate !== window.currentCrate);
549                     b = (bbb.item.crate !== window.currentCrate);
550                     if (a !== b) { return a - b; }
551
552                     // sort by exact match (mismatch goes later)
553                     a = (aaa.word !== valLower);
554                     b = (bbb.word !== valLower);
555                     if (a !== b) { return a - b; }
556
557                     // sort by item name length (longer goes later)
558                     a = aaa.word.length;
559                     b = bbb.word.length;
560                     if (a !== b) { return a - b; }
561
562                     // sort by item name (lexicographically larger goes later)
563                     a = aaa.word;
564                     b = bbb.word;
565                     if (a !== b) { return (a > b ? +1 : -1); }
566
567                     // sort by index of keyword in item name (no literal occurrence goes later)
568                     a = (aaa.index < 0);
569                     b = (bbb.index < 0);
570                     if (a !== b) { return a - b; }
571                     // (later literal occurrence, if any, goes later)
572                     a = aaa.index;
573                     b = bbb.index;
574                     if (a !== b) { return a - b; }
575
576                     // special precedence for primitive and keyword pages
577                     if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
578                         (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
579                         return -1;
580                     }
581                     if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
582                         (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
583                         return 1;
584                     }
585
586                     // sort by description (no description goes later)
587                     a = (aaa.item.desc === "");
588                     b = (bbb.item.desc === "");
589                     if (a !== b) { return a - b; }
590
591                     // sort by type (later occurrence in `itemTypes` goes later)
592                     a = aaa.item.ty;
593                     b = bbb.item.ty;
594                     if (a !== b) { return a - b; }
595
596                     // sort by path (lexicographically larger goes later)
597                     a = aaa.item.path;
598                     b = bbb.item.path;
599                     if (a !== b) { return (a > b ? +1 : -1); }
600
601                     // que sera, sera
602                     return 0;
603                 });
604
605                 var length = results.length;
606                 for (i = 0; i < length; ++i) {
607                     var result = results[i];
608
609                     // this validation does not make sense when searching by types
610                     if (result.dontValidate) {
611                         continue;
612                     }
613                     var name = result.item.name.toLowerCase(),
614                         path = result.item.path.toLowerCase(),
615                         parent = result.item.parent;
616
617                     if (isType !== true &&
618                         validateResult(name, path, split, parent) === false)
619                     {
620                         result.id = -1;
621                     }
622                 }
623                 return transformResults(results);
624             }
625
626             function extractGenerics(val) {
627                 val = val.toLowerCase();
628                 if (val.indexOf("<") !== -1) {
629                     var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
630                     return {
631                         name: val.substring(0, val.indexOf("<")),
632                         generics: values.split(/\s*,\s*/),
633                     };
634                 }
635                 return {
636                     name: val,
637                     generics: [],
638                 };
639             }
640
641             function checkGenerics(obj, val) {
642                 // The names match, but we need to be sure that all generics kinda
643                 // match as well.
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);
649                         var total = 0;
650                         var done = 0;
651                         // We need to find the type that matches the most to remove it in order
652                         // to move forward.
653                         var vlength = val.generics.length;
654                         for (var y = 0; y < vlength; ++y) {
655                             var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
656                             var elength = elems.length;
657                             for (var x = 0; x < elength; ++x) {
658                                 var tmp_lev = levenshtein(elems[x], val.generics[y]);
659                                 if (tmp_lev < lev.lev) {
660                                     lev.lev = tmp_lev;
661                                     lev.pos = x;
662                                 }
663                             }
664                             if (lev.pos !== -1) {
665                                 elems.splice(lev.pos, 1);
666                                 lev_distance = Math.min(lev.lev, lev_distance);
667                                 total += lev.lev;
668                                 done += 1;
669                             } else {
670                                 return MAX_LEV_DISTANCE + 1;
671                             }
672                         }
673                         return lev_distance;//Math.ceil(total / done);
674                     }
675                 }
676                 return MAX_LEV_DISTANCE + 1;
677             }
678
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                 var x;
683                 if (obj[NAME] === val.name) {
684                     if (literalSearch === true) {
685                         if (val.generics && val.generics.length !== 0) {
686                             if (obj.length > GENERICS_DATA &&
687                                   obj[GENERICS_DATA].length >= val.generics.length) {
688                                 var elems = obj[GENERICS_DATA].slice(0);
689                                 var allFound = true;
690
691                                 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
692                                     allFound = false;
693                                     for (x = 0; allFound === false && x < elems.length; ++x) {
694                                         allFound = elems[x] === val.generics[y];
695                                     }
696                                     if (allFound === true) {
697                                         elems.splice(x - 1, 1);
698                                     }
699                                 }
700                                 if (allFound === true) {
701                                     return true;
702                                 }
703                             } else {
704                                 return false;
705                             }
706                         }
707                         return true;
708                     }
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) {
714                             return tmp_lev;
715                         }
716                     } else {
717                         return 0;
718                     }
719                 }
720                 // Names didn't match so let's check if one of the generic types could.
721                 if (literalSearch === true) {
722                      if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
723                         var length = obj[GENERICS_DATA].length;
724                         for (x = 0; x < length; ++x) {
725                             if (obj[GENERICS_DATA][x] === val.name) {
726                                 return true;
727                             }
728                         }
729                     }
730                     return false;
731                 }
732                 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
733                 if (lev_distance <= MAX_LEV_DISTANCE) {
734                     lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
735                 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
736                     // We can check if the type we're looking for is inside the generics!
737                     var olength = obj[GENERICS_DATA].length;
738                     for (x = 0; x < olength; ++x) {
739                         lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
740                                                 lev_distance);
741                     }
742                 }
743                 // Now whatever happens, the returned distance is "less good" so we should mark it
744                 // as such, and so we add 1 to the distance to make it "less good".
745                 return lev_distance + 1;
746             }
747
748             function findArg(obj, val, literalSearch) {
749                 var lev_distance = MAX_LEV_DISTANCE + 1;
750
751                 if (obj && obj.type && obj.type[INPUTS_DATA] &&
752                       obj.type[INPUTS_DATA].length > 0) {
753                     var length = obj.type[INPUTS_DATA].length;
754                     for (var i = 0; i < length; i++) {
755                         var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
756                         if (literalSearch === true && tmp === true) {
757                             return true;
758                         }
759                         lev_distance = Math.min(tmp, lev_distance);
760                         if (lev_distance === 0) {
761                             return 0;
762                         }
763                     }
764                 }
765                 return literalSearch === true ? false : lev_distance;
766             }
767
768             function checkReturned(obj, val, literalSearch) {
769                 var lev_distance = MAX_LEV_DISTANCE + 1;
770
771                 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
772                     var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
773                     if (literalSearch === true && tmp === true) {
774                         return true;
775                     }
776                     lev_distance = Math.min(tmp, lev_distance);
777                     if (lev_distance === 0) {
778                         return 0;
779                     }
780                 }
781                 return literalSearch === true ? false : lev_distance;
782             }
783
784             function checkPath(contains, lastElem, ty) {
785                 if (contains.length === 0) {
786                     return 0;
787                 }
788                 var ret_lev = MAX_LEV_DISTANCE + 1;
789                 var path = ty.path.split("::");
790
791                 if (ty.parent && ty.parent.name) {
792                     path.push(ty.parent.name.toLowerCase());
793                 }
794
795                 var length = path.length;
796                 var clength = contains.length;
797                 if (clength > length) {
798                     return MAX_LEV_DISTANCE + 1;
799                 }
800                 for (var i = 0; i < length; ++i) {
801                     if (i + clength > length) {
802                         break;
803                     }
804                     var lev_total = 0;
805                     var aborted = false;
806                     for (var x = 0; x < clength; ++x) {
807                         var lev = levenshtein(path[i + x], contains[x]);
808                         if (lev > MAX_LEV_DISTANCE) {
809                             aborted = true;
810                             break;
811                         }
812                         lev_total += lev;
813                     }
814                     if (aborted === false) {
815                         ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
816                     }
817                 }
818                 return ret_lev;
819             }
820
821             function typePassesFilter(filter, type) {
822                 // No filter
823                 if (filter < 0) return true;
824
825                 // Exact match
826                 if (filter === type) return true;
827
828                 // Match related items
829                 var name = itemTypes[type];
830                 switch (itemTypes[filter]) {
831                     case "constant":
832                         return (name == "associatedconstant");
833                     case "fn":
834                         return (name == "method" || name == "tymethod");
835                     case "type":
836                         return (name == "primitive" || name == "keyword");
837                 }
838
839                 // No match
840                 return false;
841             }
842
843             function generateId(ty) {
844                 if (ty.parent && ty.parent.name) {
845                     return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
846                 }
847                 return itemTypes[ty.ty] + ty.path + ty.name;
848             }
849
850             // quoted values mean literal search
851             var nSearchWords = searchWords.length;
852             var i;
853             var ty;
854             var fullId;
855             var returned;
856             var in_args;
857             if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
858                 val.charAt(val.length - 1) === val.charAt(0))
859             {
860                 val = extractGenerics(val.substr(1, val.length - 2));
861                 for (i = 0; i < nSearchWords; ++i) {
862                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
863                         continue;
864                     }
865                     in_args = findArg(searchIndex[i], val, true);
866                     returned = checkReturned(searchIndex[i], val, true);
867                     ty = searchIndex[i];
868                     fullId = generateId(ty);
869
870                     if (searchWords[i] === val.name) {
871                         // filter type: ... queries
872                         if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
873                             results[fullId] === undefined)
874                         {
875                             results[fullId] = {id: i, index: -1};
876                         }
877                     } else if ((in_args === true || returned === true) &&
878                                typePassesFilter(typeFilter, searchIndex[i].ty)) {
879                         if (in_args === true || returned === true) {
880                             if (in_args === true) {
881                                 results_in_args[fullId] = {
882                                     id: i,
883                                     index: -1,
884                                     dontValidate: true,
885                                 };
886                             }
887                             if (returned === true) {
888                                 results_returned[fullId] = {
889                                     id: i,
890                                     index: -1,
891                                     dontValidate: true,
892                                 };
893                             }
894                         } else {
895                             results[fullId] = {
896                                 id: i,
897                                 index: -1,
898                                 dontValidate: true,
899                             };
900                         }
901                     }
902                 }
903                 query.inputs = [val];
904                 query.output = val;
905                 query.search = val;
906             // searching by type
907             } else if (val.search("->") > -1) {
908                 var trimmer = function(s) { return s.trim(); };
909                 var parts = val.split("->").map(trimmer);
910                 var input = parts[0];
911                 // sort inputs so that order does not matter
912                 var inputs = input.split(",").map(trimmer).sort();
913                 for (i = 0; i < inputs.length; ++i) {
914                     inputs[i] = extractGenerics(inputs[i]);
915                 }
916                 var output = extractGenerics(parts[1]);
917
918                 for (i = 0; i < nSearchWords; ++i) {
919                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
920                         continue;
921                     }
922                     var type = searchIndex[i].type;
923                     ty = searchIndex[i];
924                     if (!type) {
925                         continue;
926                     }
927                     fullId = generateId(ty);
928
929                     // allow searching for void (no output) functions as well
930                     var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
931                     returned = checkReturned(ty, output, true);
932                     if (output.name === "*" || returned === true) {
933                         in_args = false;
934                         var module = false;
935
936                         if (input === "*") {
937                             module = true;
938                         } else {
939                             var allFound = true;
940                             for (var it = 0; allFound === true && it < inputs.length; it++) {
941                                 allFound = checkType(type, inputs[it], true);
942                             }
943                             in_args = allFound;
944                         }
945                         if (in_args === true) {
946                             results_in_args[fullId] = {
947                                 id: i,
948                                 index: -1,
949                                 dontValidate: true,
950                             };
951                         }
952                         if (returned === true) {
953                             results_returned[fullId] = {
954                                 id: i,
955                                 index: -1,
956                                 dontValidate: true,
957                             };
958                         }
959                         if (module === true) {
960                             results[fullId] = {
961                                 id: i,
962                                 index: -1,
963                                 dontValidate: true,
964                             };
965                         }
966                     }
967                 }
968                 query.inputs = inputs.map(function(input) {
969                     return input.name;
970                 });
971                 query.output = output.name;
972             } else {
973                 query.inputs = [val];
974                 query.output = val;
975                 query.search = val;
976                 // gather matching search results up to a certain maximum
977                 val = val.replace(/\_/g, "");
978
979                 var valGenerics = extractGenerics(val);
980
981                 var paths = valLower.split("::");
982                 var j;
983                 for (j = 0; j < paths.length; ++j) {
984                     if (paths[j] === "") {
985                         paths.splice(j, 1);
986                         j -= 1;
987                     }
988                 }
989                 val = paths[paths.length - 1];
990                 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
991
992                 for (j = 0; j < nSearchWords; ++j) {
993                     var lev;
994                     var lev_distance;
995                     ty = searchIndex[j];
996                     if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
997                         continue;
998                     }
999                     var lev_distance;
1000                     var lev_add = 0;
1001                     if (paths.length > 1) {
1002                         lev = checkPath(contains, paths[paths.length - 1], ty);
1003                         if (lev > MAX_LEV_DISTANCE) {
1004                             continue;
1005                         } else if (lev > 0) {
1006                             lev_add = 1;
1007                         }
1008                     }
1009
1010                     returned = MAX_LEV_DISTANCE + 1;
1011                     in_args = MAX_LEV_DISTANCE + 1;
1012                     var index = -1;
1013                     // we want lev results to go lower than others
1014                     lev = MAX_LEV_DISTANCE + 1;
1015                     fullId = generateId(ty);
1016
1017                     if (searchWords[j].indexOf(split[i]) > -1 ||
1018                         searchWords[j].indexOf(val) > -1 ||
1019                         searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1020                     {
1021                         // filter type: ... queries
1022                         if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1023                             index = searchWords[j].replace(/_/g, "").indexOf(val);
1024                         }
1025                     }
1026                     if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1027                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1028                             lev = MAX_LEV_DISTANCE + 1;
1029                         } else {
1030                             lev += 1;
1031                         }
1032                     }
1033                     if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1034                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1035                             in_args = MAX_LEV_DISTANCE + 1;
1036                         }
1037                     }
1038                     if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1039                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1040                             returned = MAX_LEV_DISTANCE + 1;
1041                         }
1042                     }
1043
1044                     lev += lev_add;
1045                     if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1046                         if (val.length < 6) {
1047                             lev -= 1;
1048                         } else {
1049                             lev = 0;
1050                         }
1051                     }
1052                     if (in_args <= MAX_LEV_DISTANCE) {
1053                         if (results_in_args[fullId] === undefined) {
1054                             results_in_args[fullId] = {
1055                                 id: j,
1056                                 index: index,
1057                                 lev: in_args,
1058                             };
1059                         }
1060                         results_in_args[fullId].lev =
1061                             Math.min(results_in_args[fullId].lev, in_args);
1062                     }
1063                     if (returned <= MAX_LEV_DISTANCE) {
1064                         if (results_returned[fullId] === undefined) {
1065                             results_returned[fullId] = {
1066                                 id: j,
1067                                 index: index,
1068                                 lev: returned,
1069                             };
1070                         }
1071                         results_returned[fullId].lev =
1072                             Math.min(results_returned[fullId].lev, returned);
1073                     }
1074                     if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1075                         if (index !== -1 && paths.length < 2) {
1076                             lev = 0;
1077                         }
1078                         if (results[fullId] === undefined) {
1079                             results[fullId] = {
1080                                 id: j,
1081                                 index: index,
1082                                 lev: lev,
1083                             };
1084                         }
1085                         results[fullId].lev = Math.min(results[fullId].lev, lev);
1086                     }
1087                 }
1088             }
1089
1090             var ret = {
1091                 "in_args": sortResults(results_in_args, true),
1092                 "returned": sortResults(results_returned, true),
1093                 "others": sortResults(results),
1094             };
1095             if (ALIASES && ALIASES[window.currentCrate] &&
1096                     ALIASES[window.currentCrate][query.raw]) {
1097                 var aliases = ALIASES[window.currentCrate][query.raw];
1098                 for (i = 0; i < aliases.length; ++i) {
1099                     aliases[i].is_alias = true;
1100                     aliases[i].alias = query.raw;
1101                     aliases[i].path = aliases[i].p;
1102                     var res = buildHrefAndPath(aliases[i]);
1103                     aliases[i].displayPath = pathSplitter(res[0]);
1104                     aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1105                     aliases[i].href = res[1];
1106                     retothers.unshift(aliases[i]);
1107                     if (ret.others.length > MAX_RESULTS) {
1108                         ret.others.pop();
1109                     }
1110                 }
1111             }
1112             return ret;
1113         }
1114
1115         /**
1116          * Validate performs the following boolean logic. For example:
1117          * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1118          * exists in (name || path || parent) OR => ("file" && "open") exists in
1119          * (name || path )
1120          *
1121          * This could be written functionally, but I wanted to minimise
1122          * functions on stack.
1123          *
1124          * @param  {[string]} name   [The name of the result]
1125          * @param  {[string]} path   [The path of the result]
1126          * @param  {[string]} keys   [The keys to be used (["file", "open"])]
1127          * @param  {[object]} parent [The parent of the result]
1128          * @return {[boolean]}       [Whether the result is valid or not]
1129          */
1130         function validateResult(name, path, keys, parent) {
1131             for (var i = 0; i < keys.length; ++i) {
1132                 // each check is for validation so we negate the conditions and invalidate
1133                 if (!(
1134                     // check for an exact name match
1135                     name.indexOf(keys[i]) > -1 ||
1136                     // then an exact path match
1137                     path.indexOf(keys[i]) > -1 ||
1138                     // next if there is a parent, check for exact parent match
1139                     (parent !== undefined &&
1140                         parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1141                     // lastly check to see if the name was a levenshtein match
1142                     levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1143                     return false;
1144                 }
1145             }
1146             return true;
1147         }
1148
1149         function getQuery(raw) {
1150             var matches, type, query;
1151             query = raw;
1152
1153             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1154             if (matches) {
1155                 type = matches[1].replace(/^const$/, "constant");
1156                 query = query.substring(matches[0].length);
1157             }
1158
1159             return {
1160                 raw: raw,
1161                 query: query,
1162                 type: type,
1163                 id: query + type
1164             };
1165         }
1166
1167         function initSearchNav() {
1168             var hoverTimeout;
1169
1170             var click_func = function(e) {
1171                 var el = e.target;
1172                 // to retrieve the real "owner" of the event.
1173                 while (el.tagName !== "TR") {
1174                     el = el.parentNode;
1175                 }
1176                 var dst = e.target.getElementsByTagName("a");
1177                 if (dst.length < 1) {
1178                     return;
1179                 }
1180                 dst = dst[0];
1181                 if (window.location.pathname === dst.pathname) {
1182                     addClass(document.getElementById("search"), "hidden");
1183                     removeClass(main, "hidden");
1184                     document.location.href = dst.href;
1185                 }
1186             };
1187             var mouseover_func = function(e) {
1188                 var el = e.target;
1189                 // to retrieve the real "owner" of the event.
1190                 while (el.tagName !== "TR") {
1191                     el = el.parentNode;
1192                 }
1193                 clearTimeout(hoverTimeout);
1194                 hoverTimeout = setTimeout(function() {
1195                     onEach(document.getElementsByClassName("search-results"), function(e) {
1196                         onEach(e.getElementsByClassName("result"), function(i_e) {
1197                             removeClass(i_e, "highlighted");
1198                         });
1199                     });
1200                     addClass(el, "highlighted");
1201                 }, 20);
1202             };
1203             onEach(document.getElementsByClassName("search-results"), function(e) {
1204                 onEach(e.getElementsByClassName("result"), function(i_e) {
1205                     i_e.onclick = click_func;
1206                     i_e.onmouseover = mouseover_func;
1207                 });
1208             });
1209
1210             search_input.onkeydown = function(e) {
1211                 // "actives" references the currently highlighted item in each search tab.
1212                 // Each array in "actives" represents a tab.
1213                 var actives = [[], [], []];
1214                 // "current" is used to know which tab we're looking into.
1215                 var current = 0;
1216                 onEach(document.getElementsByClassName("search-results"), function(e) {
1217                     onEach(e.getElementsByClassName("highlighted"), function(e) {
1218                         actives[current].push(e);
1219                     });
1220                     current += 1;
1221                 });
1222
1223                 if (e.which === 38) { // up
1224                     if (!actives[currentTab].length ||
1225                         !actives[currentTab][0].previousElementSibling) {
1226                         return;
1227                     }
1228
1229                     addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1230                     removeClass(actives[currentTab][0], "highlighted");
1231                 } else if (e.which === 40) { // down
1232                     if (!actives[currentTab].length) {
1233                         var results = document.getElementsByClassName("search-results");
1234                         if (results.length > 0) {
1235                             var res = results[currentTab].getElementsByClassName("result");
1236                             if (res.length > 0) {
1237                                 addClass(res[0], "highlighted");
1238                             }
1239                         }
1240                     } else if (actives[currentTab][0].nextElementSibling) {
1241                         addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1242                         removeClass(actives[currentTab][0], "highlighted");
1243                     }
1244                 } else if (e.which === 13) { // return
1245                     if (actives[currentTab].length) {
1246                         document.location.href =
1247                             actives[currentTab][0].getElementsByTagName("a")[0].href;
1248                     }
1249                 } else if (e.which === 9) { // tab
1250                     if (e.shiftKey) {
1251                         printTab(currentTab > 0 ? currentTab - 1 : 2);
1252                     } else {
1253                         printTab(currentTab > 1 ? 0 : currentTab + 1);
1254                     }
1255                     e.preventDefault();
1256                 } else if (e.which === 16) { // shift
1257                     // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1258                 } else if (e.which === 27) { // escape
1259                     removeClass(actives[currentTab][0], "highlighted");
1260                     search_input.value = "";
1261                     defocusSearchBar();
1262                 } else if (actives[currentTab].length > 0) {
1263                     removeClass(actives[currentTab][0], "highlighted");
1264                 }
1265             };
1266         }
1267
1268         function buildHrefAndPath(item) {
1269             var displayPath;
1270             var href;
1271             var type = itemTypes[item.ty];
1272             var name = item.name;
1273
1274             if (type === "mod") {
1275                 displayPath = item.path + "::";
1276                 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1277                        name + "/index.html";
1278             } else if (type === "primitive" || type === "keyword") {
1279                 displayPath = "";
1280                 href = rootPath + item.path.replace(/::/g, "/") +
1281                        "/" + type + "." + name + ".html";
1282             } else if (type === "externcrate") {
1283                 displayPath = "";
1284                 href = rootPath + name + "/index.html";
1285             } else if (item.parent !== undefined) {
1286                 var myparent = item.parent;
1287                 var anchor = "#" + type + "." + name;
1288                 var parentType = itemTypes[myparent.ty];
1289                 if (parentType === "primitive") {
1290                     displayPath = myparent.name + "::";
1291                 } else {
1292                     displayPath = item.path + "::" + myparent.name + "::";
1293                 }
1294                 href = rootPath + item.path.replace(/::/g, "/") +
1295                        "/" + parentType +
1296                        "." + myparent.name +
1297                        ".html" + anchor;
1298             } else {
1299                 displayPath = item.path + "::";
1300                 href = rootPath + item.path.replace(/::/g, "/") +
1301                        "/" + type + "." + name + ".html";
1302             }
1303             return [displayPath, href];
1304         }
1305
1306         function escape(content) {
1307             var h1 = document.createElement("h1");
1308             h1.textContent = content;
1309             return h1.innerHTML;
1310         }
1311
1312         function pathSplitter(path) {
1313             var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1314             if (tmp.endsWith("<span>")) {
1315                 return tmp.slice(0, tmp.length - 6);
1316             }
1317             return tmp;
1318         }
1319
1320         function addTab(array, query, display) {
1321             var extraStyle = "";
1322             if (display === false) {
1323                 extraStyle = " style=\"display: none;\"";
1324             }
1325
1326             var output = "";
1327             var duplicates = {};
1328             var length = 0;
1329             if (array.length > 0) {
1330                 output = "<table class=\"search-results\"" + extraStyle + ">";
1331
1332                 array.forEach(function(item) {
1333                     var name, type;
1334
1335                     name = item.name;
1336                     type = itemTypes[item.ty];
1337
1338                     if (item.is_alias !== true) {
1339                         if (duplicates[item.fullPath]) {
1340                             return;
1341                         }
1342                         duplicates[item.fullPath] = true;
1343                     }
1344                     length += 1;
1345
1346                     output += "<tr class=\"" + type + " result\"><td>" +
1347                               "<a href=\"" + item.href + "\">" +
1348                               (item.is_alias === true ?
1349                                ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1350                                   "class=\"grey\"><i>&nbsp;- see&nbsp;</i></span>") : "") +
1351                               item.displayPath + "<span class=\"" + type + "\">" +
1352                               name + "</span></a></td><td>" +
1353                               "<a href=\"" + item.href + "\">" +
1354                               "<span class=\"desc\">" + escape(item.desc) +
1355                               "&nbsp;</span></a></td></tr>";
1356                 });
1357                 output += "</table>";
1358             } else {
1359                 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1360                     "Try on <a href=\"https://duckduckgo.com/?q=" +
1361                     encodeURIComponent("rust " + query.query) +
1362                     "\">DuckDuckGo</a>?<br/><br/>" +
1363                     "Or try looking in one of these:<ul><li>The <a " +
1364                     "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1365                     " for technical details about the language.</li><li><a " +
1366                     "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1367                     "Example</a> for expository code examples.</a></li><li>The <a " +
1368                     "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1369                     "introductions to language features and the language itself.</li><li><a " +
1370                     "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1371                     " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1372             }
1373             return [output, length];
1374         }
1375
1376         function makeTabHeader(tabNb, text, nbElems) {
1377             if (currentTab === tabNb) {
1378                 return "<div class=\"selected\">" + text +
1379                        " <div class=\"count\">(" + nbElems + ")</div></div>";
1380             }
1381             return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1382         }
1383
1384         function showResults(results) {
1385             if (results.others.length === 1 &&
1386                 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1387                 var elem = document.createElement("a");
1388                 elem.href = results.others[0].href;
1389                 elem.style.display = "none";
1390                 // For firefox, we need the element to be in the DOM so it can be clicked.
1391                 document.body.appendChild(elem);
1392                 elem.click();
1393             }
1394             var query = getQuery(search_input.value);
1395
1396             currentResults = query.id;
1397
1398             var ret_others = addTab(results.others, query);
1399             var ret_in_args = addTab(results.in_args, query, false);
1400             var ret_returned = addTab(results.returned, query, false);
1401
1402             var output = "<h1>Results for " + escape(query.query) +
1403                 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1404                 "<div id=\"titles\">" +
1405                 makeTabHeader(0, "In Names", ret_others[1]) +
1406                 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1407                 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1408                 "</div><div id=\"results\">" +
1409                 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1410
1411             addClass(main, "hidden");
1412             var search = document.getElementById("search");
1413             removeClass(search, "hidden");
1414             search.innerHTML = output;
1415             var tds = search.getElementsByTagName("td");
1416             var td_width = 0;
1417             if (tds.length > 0) {
1418                 td_width = tds[0].offsetWidth;
1419             }
1420             var width = search.offsetWidth - 40 - td_width;
1421             onEach(Array.prototype.slice.call(search.getElementsByClassName("desc")), function(e) {
1422                 e.style.width = width + "px";
1423             });
1424             initSearchNav();
1425             var elems = document.getElementById("titles").childNodes;
1426             elems[0].onclick = function() { printTab(0); };
1427             elems[1].onclick = function() { printTab(1); };
1428             elems[2].onclick = function() { printTab(2); };
1429             printTab(currentTab);
1430         }
1431
1432         function execSearch(query, searchWords, filterCrates) {
1433             function getSmallest(arrays, positions, notDuplicates) {
1434                 var start = null;
1435
1436                 for (var it = 0; it < positions.length; ++it) {
1437                     if (arrays[it].length > positions[it] &&
1438                         (start === null || start > arrays[it][positions[it]].lev) &&
1439                         !notDuplicates[arrays[it][positions[it]].fullPath]) {
1440                         start = arrays[it][positions[it]].lev;
1441                     }
1442                 }
1443                 return start;
1444             }
1445
1446             function mergeArrays(arrays) {
1447                 var ret = [];
1448                 var positions = [];
1449                 var notDuplicates = {};
1450
1451                 for (var x = 0; x < arrays.length; ++x) {
1452                     positions.push(0);
1453                 }
1454                 while (ret.length < MAX_RESULTS) {
1455                     var smallest = getSmallest(arrays, positions, notDuplicates);
1456
1457                     if (smallest === null) {
1458                         break;
1459                     }
1460                     for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1461                         if (arrays[x].length > positions[x] &&
1462                                 arrays[x][positions[x]].lev === smallest &&
1463                                 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1464                             ret.push(arrays[x][positions[x]]);
1465                             notDuplicates[arrays[x][positions[x]].fullPath] = true;
1466                             positions[x] += 1;
1467                         }
1468                     }
1469                 }
1470                 return ret;
1471             }
1472
1473             var queries = query.raw.split(",");
1474             var results = {
1475                 "in_args": [],
1476                 "returned": [],
1477                 "others": [],
1478             };
1479
1480             for (var i = 0; i < queries.length; ++i) {
1481                 query = queries[i].trim();
1482                 if (query.length !== 0) {
1483                     var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1484
1485                     results.in_args.push(tmp.in_args);
1486                     results.returned.push(tmp.returned);
1487                     results.others.push(tmp.others);
1488                 }
1489             }
1490             if (queries.length > 1) {
1491                 return {
1492                     "in_args": mergeArrays(results.in_args),
1493                     "returned": mergeArrays(results.returned),
1494                     "others": mergeArrays(results.others),
1495                 };
1496             } else {
1497                 return {
1498                     "in_args": results.in_args[0],
1499                     "returned": results.returned[0],
1500                     "others": results.others[0],
1501                 };
1502             }
1503         }
1504
1505         function getFilterCrates() {
1506             var elem = document.getElementById("crate-search");
1507
1508             if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1509                 return elem.value;
1510             }
1511             return undefined;
1512         }
1513
1514         function search(e, forced) {
1515             var params = getQueryStringParams();
1516             var query = getQuery(search_input.value.trim());
1517
1518             if (e) {
1519                 e.preventDefault();
1520             }
1521
1522             if (query.query.length === 0) {
1523                 return;
1524             }
1525             if (forced !== true && query.id === currentResults) {
1526                 if (query.query.length > 0) {
1527                     putBackSearch(search_input);
1528                 }
1529                 return;
1530             }
1531
1532             // Update document title to maintain a meaningful browser history
1533             document.title = "Results for " + query.query + " - Rust";
1534
1535             // Because searching is incremental by character, only the most
1536             // recent search query is added to the browser history.
1537             if (browserSupportsHistoryApi()) {
1538                 if (!history.state && !params.search) {
1539                     history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1540                 } else {
1541                     history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1542                 }
1543             }
1544
1545             var filterCrates = getFilterCrates();
1546             showResults(execSearch(query, index, filterCrates), filterCrates);
1547         }
1548
1549         function buildIndex(rawSearchIndex) {
1550             searchIndex = [];
1551             var searchWords = [];
1552             var i;
1553
1554             for (var crate in rawSearchIndex) {
1555                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1556
1557                 searchWords.push(crate);
1558                 searchIndex.push({
1559                     crate: crate,
1560                     ty: 1, // == ExternCrate
1561                     name: crate,
1562                     path: "",
1563                     desc: rawSearchIndex[crate].doc,
1564                     type: null,
1565                 });
1566
1567                 // an array of [(Number) item type,
1568                 //              (String) name,
1569                 //              (String) full path or empty string for previous path,
1570                 //              (String) description,
1571                 //              (Number | null) the parent path index to `paths`]
1572                 //              (Object | null) the type of the function (if any)
1573                 var items = rawSearchIndex[crate].items;
1574                 // an array of [(Number) item type,
1575                 //              (String) name]
1576                 var paths = rawSearchIndex[crate].paths;
1577
1578                 // convert `paths` into an object form
1579                 var len = paths.length;
1580                 for (i = 0; i < len; ++i) {
1581                     paths[i] = {ty: paths[i][0], name: paths[i][1]};
1582                 }
1583
1584                 // convert `items` into an object form, and construct word indices.
1585                 //
1586                 // before any analysis is performed lets gather the search terms to
1587                 // search against apart from the rest of the data.  This is a quick
1588                 // operation that is cached for the life of the page state so that
1589                 // all other search operations have access to this cached data for
1590                 // faster analysis operations
1591                 len = items.length;
1592                 var lastPath = "";
1593                 for (i = 0; i < len; ++i) {
1594                     var rawRow = items[i];
1595                     var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1596                                path: rawRow[2] || lastPath, desc: rawRow[3],
1597                                parent: paths[rawRow[4]], type: rawRow[5]};
1598                     searchIndex.push(row);
1599                     if (typeof row.name === "string") {
1600                         var word = row.name.toLowerCase();
1601                         searchWords.push(word);
1602                     } else {
1603                         searchWords.push("");
1604                     }
1605                     lastPath = row.path;
1606                 }
1607             }
1608             return searchWords;
1609         }
1610
1611         function startSearch() {
1612             var searchTimeout;
1613             var callback = function() {
1614                 clearTimeout(searchTimeout);
1615                 if (search_input.value.length === 0) {
1616                     if (browserSupportsHistoryApi()) {
1617                         history.replaceState("", "std - Rust", "?search=");
1618                     }
1619                     if (hasClass(main, "content")) {
1620                         removeClass(main, "hidden");
1621                     }
1622                     var search_c = document.getElementById("search");
1623                     if (hasClass(search_c, "content")) {
1624                         addClass(search_c, "hidden");
1625                     }
1626                 } else {
1627                     searchTimeout = setTimeout(search, 500);
1628                 }
1629             };
1630             search_input.onkeyup = callback;
1631             search_input.oninput = callback;
1632             document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1633                 e.preventDefault();
1634                 clearTimeout(searchTimeout);
1635                 search();
1636             };
1637             search_input.onchange = function(e) {
1638                 // Do NOT e.preventDefault() here. It will prevent pasting.
1639                 clearTimeout(searchTimeout);
1640                 // zero-timeout necessary here because at the time of event handler execution the
1641                 // pasted content is not in the input field yet. Shouldn’t make any difference for
1642                 // change, though.
1643                 setTimeout(search, 0);
1644             };
1645             search_input.onpaste = search_input.onchange;
1646
1647             var selectCrate = document.getElementById('crate-search');
1648             if (selectCrate) {
1649                 selectCrate.onchange = function() {
1650                     search(undefined, true);
1651                 };
1652             }
1653
1654             // Push and pop states are used to add search results to the browser
1655             // history.
1656             if (browserSupportsHistoryApi()) {
1657                 // Store the previous <title> so we can revert back to it later.
1658                 var previousTitle = document.title;
1659
1660                 window.onpopstate = function(e) {
1661                     var params = getQueryStringParams();
1662                     // When browsing back from search results the main page
1663                     // visibility must be reset.
1664                     if (!params.search) {
1665                         if (hasClass(main, "content")) {
1666                             removeClass(main, "hidden");
1667                         }
1668                         var search_c = document.getElementById("search");
1669                         if (hasClass(search_c, "content")) {
1670                             addClass(search_c, "hidden");
1671                         }
1672                     }
1673                     // Revert to the previous title manually since the History
1674                     // API ignores the title parameter.
1675                     document.title = previousTitle;
1676                     // When browsing forward to search results the previous
1677                     // search will be repeated, so the currentResults are
1678                     // cleared to ensure the search is successful.
1679                     currentResults = null;
1680                     // Synchronize search bar with query string state and
1681                     // perform the search. This will empty the bar if there's
1682                     // nothing there, which lets you really go back to a
1683                     // previous state with nothing in the bar.
1684                     if (params.search) {
1685                         search_input.value = params.search;
1686                     } else {
1687                         search_input.value = "";
1688                     }
1689                     // Some browsers fire "onpopstate" for every page load
1690                     // (Chrome), while others fire the event only when actually
1691                     // popping a state (Firefox), which is why search() is
1692                     // called both here and at the end of the startSearch()
1693                     // function.
1694                     search();
1695                 };
1696             }
1697             search();
1698         }
1699
1700         index = buildIndex(rawSearchIndex);
1701         startSearch();
1702
1703         // Draw a convenient sidebar of known crates if we have a listing
1704         if (rootPath === "../" || rootPath === "./") {
1705             var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1706             if (sidebar) {
1707                 var div = document.createElement("div");
1708                 div.className = "block crate";
1709                 div.innerHTML = "<h3>Crates</h3>";
1710                 var ul = document.createElement("ul");
1711                 div.appendChild(ul);
1712
1713                 var crates = [];
1714                 for (var crate in rawSearchIndex) {
1715                     if (!rawSearchIndex.hasOwnProperty(crate)) {
1716                         continue;
1717                     }
1718                     crates.push(crate);
1719                 }
1720                 crates.sort();
1721                 for (var i = 0; i < crates.length; ++i) {
1722                     var klass = "crate";
1723                     if (rootPath !== "./" && crates[i] === window.currentCrate) {
1724                         klass += " current";
1725                     }
1726                     var link = document.createElement("a");
1727                     link.href = rootPath + crates[i] + "/index.html";
1728                     link.title = rawSearchIndex[crates[i]].doc;
1729                     link.className = klass;
1730                     link.textContent = crates[i];
1731
1732                     var li = document.createElement("li");
1733                     li.appendChild(link);
1734                     ul.appendChild(li);
1735                 }
1736                 sidebar.appendChild(div);
1737             }
1738         }
1739     }
1740
1741     window.initSearch = initSearch;
1742
1743     // delayed sidebar rendering.
1744     function initSidebarItems(items) {
1745         var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1746         var current = window.sidebarCurrent;
1747
1748         function block(shortty, longty) {
1749             var filtered = items[shortty];
1750             if (!filtered) {
1751                 return;
1752             }
1753
1754             var div = document.createElement("div");
1755             div.className = "block " + shortty;
1756             var h3 = document.createElement("h3");
1757             h3.textContent = longty;
1758             div.appendChild(h3);
1759             var ul = document.createElement("ul");
1760
1761             var length = filtered.length;
1762             for (var i = 0; i < length; ++i) {
1763                 var item = filtered[i];
1764                 var name = item[0];
1765                 var desc = item[1]; // can be null
1766
1767                 var klass = shortty;
1768                 if (name === current.name && shortty === current.ty) {
1769                     klass += " current";
1770                 }
1771                 var path;
1772                 if (shortty === "mod") {
1773                     path = name + "/index.html";
1774                 } else {
1775                     path = shortty + "." + name + ".html";
1776                 }
1777                 var link = document.createElement("a");
1778                 link.href = current.relpath + path;
1779                 link.title = desc;
1780                 link.className = klass;
1781                 link.textContent = name;
1782                 var li = document.createElement("li");
1783                 li.appendChild(link);
1784                 ul.appendChild(li);
1785             }
1786             div.appendChild(ul);
1787             if (sidebar) {
1788                 sidebar.appendChild(div);
1789             }
1790         }
1791
1792         block("primitive", "Primitive Types");
1793         block("mod", "Modules");
1794         block("macro", "Macros");
1795         block("struct", "Structs");
1796         block("enum", "Enums");
1797         block("union", "Unions");
1798         block("constant", "Constants");
1799         block("static", "Statics");
1800         block("trait", "Traits");
1801         block("fn", "Functions");
1802         block("type", "Type Definitions");
1803         block("foreigntype", "Foreign Types");
1804         block("keyword", "Keywords");
1805     }
1806
1807     window.initSidebarItems = initSidebarItems;
1808
1809     window.register_implementors = function(imp) {
1810         var implementors = document.getElementById("implementors-list");
1811         var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1812
1813         var libs = Object.getOwnPropertyNames(imp);
1814         var llength = libs.length;
1815         for (var i = 0; i < llength; ++i) {
1816             if (libs[i] === currentCrate) { continue; }
1817             var structs = imp[libs[i]];
1818
1819             var slength = structs.length;
1820             struct_loop:
1821             for (var j = 0; j < slength; ++j) {
1822                 var struct = structs[j];
1823
1824                 var list = struct.synthetic ? synthetic_implementors : implementors;
1825
1826                 if (struct.synthetic) {
1827                     var stlength = struct.types.length;
1828                     for (var k = 0; k < stlength; k++) {
1829                         if (window.inlined_types.has(struct.types[k])) {
1830                             continue struct_loop;
1831                         }
1832                         window.inlined_types.add(struct.types[k]);
1833                     }
1834                 }
1835
1836                 var code = document.createElement("code");
1837                 code.innerHTML = struct.text;
1838
1839                 var x = code.getElementsByTagName("a");
1840                 var xlength = x.length;
1841                 for (var it = 0; it < xlength; it++) {
1842                     var href = x[it].getAttribute("href");
1843                     if (href && href.indexOf("http") !== 0) {
1844                         x[it].setAttribute("href", rootPath + href);
1845                     }
1846                 }
1847                 var display = document.createElement("h3");
1848                 addClass(display, "impl");
1849                 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1850                     "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1851                     "</tbody></table></span>";
1852                 list.appendChild(display);
1853             }
1854         }
1855     };
1856     if (window.pending_implementors) {
1857         window.register_implementors(window.pending_implementors);
1858     }
1859
1860     function labelForToggleButton(sectionIsCollapsed) {
1861         if (sectionIsCollapsed) {
1862             // button will expand the section
1863             return "+";
1864         }
1865         // button will collapse the section
1866         // note that this text is also set in the HTML template in render.rs
1867         return "\u2212"; // "\u2212" is "−" minus sign
1868     }
1869
1870     function onEveryMatchingChild(elem, className, func) {
1871         if (elem && className && func) {
1872             var length = elem.childNodes.length;
1873             var nodes = elem.childNodes;
1874             for (var i = 0; i < length; ++i) {
1875                 if (hasClass(nodes[i], className)) {
1876                     func(nodes[i]);
1877                 } else {
1878                     onEveryMatchingChild(nodes[i], className, func);
1879                 }
1880             }
1881         }
1882     }
1883
1884     function toggleAllDocs(pageId, fromAutoCollapse) {
1885         var innerToggle = document.getElementById("toggle-all-docs");
1886         if (!innerToggle) {
1887             return;
1888         }
1889         if (hasClass(innerToggle, "will-expand")) {
1890             updateLocalStorage("rustdoc-collapse", "false");
1891             removeClass(innerToggle, "will-expand");
1892             onEveryMatchingChild(innerToggle, "inner", function(e) {
1893                 e.innerHTML = labelForToggleButton(false);
1894             });
1895             innerToggle.title = "collapse all docs";
1896             if (fromAutoCollapse !== true) {
1897                 onEach(Array.prototype.slice.call(
1898                            document.getElementsByClassName("collapse-toggle")),
1899                        function(e) {
1900                     collapseDocs(e, "show");
1901                 });
1902             }
1903         } else {
1904             updateLocalStorage("rustdoc-collapse", "true");
1905             addClass(innerToggle, "will-expand");
1906             onEveryMatchingChild(innerToggle, "inner", function(e) {
1907                 e.innerHTML = labelForToggleButton(true);
1908             });
1909             innerToggle.title = "expand all docs";
1910             if (fromAutoCollapse !== true) {
1911                 onEach(Array.prototype.slice.call(
1912                            document.getElementsByClassName("collapse-toggle")),
1913                        function(e) {
1914                     collapseDocs(e, "hide", pageId);
1915                 });
1916             }
1917         }
1918     }
1919
1920     function collapseDocs(toggle, mode, pageId) {
1921         if (!toggle || !toggle.parentNode) {
1922             return;
1923         }
1924
1925         function adjustToggle(arg) {
1926             return function(e) {
1927                 if (hasClass(e, "toggle-label")) {
1928                     if (arg) {
1929                         e.style.display = "inline-block";
1930                     } else {
1931                         e.style.display = "none";
1932                     }
1933                 }
1934                 if (hasClass(e, "inner")) {
1935                     e.innerHTML = labelForToggleButton(arg);
1936                 }
1937             };
1938         }
1939
1940         function implHider(addOrRemove) {
1941             return function(n) {
1942                 var is_method = hasClass(n, "method");
1943                 if (is_method || hasClass(n, "type")) {
1944                     if (is_method === true) {
1945                         if (addOrRemove) {
1946                             addClass(n, "hidden-by-impl-hider");
1947                         } else {
1948                             removeClass(n, "hidden-by-impl-hider");
1949                         }
1950                     }
1951                     var ns = n.nextElementSibling;
1952                     while (true) {
1953                         if (ns && (
1954                                 hasClass(ns, "docblock") ||
1955                                 hasClass(ns, "stability"))) {
1956                             if (addOrRemove) {
1957                                 addClass(ns, "hidden-by-impl-hider");
1958                             } else {
1959                                 removeClass(ns, "hidden-by-impl-hider");
1960                             }
1961                             ns = ns.nextElementSibling;
1962                             continue;
1963                         }
1964                         break;
1965                     }
1966                 }
1967             };
1968         }
1969
1970         var relatedDoc;
1971         var action;
1972         if (hasClass(toggle.parentNode, "impl") === false) {
1973             relatedDoc = toggle.parentNode.nextElementSibling;
1974             if (hasClass(relatedDoc, "stability")) {
1975                 relatedDoc = relatedDoc.nextElementSibling;
1976             }
1977             if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1978                 if (mode === "toggle") {
1979                     if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1980                         action = "show";
1981                     } else {
1982                         action = "hide";
1983                     }
1984                 }
1985                 if (action === "hide") {
1986                     addClass(relatedDoc, "hidden-by-usual-hider");
1987                     onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
1988                     addClass(toggle.parentNode, "collapsed");
1989                 } else if (action === "show") {
1990                     removeClass(relatedDoc, "hidden-by-usual-hider");
1991                     removeClass(toggle.parentNode, "collapsed");
1992                     onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
1993                 }
1994             }
1995         } else {
1996             // we are collapsing the impl block
1997
1998             var parentElem = toggle.parentNode;
1999             relatedDoc = parentElem;
2000             var docblock = relatedDoc.nextElementSibling;
2001
2002             while (hasClass(relatedDoc, "impl-items") === false) {
2003                 relatedDoc = relatedDoc.nextElementSibling;
2004             }
2005
2006             if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2007                 (pageId && relatedDoc.getElementById(pageId))) {
2008                 return;
2009             }
2010
2011             // Hide all functions, but not associated types/consts
2012
2013             if (mode === "toggle") {
2014                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2015                     hasClass(docblock, "hidden-by-impl-hider")) {
2016                     action = "show";
2017                 } else {
2018                     action = "hide";
2019                 }
2020             }
2021
2022             if (action === "show") {
2023                 removeClass(relatedDoc, "fns-now-collapsed");
2024                 removeClass(docblock, "hidden-by-usual-hider");
2025                 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
2026                 onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(false));
2027             } else if (action === "hide") {
2028                 addClass(relatedDoc, "fns-now-collapsed");
2029                 addClass(docblock, "hidden-by-usual-hider");
2030                 onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
2031                 onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(true));
2032             }
2033         }
2034     }
2035
2036     function collapser(e) {
2037         // inherent impl ids are like "impl" or impl-<number>'.
2038         // they will never be hidden by default.
2039         var n = e.parentElement;
2040         if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2041             // Automatically minimize all non-inherent impls
2042             if (collapse || hasClass(n, "impl")) {
2043                 collapseDocs(e, "hide", pageId);
2044             }
2045         }
2046     }
2047
2048     function autoCollapse(pageId, collapse) {
2049         if (collapse) {
2050             toggleAllDocs(pageId, true);
2051         } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2052             var impl_list = document.getElementById("implementations-list");
2053
2054             if (impl_list !== null) {
2055                 onEach(Array.prototype.slice.call(
2056                            impl_list.getElementsByClassName("collapse-toggle")),
2057                        collapser);
2058             }
2059         }
2060     }
2061
2062     var toggles = document.getElementById("toggle-all-docs");
2063     if (toggles) {
2064         toggles.onclick = toggleAllDocs;
2065     }
2066
2067     function insertAfter(newNode, referenceNode) {
2068         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2069     }
2070
2071     function createSimpleToggle(sectionIsCollapsed) {
2072         var toggle = document.createElement("a");
2073         toggle.href = "javascript:void(0)";
2074         toggle.className = "collapse-toggle";
2075         toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2076                            "</span>]";
2077         return toggle;
2078     }
2079
2080     var toggle = createSimpleToggle(false);
2081
2082     var func = function(e) {
2083         var next = e.nextElementSibling;
2084         if (!next) {
2085             return;
2086         }
2087         if (hasClass(next, "docblock") ||
2088             (hasClass(next, "stability") &&
2089              hasClass(next.nextElementSibling, "docblock"))) {
2090             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2091         }
2092     };
2093
2094     var funcImpl = function(e) {
2095         var next = e.nextElementSibling;
2096         if (next && hasClass(next, "docblock")) {
2097             next = next.nextElementSibling;
2098         }
2099         if (!next) {
2100             return;
2101         }
2102         if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2103             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2104         }
2105     };
2106
2107     onEach(Array.prototype.slice.call(document.getElementsByClassName("method")), func);
2108     onEach(Array.prototype.slice.call(document.getElementsByClassName("associatedconstant")), func);
2109     onEach(Array.prototype.slice.call(document.getElementsByClassName("impl")), funcImpl);
2110     var impl_call = function() {};
2111     if (getCurrentValue("rustdoc-method-docs") !== "false") {
2112         impl_call = function(e, newToggle, pageId) {
2113             if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2114                 // Automatically minimize all non-inherent impls
2115                 if (hasClass(e, "impl")) {
2116                     collapseDocs(newToggle, "hide", pageId);
2117                 }
2118             }
2119         };
2120     }
2121     var pageId = getPageId();
2122     var newToggle = document.createElement("a");
2123     newToggle.href = "javascript:void(0)";
2124     newToggle.className = "collapse-toggle hidden-default collapsed";
2125     newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2126                           "</span>] Show hidden undocumented items";
2127     function toggleClicked() {
2128         if (hasClass(this, "collapsed")) {
2129             removeClass(this, "collapsed");
2130             onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("hidden")),
2131                    function(x) {
2132                 if (hasClass(x, "content") === false) {
2133                     removeClass(x, "hidden");
2134                     addClass(x, "x");
2135                 }
2136             }, true);
2137             this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2138                              "</span>] Hide undocumented items";
2139         } else {
2140             addClass(this, "collapsed");
2141             onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("x")),
2142                    function(x) {
2143                 if (hasClass(x, "content") === false) {
2144                     addClass(x, "hidden");
2145                     removeClass(x, "x");
2146                 }
2147             }, true);
2148             this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2149                              "</span>] Show hidden undocumented items";
2150         }
2151     }
2152     onEach(Array.prototype.slice.call(document.getElementsByClassName("impl-items")), function(e) {
2153         onEach(Array.prototype.slice.call(e.getElementsByClassName("associatedconstant")), func);
2154         var hiddenElems = e.getElementsByClassName("hidden");
2155         var needToggle = false;
2156
2157         var hlength = hiddenElems.length;
2158         for (var i = 0; i < hlength; ++i) {
2159             if (hasClass(hiddenElems[i], "content") === false &&
2160                 hasClass(hiddenElems[i], "docblock") === false) {
2161                 needToggle = true;
2162                 break;
2163             }
2164         }
2165         if (needToggle === true) {
2166             var inner_toggle = newToggle.cloneNode(true);
2167             inner_toggle.onclick = toggleClicked;
2168             e.insertBefore(inner_toggle, e.firstChild);
2169             impl_call(e, inner_toggle, pageId);
2170         }
2171     });
2172
2173     function createToggle(otherMessage, fontSize, extraClass, show) {
2174         var span = document.createElement("span");
2175         span.className = "toggle-label";
2176         if (show) {
2177             span.style.display = "none";
2178         }
2179         if (!otherMessage) {
2180             span.innerHTML = "&nbsp;Expand&nbsp;description";
2181         } else {
2182             span.innerHTML = otherMessage;
2183         }
2184
2185         if (fontSize) {
2186             span.style.fontSize = fontSize;
2187         }
2188
2189         var mainToggle = toggle.cloneNode(true);
2190         mainToggle.appendChild(span);
2191
2192         var wrapper = document.createElement("div");
2193         wrapper.className = "toggle-wrapper";
2194         if (!show) {
2195             addClass(wrapper, "collapsed");
2196             var inner = mainToggle.getElementsByClassName("inner");
2197             if (inner && inner.length > 0) {
2198                 inner[0].innerHTML = "+";
2199             }
2200         }
2201         if (extraClass) {
2202             addClass(wrapper, extraClass);
2203         }
2204         wrapper.appendChild(mainToggle);
2205         return wrapper;
2206     }
2207
2208     var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2209     function buildToggleWrapper(e) {
2210         if (hasClass(e, "autohide")) {
2211             var wrap = e.previousElementSibling;
2212             if (wrap && hasClass(wrap, "toggle-wrapper")) {
2213                 var inner_toggle = wrap.childNodes[0];
2214                 var extra = e.childNodes[0].tagName === "H3";
2215
2216                 e.style.display = "none";
2217                 addClass(wrap, "collapsed");
2218                 onEach(Array.prototype.slice.call(inner_toggle.getElementsByClassName("inner")),
2219                        function(e) {
2220                     e.innerHTML = labelForToggleButton(true);
2221                 });
2222                 onEach(Array.prototype.slice.call(
2223                            inner_toggle.getElementsByClassName("toggle-label")),
2224                        function(e) {
2225                     e.style.display = "inline-block";
2226                     if (extra === true) {
2227                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2228                     }
2229                 });
2230             }
2231         }
2232         if (e.parentNode.id === "main") {
2233             var otherMessage = "";
2234             var fontSize;
2235             var extraClass;
2236
2237             if (hasClass(e, "type-decl")) {
2238                 fontSize = "20px";
2239                 otherMessage = "&nbsp;Show&nbsp;declaration";
2240                 if (showItemDeclarations === false) {
2241                     extraClass = "collapsed";
2242                 }
2243             } else if (hasClass(e, "sub-variant")) {
2244                 otherMessage = "&nbsp;Show&nbsp;fields";
2245             } else if (hasClass(e, "non-exhaustive")) {
2246                 otherMessage = "&nbsp;This&nbsp;";
2247                 if (hasClass(e, "non-exhaustive-struct")) {
2248                     otherMessage += "struct";
2249                 } else if (hasClass(e, "non-exhaustive-enum")) {
2250                     otherMessage += "enum";
2251                 } else if (hasClass(e, "non-exhaustive-type")) {
2252                     otherMessage += "type";
2253                 }
2254                 otherMessage += "&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive";
2255             } else if (hasClass(e.childNodes[0], "impl-items")) {
2256                 extraClass = "marg-left";
2257             }
2258
2259             e.parentNode.insertBefore(
2260                 createToggle(otherMessage,
2261                              fontSize,
2262                              extraClass,
2263                              hasClass(e, "type-decl") === false || showItemDeclarations === true),
2264                 e);
2265             if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2266                 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2267             }
2268         }
2269     }
2270
2271     onEach(Array.prototype.slice.call(document.getElementsByClassName("docblock")),
2272            buildToggleWrapper);
2273     onEach(Array.prototype.slice.call(document.getElementsByClassName("sub-variant")),
2274            buildToggleWrapper);
2275
2276     // In the search display, allows to switch between tabs.
2277     function printTab(nb) {
2278         if (nb === 0 || nb === 1 || nb === 2) {
2279             currentTab = nb;
2280         }
2281         var nb_copy = nb;
2282         onEach(Array.prototype.slice.call(document.getElementById("titles").childNodes),
2283                function(elem) {
2284             if (nb_copy === 0) {
2285                 addClass(elem, "selected");
2286             } else {
2287                 removeClass(elem, "selected");
2288             }
2289             nb_copy -= 1;
2290         });
2291         onEach(Array.prototype.slice.call(document.getElementById("results").childNodes),
2292                function(elem) {
2293             if (nb === 0) {
2294                 elem.style.display = "";
2295             } else {
2296                 elem.style.display = "none";
2297             }
2298             nb -= 1;
2299         });
2300     }
2301
2302     function createToggleWrapper(tog) {
2303         var span = document.createElement("span");
2304         span.className = "toggle-label";
2305         span.style.display = "none";
2306         span.innerHTML = "&nbsp;Expand&nbsp;attributes";
2307         tog.appendChild(span);
2308
2309         var wrapper = document.createElement("div");
2310         wrapper.className = "toggle-wrapper toggle-attributes";
2311         wrapper.appendChild(tog);
2312         return wrapper;
2313     }
2314
2315     // To avoid checking on "rustdoc-item-attributes" value on every loop...
2316     var itemAttributesFunc = function() {};
2317     if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2318         itemAttributesFunc = function(x) {
2319             collapseDocs(x.previousSibling.childNodes[0], "toggle");
2320         };
2321     }
2322     var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2323     onEach(Array.prototype.slice.call(main.getElementsByClassName("attributes")), function(i_e) {
2324         i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2325         itemAttributesFunc(i_e);
2326     });
2327
2328     // To avoid checking on "rustdoc-line-numbers" value on every loop...
2329     var lineNumbersFunc = function() {};
2330     if (getCurrentValue("rustdoc-line-numbers") === "true") {
2331         lineNumbersFunc = function(x) {
2332             var count = x.textContent.split("\n").length;
2333             var elems = [];
2334             for (var i = 0; i < count; ++i) {
2335                 elems.push(i + 1);
2336             }
2337             var node = document.createElement("pre");
2338             addClass(node, "line-number");
2339             node.innerHTML = elems.join("\n");
2340             x.parentNode.insertBefore(node, x);
2341         };
2342     }
2343     onEach(Array.prototype.slice.call(document.getElementsByClassName("rust-example-rendered")),
2344            function(e) {
2345         if (hasClass(e, "compile_fail")) {
2346             e.addEventListener("mouseover", function(event) {
2347                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2348             });
2349             e.addEventListener("mouseout", function(event) {
2350                 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2351             });
2352         } else if (hasClass(e, "ignore")) {
2353             e.addEventListener("mouseover", function(event) {
2354                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2355             });
2356             e.addEventListener("mouseout", function(event) {
2357                 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2358             });
2359         }
2360         lineNumbersFunc(e);
2361     });
2362
2363     function showModal(content) {
2364         var modal = document.createElement("div");
2365         modal.id = "important";
2366         addClass(modal, "modal");
2367         modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2368                           "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2369                           "</span></div>";
2370         document.getElementsByTagName("body")[0].appendChild(modal);
2371         document.getElementById("modal-close").onclick = hideModal;
2372         modal.onclick = hideModal;
2373     }
2374
2375     function hideModal() {
2376         var modal = document.getElementById("important");
2377         if (modal) {
2378             modal.parentNode.removeChild(modal);
2379         }
2380     }
2381
2382     onEach(Array.prototype.slice.call(document.getElementsByClassName("important-traits")),
2383            function(e) {
2384         e.onclick = function() {
2385             showModal(e.lastElementChild.innerHTML);
2386         };
2387     });
2388
2389     function putBackSearch(search_input) {
2390         if (search_input.value !== "") {
2391             addClass(main, "hidden");
2392             removeClass(document.getElementById("search"), "hidden");
2393             if (browserSupportsHistoryApi()) {
2394                 history.replaceState(search_input.value,
2395                                      "",
2396                                      "?search=" + encodeURIComponent(search_input.value));
2397             }
2398         }
2399     }
2400
2401     if (search_input) {
2402         search_input.onfocus = function() {
2403             putBackSearch(this);
2404         };
2405     }
2406
2407     var params = getQueryStringParams();
2408     if (params && params.search) {
2409         addClass(main, "hidden");
2410         var search = document.getElementById("search");
2411         removeClass(search, "hidden");
2412         search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2413     }
2414
2415     var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2416     if (sidebar_menu) {
2417         sidebar_menu.onclick = function() {
2418             var sidebar = document.getElementsByClassName("sidebar")[0];
2419             if (hasClass(sidebar, "mobile") === true) {
2420                 hideSidebar();
2421             } else {
2422                 showSidebar();
2423             }
2424         };
2425     }
2426
2427     window.onresize = function() {
2428         hideSidebar();
2429     };
2430
2431     autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2432
2433     if (window.location.hash && window.location.hash.length > 0) {
2434         expandSection(window.location.hash.replace(/^#/, ""));
2435     }
2436
2437     if (main) {
2438         onEach(Array.prototype.slice.call(main.childNodes), function(e) {
2439             if (e.tagName === "H2" || e.tagName === "H3") {
2440                 e.nextElementSibling.style.display = "block";
2441             }
2442         });
2443     }
2444
2445     function addSearchOptions(crates) {
2446         var elem = document.getElementById('crate-search');
2447
2448         if (!elem) {
2449             return;
2450         }
2451         var crates_text = [];
2452         for (var crate in crates) {
2453             if (crates.hasOwnProperty(crate)) {
2454                 crates_text.push(crate);
2455             }
2456         }
2457         crates_text.sort(function(a, b) {
2458             var lower_a = a.toLowerCase();
2459             var lower_b = b.toLowerCase();
2460
2461             if (lower_a < lower_b) {
2462                 return -1;
2463             } else if (lower_a > lower_b) {
2464                 return 1;
2465             }
2466             return 0;
2467         });
2468         for (var i = 0; i < crates_text.length; ++i) {
2469             var option = document.createElement("option");
2470             option.value = crates_text[i];
2471             option.innerText = crates_text[i];
2472             elem.appendChild(option);
2473         }
2474     }
2475
2476     window.addSearchOptions = addSearchOptions;
2477 }());
2478
2479 // Sets the focus on the search bar at the top of the page
2480 function focusSearchBar() {
2481     document.getElementsByClassName("search-input")[0].focus();
2482 }
2483
2484 // Removes the focus from the search bar
2485 function defocusSearchBar() {
2486     document.getElementsByClassName("search-input")[0].blur();
2487 }