main.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  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. /*jslint browser: true, es5: true */
  13. /*globals $: true, rootPath: true */
  14. (function() {
  15. "use strict";
  16. // This mapping table should match the discriminants of
  17. // `rustdoc::html::item_type::ItemType` type in Rust.
  18. var itemTypes = ["mod",
  19. "externcrate",
  20. "import",
  21. "struct",
  22. "enum",
  23. "fn",
  24. "type",
  25. "static",
  26. "trait",
  27. "impl",
  28. "tymethod",
  29. "method",
  30. "structfield",
  31. "variant",
  32. "macro",
  33. "primitive",
  34. "associatedtype",
  35. "constant",
  36. "associatedconstant",
  37. "union",
  38. "foreigntype"];
  39. // On the search screen, so you remain on the last tab you opened.
  40. //
  41. // 0 for "In Names"
  42. // 1 for "In Parameters"
  43. // 2 for "In Return Types"
  44. var currentTab = 0;
  45. var themesWidth = null;
  46. function hasClass(elem, className) {
  47. if (elem && className && elem.className) {
  48. var elemClass = elem.className;
  49. var start = elemClass.indexOf(className);
  50. if (start === -1) {
  51. return false;
  52. } else if (elemClass.length === className.length) {
  53. return true;
  54. } else {
  55. if (start > 0 && elemClass[start - 1] !== ' ') {
  56. return false;
  57. }
  58. var end = start + className.length;
  59. if (end < elemClass.length && elemClass[end] !== ' ') {
  60. return false;
  61. }
  62. return true;
  63. }
  64. if (start > 0 && elemClass[start - 1] !== ' ') {
  65. return false;
  66. }
  67. var end = start + className.length;
  68. if (end < elemClass.length && elemClass[end] !== ' ') {
  69. return false;
  70. }
  71. return true;
  72. }
  73. return false;
  74. }
  75. function addClass(elem, className) {
  76. if (elem && className && !hasClass(elem, className)) {
  77. if (elem.className && elem.className.length > 0) {
  78. elem.className += ' ' + className;
  79. } else {
  80. elem.className = className;
  81. }
  82. }
  83. }
  84. function removeClass(elem, className) {
  85. if (elem && className && elem.className) {
  86. elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
  87. .trim();
  88. }
  89. }
  90. function onEach(arr, func) {
  91. if (arr && arr.length > 0 && func) {
  92. for (var i = 0; i < arr.length; i++) {
  93. func(arr[i]);
  94. }
  95. }
  96. }
  97. function isHidden(elem) {
  98. return (elem.offsetParent === null)
  99. }
  100. function showSidebar() {
  101. var elems = document.getElementsByClassName("sidebar-elems")[0];
  102. if (elems) {
  103. addClass(elems, "show-it");
  104. }
  105. var sidebar = document.getElementsByClassName('sidebar')[0];
  106. if (sidebar) {
  107. addClass(sidebar, 'mobile');
  108. var filler = document.getElementById("sidebar-filler");
  109. if (!filler) {
  110. var div = document.createElement("div");
  111. div.id = "sidebar-filler";
  112. sidebar.appendChild(div);
  113. }
  114. }
  115. var themePicker = document.getElementsByClassName("theme-picker");
  116. if (themePicker && themePicker.length > 0) {
  117. themePicker[0].style.display = "none";
  118. }
  119. }
  120. function hideSidebar() {
  121. var elems = document.getElementsByClassName("sidebar-elems")[0];
  122. if (elems) {
  123. removeClass(elems, "show-it");
  124. }
  125. var sidebar = document.getElementsByClassName('sidebar')[0];
  126. removeClass(sidebar, 'mobile');
  127. var filler = document.getElementById("sidebar-filler");
  128. if (filler) {
  129. filler.remove();
  130. }
  131. document.getElementsByTagName("body")[0].style.marginTop = '';
  132. var themePicker = document.getElementsByClassName("theme-picker");
  133. if (themePicker && themePicker.length > 0) {
  134. themePicker[0].style.display = null;
  135. }
  136. }
  137. // used for special search precedence
  138. var TY_PRIMITIVE = itemTypes.indexOf("primitive");
  139. onEach(document.getElementsByClassName('js-only'), function(e) {
  140. removeClass(e, 'js-only');
  141. });
  142. function getQueryStringParams() {
  143. var params = {};
  144. window.location.search.substring(1).split("&").
  145. map(function(s) {
  146. var pair = s.split("=");
  147. params[decodeURIComponent(pair[0])] =
  148. typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
  149. });
  150. return params;
  151. }
  152. function browserSupportsHistoryApi() {
  153. return document.location.protocol != "file:" &&
  154. window.history && typeof window.history.pushState === "function";
  155. }
  156. function highlightSourceLines(ev) {
  157. // If we're in mobile mode, we should add the sidebar in any case.
  158. hideSidebar();
  159. var search = document.getElementById("search");
  160. var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
  161. if (match) {
  162. from = parseInt(match[1], 10);
  163. to = Math.min(50000, parseInt(match[2] || match[1], 10));
  164. from = Math.min(from, to);
  165. var elem = document.getElementById(from);
  166. if (!elem) {
  167. return;
  168. }
  169. if (ev === null) {
  170. var x = document.getElementById(from);
  171. if (x) {
  172. x.scrollIntoView();
  173. }
  174. }
  175. onEach(document.getElementsByClassName('line-numbers'), function(e) {
  176. onEach(e.getElementsByTagName('span'), function(i_e) {
  177. removeClass(i_e, 'line-highlighted');
  178. });
  179. })
  180. for (i = from; i <= to; ++i) {
  181. addClass(document.getElementById(i), 'line-highlighted');
  182. }
  183. } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
  184. addClass(search, "hidden");
  185. removeClass(document.getElementById("main"), "hidden");
  186. var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
  187. if (browserSupportsHistoryApi()) {
  188. history.replaceState(hash, "", "?search=#" + hash);
  189. }
  190. var elem = document.getElementById(hash);
  191. if (elem) {
  192. elem.scrollIntoView();
  193. }
  194. }
  195. }
  196. highlightSourceLines(null);
  197. window.onhashchange = highlightSourceLines;
  198. // Gets the human-readable string for the virtual-key code of the
  199. // given KeyboardEvent, ev.
  200. //
  201. // This function is meant as a polyfill for KeyboardEvent#key,
  202. // since it is not supported in Trident. We also test for
  203. // KeyboardEvent#keyCode because the handleShortcut handler is
  204. // also registered for the keydown event, because Blink doesn't fire
  205. // keypress on hitting the Escape key.
  206. //
  207. // So I guess you could say things are getting pretty interoperable.
  208. function getVirtualKey(ev) {
  209. if ("key" in ev && typeof ev.key != "undefined")
  210. return ev.key;
  211. var c = ev.charCode || ev.keyCode;
  212. if (c == 27)
  213. return "Escape";
  214. return String.fromCharCode(c);
  215. }
  216. function displayHelp(display, ev) {
  217. if (display === true) {
  218. if (hasClass(help, "hidden")) {
  219. ev.preventDefault();
  220. removeClass(help, "hidden");
  221. addClass(document.body, "blur");
  222. }
  223. } else if (!hasClass(help, "hidden")) {
  224. ev.preventDefault();
  225. addClass(help, "hidden");
  226. removeClass(document.body, "blur");
  227. }
  228. }
  229. function handleShortcut(ev) {
  230. if (document.activeElement.tagName === "INPUT")
  231. return;
  232. // Don't interfere with browser shortcuts
  233. if (ev.ctrlKey || ev.altKey || ev.metaKey)
  234. return;
  235. var help = document.getElementById("help");
  236. switch (getVirtualKey(ev)) {
  237. case "Escape":
  238. hideModal();
  239. var search = document.getElementById("search");
  240. if (!hasClass(help, "hidden")) {
  241. displayHelp(false, ev);
  242. } else if (!hasClass(search, "hidden")) {
  243. ev.preventDefault();
  244. addClass(search, "hidden");
  245. removeClass(document.getElementById("main"), "hidden");
  246. }
  247. defocusSearchBar();
  248. break;
  249. case "s":
  250. case "S":
  251. displayHelp(false, ev);
  252. hideModal();
  253. ev.preventDefault();
  254. focusSearchBar();
  255. break;
  256. case "+":
  257. case "-":
  258. ev.preventDefault();
  259. toggleAllDocs();
  260. break;
  261. case "?":
  262. if (ev.shiftKey) {
  263. hideModal();
  264. displayHelp(true, ev);
  265. }
  266. break;
  267. }
  268. }
  269. document.onkeypress = handleShortcut;
  270. document.onkeydown = handleShortcut;
  271. document.onclick = function(ev) {
  272. if (hasClass(ev.target, 'collapse-toggle')) {
  273. collapseDocs(ev.target);
  274. } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
  275. collapseDocs(ev.target.parentNode);
  276. } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
  277. var prev_id = 0;
  278. var set_fragment = function (name) {
  279. if (browserSupportsHistoryApi()) {
  280. history.replaceState(null, null, '#' + name);
  281. window.hashchange();
  282. } else {
  283. location.replace('#' + name);
  284. }
  285. };
  286. var cur_id = parseInt(ev.target.id, 10);
  287. if (ev.shiftKey && prev_id) {
  288. if (prev_id > cur_id) {
  289. var tmp = prev_id;
  290. prev_id = cur_id;
  291. cur_id = tmp;
  292. }
  293. set_fragment(prev_id + '-' + cur_id);
  294. } else {
  295. prev_id = cur_id;
  296. set_fragment(cur_id);
  297. }
  298. } else if (!hasClass(document.getElementById("help"), "hidden")) {
  299. addClass(document.getElementById("help"), "hidden");
  300. removeClass(document.body, "blur");
  301. }
  302. };
  303. var x = document.getElementsByClassName('version-selector');
  304. if (x.length > 0) {
  305. x[0].onchange = function() {
  306. var i, match,
  307. url = document.location.href,
  308. stripped = '',
  309. len = rootPath.match(/\.\.\//g).length + 1;
  310. for (i = 0; i < len; ++i) {
  311. match = url.match(/\/[^\/]*$/);
  312. if (i < len - 1) {
  313. stripped = match[0] + stripped;
  314. }
  315. url = url.substring(0, url.length - match[0].length);
  316. }
  317. url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
  318. document.location.href = url;
  319. };
  320. }
  321. /**
  322. * A function to compute the Levenshtein distance between two strings
  323. * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
  324. * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
  325. * This code is an unmodified version of the code written by Marco de Wit
  326. * and was found at http://stackoverflow.com/a/18514751/745719
  327. */
  328. var levenshtein_row2 = [];
  329. function levenshtein(s1, s2) {
  330. if (s1 === s2) {
  331. return 0;
  332. }
  333. var s1_len = s1.length, s2_len = s2.length;
  334. if (s1_len && s2_len) {
  335. var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
  336. while (i1 < s1_len) {
  337. row[i1] = ++i1;
  338. }
  339. while (i2 < s2_len) {
  340. c2 = s2.charCodeAt(i2);
  341. a = i2;
  342. ++i2;
  343. b = i2;
  344. for (i1 = 0; i1 < s1_len; ++i1) {
  345. c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
  346. a = row[i1];
  347. b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
  348. row[i1] = b;
  349. }
  350. }
  351. return b;
  352. }
  353. return s1_len + s2_len;
  354. }
  355. function initSearch(rawSearchIndex) {
  356. var currentResults, index, searchIndex;
  357. var MAX_LEV_DISTANCE = 3;
  358. var MAX_RESULTS = 200;
  359. var params = getQueryStringParams();
  360. // Populate search bar with query string search term when provided,
  361. // but only if the input bar is empty. This avoid the obnoxious issue
  362. // where you start trying to do a search, and the index loads, and
  363. // suddenly your search is gone!
  364. if (document.getElementsByClassName("search-input")[0].value === "") {
  365. document.getElementsByClassName("search-input")[0].value = params.search || '';
  366. }
  367. /**
  368. * Executes the query and builds an index of results
  369. * @param {[Object]} query [The user query]
  370. * @param {[type]} searchWords [The list of search words to query
  371. * against]
  372. * @return {[type]} [A search index of results]
  373. */
  374. function execQuery(query, searchWords) {
  375. function itemTypeFromName(typename) {
  376. for (var i = 0; i < itemTypes.length; ++i) {
  377. if (itemTypes[i] === typename) {
  378. return i;
  379. }
  380. }
  381. return -1;
  382. }
  383. var valLower = query.query.toLowerCase(),
  384. val = valLower,
  385. typeFilter = itemTypeFromName(query.type),
  386. results = {}, results_in_args = {}, results_returned = {},
  387. split = valLower.split("::");
  388. for (var z = 0; z < split.length; ++z) {
  389. if (split[z] === "") {
  390. split.splice(z, 1);
  391. z -= 1;
  392. }
  393. }
  394. function transformResults(results, isType) {
  395. var out = [];
  396. for (i = 0; i < results.length; ++i) {
  397. if (results[i].id > -1) {
  398. var obj = searchIndex[results[i].id];
  399. obj.lev = results[i].lev;
  400. if (isType !== true || obj.type) {
  401. out.push(obj);
  402. }
  403. }
  404. if (out.length >= MAX_RESULTS) {
  405. break;
  406. }
  407. }
  408. return out;
  409. }
  410. function sortResults(results, isType) {
  411. var ar = [];
  412. for (var entry in results) {
  413. if (results.hasOwnProperty(entry)) {
  414. ar.push(results[entry]);
  415. }
  416. }
  417. results = ar;
  418. var nresults = results.length;
  419. for (var i = 0; i < nresults; ++i) {
  420. results[i].word = searchWords[results[i].id];
  421. results[i].item = searchIndex[results[i].id] || {};
  422. }
  423. // if there are no results then return to default and fail
  424. if (results.length === 0) {
  425. return [];
  426. }
  427. results.sort(function(aaa, bbb) {
  428. var a, b;
  429. // Sort by non levenshtein results and then levenshtein results by the distance
  430. // (less changes required to match means higher rankings)
  431. a = (aaa.lev);
  432. b = (bbb.lev);
  433. if (a !== b) { return a - b; }
  434. // sort by crate (non-current crate goes later)
  435. a = (aaa.item.crate !== window.currentCrate);
  436. b = (bbb.item.crate !== window.currentCrate);
  437. if (a !== b) { return a - b; }
  438. // sort by exact match (mismatch goes later)
  439. a = (aaa.word !== valLower);
  440. b = (bbb.word !== valLower);
  441. if (a !== b) { return a - b; }
  442. // sort by item name length (longer goes later)
  443. a = aaa.word.length;
  444. b = bbb.word.length;
  445. if (a !== b) { return a - b; }
  446. // sort by item name (lexicographically larger goes later)
  447. a = aaa.word;
  448. b = bbb.word;
  449. if (a !== b) { return (a > b ? +1 : -1); }
  450. // sort by index of keyword in item name (no literal occurrence goes later)
  451. a = (aaa.index < 0);
  452. b = (bbb.index < 0);
  453. if (a !== b) { return a - b; }
  454. // (later literal occurrence, if any, goes later)
  455. a = aaa.index;
  456. b = bbb.index;
  457. if (a !== b) { return a - b; }
  458. // special precedence for primitive pages
  459. if ((aaa.item.ty === TY_PRIMITIVE) && (bbb.item.ty !== TY_PRIMITIVE)) {
  460. return -1;
  461. }
  462. if ((bbb.item.ty === TY_PRIMITIVE) && (aaa.item.ty !== TY_PRIMITIVE)) {
  463. return 1;
  464. }
  465. // sort by description (no description goes later)
  466. a = (aaa.item.desc === '');
  467. b = (bbb.item.desc === '');
  468. if (a !== b) { return a - b; }
  469. // sort by type (later occurrence in `itemTypes` goes later)
  470. a = aaa.item.ty;
  471. b = bbb.item.ty;
  472. if (a !== b) { return a - b; }
  473. // sort by path (lexicographically larger goes later)
  474. a = aaa.item.path;
  475. b = bbb.item.path;
  476. if (a !== b) { return (a > b ? +1 : -1); }
  477. // que sera, sera
  478. return 0;
  479. });
  480. for (var i = 0; i < results.length; ++i) {
  481. var result = results[i];
  482. // this validation does not make sense when searching by types
  483. if (result.dontValidate) {
  484. continue;
  485. }
  486. var name = result.item.name.toLowerCase(),
  487. path = result.item.path.toLowerCase(),
  488. parent = result.item.parent;
  489. if (isType !== true &&
  490. validateResult(name, path, split, parent) === false)
  491. {
  492. result.id = -1;
  493. }
  494. }
  495. return transformResults(results);
  496. }
  497. function extractGenerics(val) {
  498. val = val.toLowerCase();
  499. if (val.indexOf('<') !== -1) {
  500. var values = val.substring(val.indexOf('<') + 1, val.lastIndexOf('>'));
  501. return {
  502. name: val.substring(0, val.indexOf('<')),
  503. generics: values.split(/\s*,\s*/),
  504. };
  505. }
  506. return {
  507. name: val,
  508. generics: [],
  509. };
  510. }
  511. function checkGenerics(obj, val) {
  512. // The names match, but we need to be sure that all generics kinda
  513. // match as well.
  514. var lev_distance = MAX_LEV_DISTANCE + 1;
  515. if (val.generics.length > 0) {
  516. if (obj.generics && obj.generics.length >= val.generics.length) {
  517. var elems = obj.generics.slice(0);
  518. var total = 0;
  519. var done = 0;
  520. // We need to find the type that matches the most to remove it in order
  521. // to move forward.
  522. for (var y = 0; y < val.generics.length; ++y) {
  523. var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
  524. for (var x = 0; x < elems.length; ++x) {
  525. var tmp_lev = levenshtein(elems[x], val.generics[y]);
  526. if (tmp_lev < lev.lev) {
  527. lev.lev = tmp_lev;
  528. lev.pos = x;
  529. }
  530. }
  531. if (lev.pos !== -1) {
  532. elems.splice(lev.pos, 1);
  533. lev_distance = Math.min(lev.lev, lev_distance);
  534. total += lev.lev;
  535. done += 1;
  536. } else {
  537. return MAX_LEV_DISTANCE + 1;
  538. }
  539. }
  540. return lev_distance;//Math.ceil(total / done);
  541. }
  542. }
  543. return MAX_LEV_DISTANCE + 1;
  544. }
  545. // Check for type name and type generics (if any).
  546. function checkType(obj, val, literalSearch) {
  547. var lev_distance = MAX_LEV_DISTANCE + 1;
  548. if (obj.name === val.name) {
  549. if (literalSearch === true) {
  550. if (val.generics && val.generics.length !== 0) {
  551. if (obj.generics && obj.length >= val.generics.length) {
  552. var elems = obj.generics.slice(0);
  553. var allFound = true;
  554. var x;
  555. for (var y = 0; allFound === true && y < val.generics.length; ++y) {
  556. allFound = false;
  557. for (x = 0; allFound === false && x < elems.length; ++x) {
  558. allFound = elems[x] === val.generics[y];
  559. }
  560. if (allFound === true) {
  561. elems.splice(x - 1, 1);
  562. }
  563. }
  564. if (allFound === true) {
  565. return true;
  566. }
  567. } else {
  568. return false;
  569. }
  570. }
  571. return true;
  572. }
  573. // If the type has generics but don't match, then it won't return at this point.
  574. // Otherwise, `checkGenerics` will return 0 and it'll return.
  575. if (obj.generics && obj.generics.length !== 0) {
  576. var tmp_lev = checkGenerics(obj, val);
  577. if (tmp_lev <= MAX_LEV_DISTANCE) {
  578. return tmp_lev;
  579. }
  580. } else {
  581. return 0;
  582. }
  583. }
  584. // Names didn't match so let's check if one of the generic types could.
  585. if (literalSearch === true) {
  586. if (obj.generics && obj.generics.length > 0) {
  587. for (var x = 0; x < obj.generics.length; ++x) {
  588. if (obj.generics[x] === val.name) {
  589. return true;
  590. }
  591. }
  592. }
  593. return false;
  594. }
  595. var lev_distance = Math.min(levenshtein(obj.name, val.name), lev_distance);
  596. if (lev_distance <= MAX_LEV_DISTANCE) {
  597. lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
  598. } else if (obj.generics && obj.generics.length > 0) {
  599. // We can check if the type we're looking for is inside the generics!
  600. for (var x = 0; x < obj.generics.length; ++x) {
  601. lev_distance = Math.min(levenshtein(obj.generics[x], val.name),
  602. lev_distance);
  603. }
  604. }
  605. // Now whatever happens, the returned distance is "less good" so we should mark it
  606. // as such, and so we add 1 to the distance to make it "less good".
  607. return lev_distance + 1;
  608. }
  609. function findArg(obj, val, literalSearch) {
  610. var lev_distance = MAX_LEV_DISTANCE + 1;
  611. if (obj && obj.type && obj.type.inputs.length > 0) {
  612. for (var i = 0; i < obj.type.inputs.length; i++) {
  613. var tmp = checkType(obj.type.inputs[i], val, literalSearch);
  614. if (literalSearch === true && tmp === true) {
  615. return true;
  616. }
  617. lev_distance = Math.min(tmp, lev_distance);
  618. if (lev_distance === 0) {
  619. return 0;
  620. }
  621. }
  622. }
  623. return literalSearch === true ? false : lev_distance;
  624. }
  625. function checkReturned(obj, val, literalSearch) {
  626. var lev_distance = MAX_LEV_DISTANCE + 1;
  627. if (obj && obj.type && obj.type.output) {
  628. var tmp = checkType(obj.type.output, val, literalSearch);
  629. if (literalSearch === true && tmp === true) {
  630. return true;
  631. }
  632. lev_distance = Math.min(tmp, lev_distance);
  633. if (lev_distance === 0) {
  634. return 0;
  635. }
  636. }
  637. return literalSearch === true ? false : lev_distance;
  638. }
  639. function checkPath(startsWith, lastElem, ty) {
  640. if (startsWith.length === 0) {
  641. return 0;
  642. }
  643. var ret_lev = MAX_LEV_DISTANCE + 1;
  644. var path = ty.path.split("::");
  645. if (ty.parent && ty.parent.name) {
  646. path.push(ty.parent.name.toLowerCase());
  647. }
  648. if (startsWith.length > path.length) {
  649. return MAX_LEV_DISTANCE + 1;
  650. }
  651. for (var i = 0; i < path.length; ++i) {
  652. if (i + startsWith.length > path.length) {
  653. break;
  654. }
  655. var lev_total = 0;
  656. var aborted = false;
  657. for (var x = 0; x < startsWith.length; ++x) {
  658. var lev = levenshtein(path[i + x], startsWith[x]);
  659. if (lev > MAX_LEV_DISTANCE) {
  660. aborted = true;
  661. break;
  662. }
  663. lev_total += lev;
  664. }
  665. if (aborted === false) {
  666. ret_lev = Math.min(ret_lev, Math.round(lev_total / startsWith.length));
  667. }
  668. }
  669. return ret_lev;
  670. }
  671. function typePassesFilter(filter, type) {
  672. // No filter
  673. if (filter < 0) return true;
  674. // Exact match
  675. if (filter === type) return true;
  676. // Match related items
  677. var name = itemTypes[type];
  678. switch (itemTypes[filter]) {
  679. case "constant":
  680. return (name == "associatedconstant");
  681. case "fn":
  682. return (name == "method" || name == "tymethod");
  683. case "type":
  684. return (name == "primitive");
  685. }
  686. // No match
  687. return false;
  688. }
  689. function generateId(ty) {
  690. if (ty.parent && ty.parent.name) {
  691. return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
  692. }
  693. return itemTypes[ty.ty] + ty.path + ty.name;
  694. }
  695. // quoted values mean literal search
  696. var nSearchWords = searchWords.length;
  697. if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
  698. val.charAt(val.length - 1) === val.charAt(0))
  699. {
  700. val = extractGenerics(val.substr(1, val.length - 2));
  701. for (var i = 0; i < nSearchWords; ++i) {
  702. var in_args = findArg(searchIndex[i], val, true);
  703. var returned = checkReturned(searchIndex[i], val, true);
  704. var ty = searchIndex[i];
  705. var fullId = generateId(ty);
  706. if (searchWords[i] === val.name) {
  707. // filter type: ... queries
  708. if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
  709. results[fullId] === undefined)
  710. {
  711. results[fullId] = {id: i, index: -1};
  712. }
  713. } else if ((in_args === true || returned === true) &&
  714. typePassesFilter(typeFilter, searchIndex[i].ty)) {
  715. if (in_args === true || returned === true) {
  716. if (in_args === true) {
  717. results_in_args[fullId] = {
  718. id: i,
  719. index: -1,
  720. dontValidate: true,
  721. };
  722. }
  723. if (returned === true) {
  724. results_returned[fullId] = {
  725. id: i,
  726. index: -1,
  727. dontValidate: true,
  728. };
  729. }
  730. } else {
  731. results[fullId] = {
  732. id: i,
  733. index: -1,
  734. dontValidate: true,
  735. };
  736. }
  737. }
  738. }
  739. query.inputs = [val];
  740. query.output = val;
  741. query.search = val;
  742. // searching by type
  743. } else if (val.search("->") > -1) {
  744. var trimmer = function (s) { return s.trim(); };
  745. var parts = val.split("->").map(trimmer);
  746. var input = parts[0];
  747. // sort inputs so that order does not matter
  748. var inputs = input.split(",").map(trimmer).sort();
  749. for (var i = 0; i < inputs.length; ++i) {
  750. inputs[i] = extractGenerics(inputs[i]);
  751. }
  752. var output = extractGenerics(parts[1]);
  753. for (var i = 0; i < nSearchWords; ++i) {
  754. var type = searchIndex[i].type;
  755. var ty = searchIndex[i];
  756. if (!type) {
  757. continue;
  758. }
  759. var fullId = generateId(ty);
  760. // allow searching for void (no output) functions as well
  761. var typeOutput = type.output ? type.output.name : "";
  762. var returned = checkReturned(ty, output, true);
  763. if (output.name === "*" || returned === true) {
  764. var in_args = false;
  765. var module = false;
  766. if (input === "*") {
  767. module = true;
  768. } else {
  769. var allFound = true;
  770. for (var it = 0; allFound === true && it < inputs.length; it++) {
  771. allFound = checkType(type, inputs[it], true);
  772. }
  773. in_args = allFound;
  774. }
  775. if (in_args === true) {
  776. results_in_args[fullId] = {
  777. id: i,
  778. index: -1,
  779. dontValidate: true,
  780. };
  781. }
  782. if (returned === true) {
  783. results_returned[fullId] = {
  784. id: i,
  785. index: -1,
  786. dontValidate: true,
  787. };
  788. }
  789. if (module === true) {
  790. results[fullId] = {
  791. id: i,
  792. index: -1,
  793. dontValidate: true,
  794. };
  795. }
  796. }
  797. }
  798. query.inputs = inputs.map(function(input) {
  799. return input.name;
  800. });
  801. query.output = output.name;
  802. } else {
  803. query.inputs = [val];
  804. query.output = val;
  805. query.search = val;
  806. // gather matching search results up to a certain maximum
  807. val = val.replace(/\_/g, "");
  808. var valGenerics = extractGenerics(val);
  809. var paths = valLower.split("::");
  810. var j;
  811. for (j = 0; j < paths.length; ++j) {
  812. if (paths[j] === "") {
  813. paths.splice(j, 1);
  814. j -= 1;
  815. }
  816. }
  817. val = paths[paths.length - 1];
  818. var startsWith = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
  819. for (j = 0; j < nSearchWords; ++j) {
  820. var lev_distance;
  821. var ty = searchIndex[j];
  822. if (!ty) {
  823. continue;
  824. }
  825. var lev_add = 0;
  826. if (paths.length > 1) {
  827. var lev = checkPath(startsWith, paths[paths.length - 1], ty);
  828. if (lev > MAX_LEV_DISTANCE) {
  829. continue;
  830. } else if (lev > 0) {
  831. lev_add = 1;
  832. }
  833. }
  834. var returned = MAX_LEV_DISTANCE + 1;
  835. var in_args = MAX_LEV_DISTANCE + 1;
  836. var index = -1;
  837. // we want lev results to go lower than others
  838. var lev = MAX_LEV_DISTANCE + 1;
  839. var fullId = generateId(ty);
  840. if (searchWords[j].indexOf(split[i]) > -1 ||
  841. searchWords[j].indexOf(val) > -1 ||
  842. searchWords[j].replace(/_/g, "").indexOf(val) > -1)
  843. {
  844. // filter type: ... queries
  845. if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
  846. index = searchWords[j].replace(/_/g, "").indexOf(val);
  847. }
  848. }
  849. if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
  850. if (typePassesFilter(typeFilter, ty.ty) === false) {
  851. lev = MAX_LEV_DISTANCE + 1;
  852. } else {
  853. lev += 1;
  854. }
  855. }
  856. if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
  857. if (typePassesFilter(typeFilter, ty.ty) === false) {
  858. in_args = MAX_LEV_DISTANCE + 1;
  859. }
  860. }
  861. if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
  862. if (typePassesFilter(typeFilter, ty.ty) === false) {
  863. returned = MAX_LEV_DISTANCE + 1;
  864. }
  865. }
  866. lev += lev_add;
  867. if (lev > 0 && val.length > 3 && searchWords[j].startsWith(val)) {
  868. if (val.length < 6) {
  869. lev -= 1;
  870. } else {
  871. lev = 0;
  872. }
  873. }
  874. if (in_args <= MAX_LEV_DISTANCE) {
  875. if (results_in_args[fullId] === undefined) {
  876. results_in_args[fullId] = {
  877. id: j,
  878. index: index,
  879. lev: in_args,
  880. };
  881. }
  882. results_in_args[fullId].lev =
  883. Math.min(results_in_args[fullId].lev, in_args);
  884. }
  885. if (returned <= MAX_LEV_DISTANCE) {
  886. if (results_returned[fullId] === undefined) {
  887. results_returned[fullId] = {
  888. id: j,
  889. index: index,
  890. lev: returned,
  891. };
  892. }
  893. results_returned[fullId].lev =
  894. Math.min(results_returned[fullId].lev, returned);
  895. }
  896. if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
  897. if (index !== -1) {
  898. lev = 0;
  899. }
  900. if (results[fullId] === undefined) {
  901. results[fullId] = {
  902. id: j,
  903. index: index,
  904. lev: lev,
  905. };
  906. }
  907. results[fullId].lev = Math.min(results[fullId].lev, lev);
  908. }
  909. }
  910. }
  911. return {
  912. 'in_args': sortResults(results_in_args, true),
  913. 'returned': sortResults(results_returned, true),
  914. 'others': sortResults(results),
  915. };
  916. }
  917. /**
  918. * Validate performs the following boolean logic. For example:
  919. * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
  920. * exists in (name || path || parent) OR => ("file" && "open") exists in
  921. * (name || path )
  922. *
  923. * This could be written functionally, but I wanted to minimise
  924. * functions on stack.
  925. *
  926. * @param {[string]} name [The name of the result]
  927. * @param {[string]} path [The path of the result]
  928. * @param {[string]} keys [The keys to be used (["file", "open"])]
  929. * @param {[object]} parent [The parent of the result]
  930. * @return {[boolean]} [Whether the result is valid or not]
  931. */
  932. function validateResult(name, path, keys, parent) {
  933. for (var i = 0; i < keys.length; ++i) {
  934. // each check is for validation so we negate the conditions and invalidate
  935. if (!(
  936. // check for an exact name match
  937. name.indexOf(keys[i]) > -1 ||
  938. // then an exact path match
  939. path.indexOf(keys[i]) > -1 ||
  940. // next if there is a parent, check for exact parent match
  941. (parent !== undefined &&
  942. parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
  943. // lastly check to see if the name was a levenshtein match
  944. levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
  945. return false;
  946. }
  947. }
  948. return true;
  949. }
  950. function getQuery(raw) {
  951. var matches, type, query;
  952. query = raw;
  953. matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
  954. if (matches) {
  955. type = matches[1].replace(/^const$/, 'constant');
  956. query = query.substring(matches[0].length);
  957. }
  958. return {
  959. raw: raw,
  960. query: query,
  961. type: type,
  962. id: query + type
  963. };
  964. }
  965. function initSearchNav() {
  966. var hoverTimeout;
  967. var click_func = function(e) {
  968. var el = e.target;
  969. // to retrieve the real "owner" of the event.
  970. while (el.tagName !== 'TR') {
  971. el = el.parentNode;
  972. }
  973. var dst = e.target.getElementsByTagName('a');
  974. if (dst.length < 1) {
  975. return;
  976. }
  977. dst = dst[0];
  978. if (window.location.pathname === dst.pathname) {
  979. addClass(document.getElementById('search'), 'hidden');
  980. removeClass(document.getElementById('main'), 'hidden');
  981. document.location.href = dst.href;
  982. }
  983. };
  984. var mouseover_func = function(e) {
  985. var el = e.target;
  986. // to retrieve the real "owner" of the event.
  987. while (el.tagName !== 'TR') {
  988. el = el.parentNode;
  989. }
  990. clearTimeout(hoverTimeout);
  991. hoverTimeout = setTimeout(function() {
  992. onEach(document.getElementsByClassName('search-results'), function(e) {
  993. onEach(e.getElementsByClassName('result'), function(i_e) {
  994. removeClass(i_e, 'highlighted');
  995. });
  996. });
  997. addClass(el, 'highlighted');
  998. }, 20);
  999. };
  1000. onEach(document.getElementsByClassName('search-results'), function(e) {
  1001. onEach(e.getElementsByClassName('result'), function(i_e) {
  1002. i_e.onclick = click_func;
  1003. i_e.onmouseover = mouseover_func;
  1004. });
  1005. });
  1006. var search_input = document.getElementsByClassName('search-input')[0];
  1007. search_input.onkeydown = function(e) {
  1008. // "actives" references the currently highlighted item in each search tab.
  1009. // Each array in "actives" represents a tab.
  1010. var actives = [[], [], []];
  1011. // "current" is used to know which tab we're looking into.
  1012. var current = 0;
  1013. onEach(document.getElementsByClassName('search-results'), function(e) {
  1014. onEach(e.getElementsByClassName('highlighted'), function(e) {
  1015. actives[current].push(e);
  1016. });
  1017. current += 1;
  1018. });
  1019. if (e.which === 38) { // up
  1020. if (!actives[currentTab].length ||
  1021. !actives[currentTab][0].previousElementSibling) {
  1022. return;
  1023. }
  1024. addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
  1025. removeClass(actives[currentTab][0], 'highlighted');
  1026. } else if (e.which === 40) { // down
  1027. if (!actives[currentTab].length) {
  1028. var results = document.getElementsByClassName('search-results');
  1029. if (results.length > 0) {
  1030. var res = results[currentTab].getElementsByClassName('result');
  1031. if (res.length > 0) {
  1032. addClass(res[0], 'highlighted');
  1033. }
  1034. }
  1035. } else if (actives[currentTab][0].nextElementSibling) {
  1036. addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
  1037. removeClass(actives[currentTab][0], 'highlighted');
  1038. }
  1039. } else if (e.which === 13) { // return
  1040. if (actives[currentTab].length) {
  1041. document.location.href =
  1042. actives[currentTab][0].getElementsByTagName('a')[0].href;
  1043. }
  1044. } else if (e.which === 9) { // tab
  1045. if (e.shiftKey) {
  1046. printTab(currentTab > 0 ? currentTab - 1 : 2);
  1047. } else {
  1048. printTab(currentTab > 1 ? 0 : currentTab + 1);
  1049. }
  1050. e.preventDefault();
  1051. } else if (e.which === 16) { // shift
  1052. // Does nothing, it's just to avoid losing "focus" on the highlighted element.
  1053. } else if (e.which === 27) { // escape
  1054. removeClass(actives[currentTab][0], 'highlighted');
  1055. document.getElementsByClassName('search-input')[0].value = '';
  1056. defocusSearchBar();
  1057. } else if (actives[currentTab].length > 0) {
  1058. removeClass(actives[currentTab][0], 'highlighted');
  1059. }
  1060. };
  1061. }
  1062. function escape(content) {
  1063. var h1 = document.createElement('h1');
  1064. h1.textContent = content;
  1065. return h1.innerHTML;
  1066. }
  1067. function addTab(array, query, display) {
  1068. var extraStyle = '';
  1069. if (display === false) {
  1070. extraStyle = ' style="display: none;"';
  1071. }
  1072. var output = '';
  1073. if (array.length > 0) {
  1074. output = '<table class="search-results"' + extraStyle + '>';
  1075. var shown = [];
  1076. array.forEach(function(item) {
  1077. var name, type, href, displayPath;
  1078. if (shown.indexOf(item) !== -1) {
  1079. return;
  1080. }
  1081. shown.push(item);
  1082. name = item.name;
  1083. type = itemTypes[item.ty];
  1084. if (type === 'mod') {
  1085. displayPath = item.path + '::';
  1086. href = rootPath + item.path.replace(/::/g, '/') + '/' +
  1087. name + '/index.html';
  1088. } else if (type === "primitive") {
  1089. displayPath = "";
  1090. href = rootPath + item.path.replace(/::/g, '/') +
  1091. '/' + type + '.' + name + '.html';
  1092. } else if (type === "externcrate") {
  1093. displayPath = "";
  1094. href = rootPath + name + '/index.html';
  1095. } else if (item.parent !== undefined) {
  1096. var myparent = item.parent;
  1097. var anchor = '#' + type + '.' + name;
  1098. var parentType = itemTypes[myparent.ty];
  1099. if (parentType === "primitive") {
  1100. displayPath = myparent.name + '::';
  1101. } else {
  1102. displayPath = item.path + '::' + myparent.name + '::';
  1103. }
  1104. href = rootPath + item.path.replace(/::/g, '/') +
  1105. '/' + parentType +
  1106. '.' + myparent.name +
  1107. '.html' + anchor;
  1108. } else {
  1109. displayPath = item.path + '::';
  1110. href = rootPath + item.path.replace(/::/g, '/') +
  1111. '/' + type + '.' + name + '.html';
  1112. }
  1113. output += '<tr class="' + type + ' result"><td>' +
  1114. '<a href="' + href + '">' +
  1115. displayPath + '<span class="' + type + '">' +
  1116. name + '</span></a></td><td>' +
  1117. '<a href="' + href + '">' +
  1118. '<span class="desc">' + escape(item.desc) +
  1119. '&nbsp;</span></a></td></tr>';
  1120. });
  1121. output += '</table>';
  1122. } else {
  1123. output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
  1124. 'Try on <a href="https://duckduckgo.com/?q=' +
  1125. encodeURIComponent('rust ' + query.query) +
  1126. '">DuckDuckGo</a>?</div>';
  1127. }
  1128. return output;
  1129. }
  1130. function makeTabHeader(tabNb, text, nbElems) {
  1131. if (currentTab === tabNb) {
  1132. return '<div class="selected">' + text +
  1133. ' <div class="count">(' + nbElems + ')</div></div>';
  1134. }
  1135. return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
  1136. }
  1137. function showResults(results) {
  1138. var output, query = getQuery(document.getElementsByClassName('search-input')[0].value);
  1139. currentResults = query.id;
  1140. output = '<h1>Results for ' + escape(query.query) +
  1141. (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>' +
  1142. '<div id="titles">' +
  1143. makeTabHeader(0, "In Names", results['others'].length) +
  1144. makeTabHeader(1, "In Parameters", results['in_args'].length) +
  1145. makeTabHeader(2, "In Return Types", results['returned'].length) +
  1146. '</div><div id="results">';
  1147. output += addTab(results['others'], query);
  1148. output += addTab(results['in_args'], query, false);
  1149. output += addTab(results['returned'], query, false);
  1150. output += '</div>';
  1151. addClass(document.getElementById('main'), 'hidden');
  1152. var search = document.getElementById('search');
  1153. removeClass(search, 'hidden');
  1154. search.innerHTML = output;
  1155. var tds = search.getElementsByTagName('td');
  1156. var td_width = 0;
  1157. if (tds.length > 0) {
  1158. td_width = tds[0].offsetWidth;
  1159. }
  1160. var width = search.offsetWidth - 40 - td_width;
  1161. onEach(search.getElementsByClassName('desc'), function(e) {
  1162. e.style.width = width + 'px';
  1163. });
  1164. initSearchNav();
  1165. var elems = document.getElementById('titles').childNodes;
  1166. elems[0].onclick = function() { printTab(0); };
  1167. elems[1].onclick = function() { printTab(1); };
  1168. elems[2].onclick = function() { printTab(2); };
  1169. printTab(currentTab);
  1170. }
  1171. function search(e) {
  1172. var query,
  1173. obj, i, len,
  1174. results = {"in_args": [], "returned": [], "others": []},
  1175. resultIndex;
  1176. var params = getQueryStringParams();
  1177. query = getQuery(document.getElementsByClassName('search-input')[0].value);
  1178. if (e) {
  1179. e.preventDefault();
  1180. }
  1181. if (!query.query || query.id === currentResults) {
  1182. return;
  1183. }
  1184. // Update document title to maintain a meaningful browser history
  1185. document.title = "Results for " + query.query + " - Rust";
  1186. // Because searching is incremental by character, only the most
  1187. // recent search query is added to the browser history.
  1188. if (browserSupportsHistoryApi()) {
  1189. if (!history.state && !params.search) {
  1190. history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
  1191. } else {
  1192. history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
  1193. }
  1194. }
  1195. results = execQuery(query, index);
  1196. showResults(results);
  1197. }
  1198. function buildIndex(rawSearchIndex) {
  1199. searchIndex = [];
  1200. var searchWords = [];
  1201. for (var crate in rawSearchIndex) {
  1202. if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
  1203. searchWords.push(crate);
  1204. searchIndex.push({
  1205. crate: crate,
  1206. ty: 1, // == ExternCrate
  1207. name: crate,
  1208. path: "",
  1209. desc: rawSearchIndex[crate].doc,
  1210. type: null,
  1211. });
  1212. // an array of [(Number) item type,
  1213. // (String) name,
  1214. // (String) full path or empty string for previous path,
  1215. // (String) description,
  1216. // (Number | null) the parent path index to `paths`]
  1217. // (Object | null) the type of the function (if any)
  1218. var items = rawSearchIndex[crate].items;
  1219. // an array of [(Number) item type,
  1220. // (String) name]
  1221. var paths = rawSearchIndex[crate].paths;
  1222. // convert `paths` into an object form
  1223. var len = paths.length;
  1224. for (var i = 0; i < len; ++i) {
  1225. paths[i] = {ty: paths[i][0], name: paths[i][1]};
  1226. }
  1227. // convert `items` into an object form, and construct word indices.
  1228. //
  1229. // before any analysis is performed lets gather the search terms to
  1230. // search against apart from the rest of the data. This is a quick
  1231. // operation that is cached for the life of the page state so that
  1232. // all other search operations have access to this cached data for
  1233. // faster analysis operations
  1234. var len = items.length;
  1235. var lastPath = "";
  1236. for (var i = 0; i < len; ++i) {
  1237. var rawRow = items[i];
  1238. var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
  1239. path: rawRow[2] || lastPath, desc: rawRow[3],
  1240. parent: paths[rawRow[4]], type: rawRow[5]};
  1241. searchIndex.push(row);
  1242. if (typeof row.name === "string") {
  1243. var word = row.name.toLowerCase();
  1244. searchWords.push(word);
  1245. } else {
  1246. searchWords.push("");
  1247. }
  1248. lastPath = row.path;
  1249. }
  1250. }
  1251. return searchWords;
  1252. }
  1253. function startSearch() {
  1254. var searchTimeout;
  1255. var callback = function() {
  1256. var search_input = document.getElementsByClassName('search-input');
  1257. if (search_input.length < 1) { return; }
  1258. search_input = search_input[0];
  1259. clearTimeout(searchTimeout);
  1260. if (search_input.value.length === 0) {
  1261. if (browserSupportsHistoryApi()) {
  1262. history.replaceState("", "std - Rust", "?search=");
  1263. }
  1264. var main = document.getElementById('main');
  1265. if (hasClass(main, 'content')) {
  1266. removeClass(main, 'hidden');
  1267. }
  1268. var search_c = document.getElementById('search');
  1269. if (hasClass(search_c, 'content')) {
  1270. addClass(search_c, 'hidden');
  1271. }
  1272. } else {
  1273. searchTimeout = setTimeout(search, 500);
  1274. }
  1275. };
  1276. var search_input = document.getElementsByClassName("search-input")[0];
  1277. search_input.onkeyup = callback;
  1278. search_input.oninput = callback;
  1279. document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
  1280. e.preventDefault();
  1281. clearTimeout(searchTimeout);
  1282. search();
  1283. };
  1284. search_input.onchange = function(e) {
  1285. // Do NOT e.preventDefault() here. It will prevent pasting.
  1286. clearTimeout(searchTimeout);
  1287. // zero-timeout necessary here because at the time of event handler execution the
  1288. // pasted content is not in the input field yet. Shouldn’t make any difference for
  1289. // change, though.
  1290. setTimeout(search, 0);
  1291. };
  1292. search_input.onpaste = search_input.onchange;
  1293. // Push and pop states are used to add search results to the browser
  1294. // history.
  1295. if (browserSupportsHistoryApi()) {
  1296. // Store the previous <title> so we can revert back to it later.
  1297. var previousTitle = document.title;
  1298. window.onpopstate = function(e) {
  1299. var params = getQueryStringParams();
  1300. // When browsing back from search results the main page
  1301. // visibility must be reset.
  1302. if (!params.search) {
  1303. var main = document.getElementById('main');
  1304. if (hasClass(main, 'content')) {
  1305. removeClass(main, 'hidden');
  1306. }
  1307. var search_c = document.getElementById('search');
  1308. if (hasClass(search_c, 'content')) {
  1309. addClass(search_c, 'hidden');
  1310. }
  1311. }
  1312. // Revert to the previous title manually since the History
  1313. // API ignores the title parameter.
  1314. document.title = previousTitle;
  1315. // When browsing forward to search results the previous
  1316. // search will be repeated, so the currentResults are
  1317. // cleared to ensure the search is successful.
  1318. currentResults = null;
  1319. // Synchronize search bar with query string state and
  1320. // perform the search. This will empty the bar if there's
  1321. // nothing there, which lets you really go back to a
  1322. // previous state with nothing in the bar.
  1323. if (params.search) {
  1324. document.getElementsByClassName('search-input')[0].value = params.search;
  1325. } else {
  1326. document.getElementsByClassName('search-input')[0].value = '';
  1327. }
  1328. // Some browsers fire 'onpopstate' for every page load
  1329. // (Chrome), while others fire the event only when actually
  1330. // popping a state (Firefox), which is why search() is
  1331. // called both here and at the end of the startSearch()
  1332. // function.
  1333. search();
  1334. };
  1335. }
  1336. search();
  1337. }
  1338. index = buildIndex(rawSearchIndex);
  1339. startSearch();
  1340. // Draw a convenient sidebar of known crates if we have a listing
  1341. if (rootPath === '../') {
  1342. var sidebar = document.getElementsByClassName('sidebar-elems')[0];
  1343. var div = document.createElement('div');
  1344. div.className = 'block crate';
  1345. div.innerHTML = '<h3>Crates</h3>';
  1346. var ul = document.createElement('ul');
  1347. div.appendChild(ul);
  1348. var crates = [];
  1349. for (var crate in rawSearchIndex) {
  1350. if (!rawSearchIndex.hasOwnProperty(crate)) {
  1351. continue;
  1352. }
  1353. crates.push(crate);
  1354. }
  1355. crates.sort();
  1356. for (var i = 0; i < crates.length; ++i) {
  1357. var klass = 'crate';
  1358. if (crates[i] === window.currentCrate) {
  1359. klass += ' current';
  1360. }
  1361. var link = document.createElement('a');
  1362. link.href = '../' + crates[i] + '/index.html';
  1363. link.title = rawSearchIndex[crates[i]].doc;
  1364. link.className = klass;
  1365. link.textContent = crates[i];
  1366. var li = document.createElement('li');
  1367. li.appendChild(link);
  1368. ul.appendChild(li);
  1369. }
  1370. sidebar.appendChild(div);
  1371. }
  1372. }
  1373. window.initSearch = initSearch;
  1374. // delayed sidebar rendering.
  1375. function initSidebarItems(items) {
  1376. var sidebar = document.getElementsByClassName('sidebar-elems')[0];
  1377. var current = window.sidebarCurrent;
  1378. function block(shortty, longty) {
  1379. var filtered = items[shortty];
  1380. if (!filtered) { return; }
  1381. var div = document.createElement('div');
  1382. div.className = 'block ' + shortty;
  1383. var h3 = document.createElement('h3');
  1384. h3.textContent = longty;
  1385. div.appendChild(h3);
  1386. var ul = document.createElement('ul');
  1387. for (var i = 0; i < filtered.length; ++i) {
  1388. var item = filtered[i];
  1389. var name = item[0];
  1390. var desc = item[1]; // can be null
  1391. var klass = shortty;
  1392. if (name === current.name && shortty === current.ty) {
  1393. klass += ' current';
  1394. }
  1395. var path;
  1396. if (shortty === 'mod') {
  1397. path = name + '/index.html';
  1398. } else {
  1399. path = shortty + '.' + name + '.html';
  1400. }
  1401. var link = document.createElement('a');
  1402. link.href = current.relpath + path;
  1403. link.title = desc;
  1404. link.className = klass;
  1405. link.textContent = name;
  1406. var li = document.createElement('li');
  1407. li.appendChild(link);
  1408. ul.appendChild(li);
  1409. }
  1410. div.appendChild(ul);
  1411. if (sidebar) {
  1412. sidebar.appendChild(div);
  1413. }
  1414. }
  1415. block("primitive", "Primitive Types");
  1416. block("mod", "Modules");
  1417. block("macro", "Macros");
  1418. block("struct", "Structs");
  1419. block("enum", "Enums");
  1420. block("union", "Unions");
  1421. block("constant", "Constants");
  1422. block("static", "Statics");
  1423. block("trait", "Traits");
  1424. block("fn", "Functions");
  1425. block("type", "Type Definitions");
  1426. block("foreigntype", "Foreign Types");
  1427. }
  1428. window.initSidebarItems = initSidebarItems;
  1429. window.register_implementors = function(imp) {
  1430. var list = document.getElementById('implementors-list');
  1431. var libs = Object.getOwnPropertyNames(imp);
  1432. for (var i = 0; i < libs.length; ++i) {
  1433. if (libs[i] === currentCrate) { continue; }
  1434. var structs = imp[libs[i]];
  1435. for (var j = 0; j < structs.length; ++j) {
  1436. var code = document.createElement('code');
  1437. code.innerHTML = structs[j];
  1438. var x = code.getElementsByTagName('a');
  1439. for (var k = 0; k < x.length; k++) {
  1440. var href = x[k].getAttribute('href');
  1441. if (href && href.indexOf('http') !== 0) {
  1442. x[k].setAttribute('href', rootPath + href);
  1443. }
  1444. }
  1445. var li = document.createElement('li');
  1446. li.appendChild(code);
  1447. list.appendChild(li);
  1448. }
  1449. }
  1450. };
  1451. if (window.pending_implementors) {
  1452. window.register_implementors(window.pending_implementors);
  1453. }
  1454. function labelForToggleButton(sectionIsCollapsed) {
  1455. if (sectionIsCollapsed) {
  1456. // button will expand the section
  1457. return "+";
  1458. }
  1459. // button will collapse the section
  1460. // note that this text is also set in the HTML template in render.rs
  1461. return "\u2212"; // "\u2212" is '−' minus sign
  1462. }
  1463. function onEveryMatchingChild(elem, className, func) {
  1464. if (elem && className && func) {
  1465. for (var i = 0; i < elem.childNodes.length; i++) {
  1466. if (hasClass(elem.childNodes[i], className)) {
  1467. func(elem.childNodes[i]);
  1468. } else {
  1469. onEveryMatchingChild(elem.childNodes[i], className, func);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. function toggleAllDocs() {
  1475. var toggle = document.getElementById("toggle-all-docs");
  1476. if (hasClass(toggle, "will-expand")) {
  1477. removeClass(toggle, "will-expand");
  1478. onEveryMatchingChild(toggle, "inner", function(e) {
  1479. e.innerHTML = labelForToggleButton(false);
  1480. });
  1481. toggle.title = "collapse all docs";
  1482. onEach(document.getElementsByClassName("docblock"), function(e) {
  1483. e.style.display = 'block';
  1484. });
  1485. onEach(document.getElementsByClassName("toggle-label"), function(e) {
  1486. e.style.display = 'none';
  1487. });
  1488. onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
  1489. removeClass(e, "collapsed");
  1490. });
  1491. onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
  1492. onEveryMatchingChild(e, "inner", function(i_e) {
  1493. i_e.innerHTML = labelForToggleButton(false);
  1494. });
  1495. });
  1496. } else {
  1497. addClass(toggle, "will-expand");
  1498. onEveryMatchingChild(toggle, "inner", function(e) {
  1499. e.innerHTML = labelForToggleButton(true);
  1500. });
  1501. toggle.title = "expand all docs";
  1502. onEach(document.getElementsByClassName("docblock"), function(e) {
  1503. e.style.display = 'none';
  1504. });
  1505. onEach(document.getElementsByClassName("toggle-label"), function(e) {
  1506. e.style.display = 'inline-block';
  1507. });
  1508. onEach(document.getElementsByClassName("toggle-wrapper"), function(e) {
  1509. addClass(e, "collapsed");
  1510. });
  1511. onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
  1512. onEveryMatchingChild(e, "inner", function(i_e) {
  1513. i_e.innerHTML = labelForToggleButton(true);
  1514. });
  1515. });
  1516. }
  1517. }
  1518. function collapseDocs(toggle) {
  1519. if (!toggle || !toggle.parentNode) {
  1520. return;
  1521. }
  1522. var relatedDoc = toggle.parentNode.nextElementSibling;
  1523. if (hasClass(relatedDoc, "stability")) {
  1524. relatedDoc = relatedDoc.nextElementSibling;
  1525. }
  1526. if (hasClass(relatedDoc, "docblock")) {
  1527. if (!isHidden(relatedDoc)) {
  1528. relatedDoc.style.display = 'none';
  1529. onEach(toggle.childNodes, function(e) {
  1530. if (hasClass(e, 'toggle-label')) {
  1531. e.style.display = 'inline-block';
  1532. }
  1533. if (hasClass(e, 'inner')) {
  1534. e.innerHTML = labelForToggleButton(true);
  1535. }
  1536. });
  1537. addClass(toggle.parentNode, 'collapsed');
  1538. } else {
  1539. relatedDoc.style.display = 'block';
  1540. removeClass(toggle.parentNode, 'collapsed');
  1541. onEach(toggle.childNodes, function(e) {
  1542. if (hasClass(e, 'toggle-label')) {
  1543. e.style.display = 'none';
  1544. }
  1545. if (hasClass(e, 'inner')) {
  1546. e.innerHTML = labelForToggleButton(false);
  1547. }
  1548. });
  1549. }
  1550. }
  1551. }
  1552. var x = document.getElementById('toggle-all-docs');
  1553. if (x) {
  1554. x.onclick = toggleAllDocs;
  1555. }
  1556. function insertAfter(newNode, referenceNode) {
  1557. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  1558. }
  1559. var toggle = document.createElement('a');
  1560. toggle.href = 'javascript:void(0)';
  1561. toggle.className = 'collapse-toggle';
  1562. toggle.innerHTML = "[<span class='inner'>"+labelForToggleButton(false)+"</span>]";
  1563. var func = function(e) {
  1564. var next = e.nextElementSibling;
  1565. if (!next) {
  1566. return;
  1567. }
  1568. if (hasClass(next, 'docblock') ||
  1569. (hasClass(next, 'stability') &&
  1570. hasClass(next.nextElementSibling, 'docblock'))) {
  1571. insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
  1572. }
  1573. }
  1574. onEach(document.getElementsByClassName('method'), func);
  1575. onEach(document.getElementsByClassName('impl-items'), function(e) {
  1576. onEach(e.getElementsByClassName('associatedconstant'), func);
  1577. });
  1578. function createToggle() {
  1579. var span = document.createElement('span');
  1580. span.className = 'toggle-label';
  1581. span.style.display = 'none';
  1582. span.innerHTML = '&nbsp;Expand&nbsp;description';
  1583. var mainToggle = toggle.cloneNode(true);
  1584. mainToggle.appendChild(span);
  1585. var wrapper = document.createElement('div');
  1586. wrapper.className = 'toggle-wrapper';
  1587. wrapper.appendChild(mainToggle);
  1588. return wrapper;
  1589. }
  1590. onEach(document.getElementById('main').getElementsByClassName('docblock'), function(e) {
  1591. if (e.parentNode.id === "main") {
  1592. e.parentNode.insertBefore(createToggle(), e);
  1593. }
  1594. });
  1595. onEach(document.getElementsByClassName('docblock'), function(e) {
  1596. if (hasClass(e, 'autohide')) {
  1597. var wrap = e.previousElementSibling;
  1598. if (wrap && hasClass(wrap, 'toggle-wrapper')) {
  1599. var toggle = wrap.childNodes[0];
  1600. if (e.childNodes[0].tagName === 'H3') {
  1601. onEach(toggle.getElementsByClassName('toggle-label'), function(i_e) {
  1602. i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
  1603. });
  1604. }
  1605. e.style.display = 'none';
  1606. addClass(wrap, 'collapsed');
  1607. onEach(toggle.getElementsByClassName('inner'), function(e) {
  1608. e.innerHTML = labelForToggleButton(true);
  1609. });
  1610. onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
  1611. e.style.display = 'inline-block';
  1612. });
  1613. }
  1614. }
  1615. })
  1616. function createToggleWrapper() {
  1617. var span = document.createElement('span');
  1618. span.className = 'toggle-label';
  1619. span.style.display = 'none';
  1620. span.innerHTML = '&nbsp;Expand&nbsp;attributes';
  1621. toggle.appendChild(span);
  1622. var wrapper = document.createElement('div');
  1623. wrapper.className = 'toggle-wrapper toggle-attributes';
  1624. wrapper.appendChild(toggle);
  1625. return wrapper;
  1626. }
  1627. // In the search display, allows to switch between tabs.
  1628. function printTab(nb) {
  1629. if (nb === 0 || nb === 1 || nb === 2) {
  1630. currentTab = nb;
  1631. }
  1632. var nb_copy = nb;
  1633. onEach(document.getElementById('titles').childNodes, function(elem) {
  1634. if (nb_copy === 0) {
  1635. addClass(elem, 'selected');
  1636. } else {
  1637. removeClass(elem, 'selected');
  1638. }
  1639. nb_copy -= 1;
  1640. });
  1641. onEach(document.getElementById('results').childNodes, function(elem) {
  1642. if (nb === 0) {
  1643. elem.style.display = '';
  1644. } else {
  1645. elem.style.display = 'none';
  1646. }
  1647. nb -= 1;
  1648. });
  1649. }
  1650. onEach(document.getElementById('main').getElementsByTagName('pre'), function(e) {
  1651. onEach(e.getElementsByClassName('attributes'), function(i_e) {
  1652. i_e.parentNode.insertBefore(createToggleWrapper(), i_e);
  1653. collapseDocs(i_e.previousSibling.childNodes[0]);
  1654. });
  1655. });
  1656. onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
  1657. if (hasClass(e, 'compile_fail')) {
  1658. e.addEventListener("mouseover", function(event) {
  1659. e.previousElementSibling.childNodes[0].style.color = '#f00';
  1660. });
  1661. e.addEventListener("mouseout", function(event) {
  1662. e.previousElementSibling.childNodes[0].style.color = '';
  1663. });
  1664. } else if (hasClass(e, 'ignore')) {
  1665. e.addEventListener("mouseover", function(event) {
  1666. e.previousElementSibling.childNodes[0].style.color = '#ff9200';
  1667. });
  1668. e.addEventListener("mouseout", function(event) {
  1669. e.previousElementSibling.childNodes[0].style.color = '';
  1670. });
  1671. }
  1672. });
  1673. function showModal(content) {
  1674. var modal = document.createElement('div');
  1675. modal.id = "important";
  1676. addClass(modal, 'modal');
  1677. modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
  1678. '<div class="whiter"></div><span class="docblock">' + content +
  1679. '</span></div>';
  1680. document.getElementsByTagName('body')[0].appendChild(modal);
  1681. document.getElementById('modal-close').onclick = hideModal;
  1682. modal.onclick = hideModal;
  1683. }
  1684. function hideModal() {
  1685. var modal = document.getElementById("important");
  1686. if (modal) {
  1687. modal.parentNode.removeChild(modal);
  1688. }
  1689. }
  1690. onEach(document.getElementsByClassName('important-traits'), function(e) {
  1691. e.onclick = function() {
  1692. showModal(e.lastElementChild.innerHTML);
  1693. };
  1694. });
  1695. var search_input = document.getElementsByClassName("search-input")[0];
  1696. if (search_input) {
  1697. search_input.onfocus = function() {
  1698. if (search_input.value !== "") {
  1699. addClass(document.getElementById("main"), "hidden");
  1700. removeClass(document.getElementById("search"), "hidden");
  1701. if (browserSupportsHistoryApi()) {
  1702. history.replaceState(search_input.value,
  1703. "",
  1704. "?search=" + encodeURIComponent(search_input.value));
  1705. }
  1706. }
  1707. };
  1708. }
  1709. var params = getQueryStringParams();
  1710. if (params && params.search) {
  1711. addClass(document.getElementById("main"), "hidden");
  1712. var search = document.getElementById("search");
  1713. removeClass(search, "hidden");
  1714. search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
  1715. }
  1716. var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
  1717. if (sidebar_menu) {
  1718. sidebar_menu.onclick = function() {
  1719. var sidebar = document.getElementsByClassName('sidebar')[0];
  1720. if (hasClass(sidebar, "mobile") === true) {
  1721. hideSidebar();
  1722. } else {
  1723. showSidebar();
  1724. }
  1725. };
  1726. }
  1727. window.onresize = function() {
  1728. hideSidebar();
  1729. };
  1730. }());
  1731. // Sets the focus on the search bar at the top of the page
  1732. function focusSearchBar() {
  1733. document.getElementsByClassName('search-input')[0].focus();
  1734. }
  1735. // Removes the focus from the search bar
  1736. function defocusSearchBar() {
  1737. document.getElementsByClassName('search-input')[0].blur();
  1738. }