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