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