[
  {
    "path": ".editorconfig",
    "content": "# EditorConfig helps developers define and maintain consistent\n# coding styles between different editors and IDEs\n# editorconfig.org\n\nroot = true\n\n\n[*]\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\nindent_size = 4\n\n[*.rs]\nindent_style = space\nindent_size = 4\n\n[*.toml]\nindent_style = space\nindent_size = 4\n\n[*.md]\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\nlog.json\n.DS_Store\ndist/\n*.bk\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: rust\nrust:\n- stable\nnotifications:\n  email:\n    on_success: never\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"compile-trpl\"\nversion = \"0.1.1\"\nauthors = [\"Pascal Hertleif <killercup@gmail.com>\"]\n\n[features]\ndefault = []\ndev = [\"clippy\"]\n\n[dependencies]\nregex = \"0.1.32\"\ndocopt = \"0.6.69\"\nrustc-serialize = \"0.3\"\n\n[dependencies.clippy]\ngit = \"https://github.com/Manishearth/rust-clippy.git\"\noptional = true\n"
  },
  {
    "path": "Readme.md",
    "content": "# 'The Rust Programming Language' as EBook\n\nThis repository contains stuff to convert [this book](http://doc.rust-lang.org/book/) to HTML, EPUB and PDF.\n\n**[Download Links](http://killercup.github.io/trpl-ebook/)**\n\n[![Build Status](https://travis-ci.org/killercup/trpl-ebook.svg?branch=master)](https://travis-ci.org/killercup/trpl-ebook)\n\n## DIY\n\nInstall:\n\n- pandoc\n- Rust and cargo\n- XeLaTeX, up to date (`sudo tlmgr update -all`) and probably some additional packages (`sudo tlmgr install $pkg`) such as:\n    + framed\n    + hyphenat\n    + quotchap\n    + collection-fontsrecommended\n    + mathspec\n    + euenc\n    + xltxtra\n    + xecjk\n    + fancyhdr\n- the DejaVu Sans Mono font: http://dejavu-fonts.org/\n- the IPA font for Japanese Text: http://ipafont.ipa.go.jp/ipaexfont/download.html#en\n\nThen run:\n\n```sh\n$ cargo run --release\n```\n\nVoilà!\n\n## Build different books\n\nThere are some CLI arguments that you can use to compile books other than the default (`trpl`). E.g., this repository also include the Rustonomicon.\n\nYou can build it like this:\n\n```sh\n$ cargo run --release -- --prefix=nomicon --source=nomicon --meta=nomicon_meta.yml\n```\n\n## License\n\nThe book content itself as well as any code I added as part of this repository is Copyright (c) 2015 The Rust Project Developers and licensed like Rust itself ([MIT](https://github.com/rust-lang/rust/blob/master/LICENSE-MIT) and [Apache](https://github.com/rust-lang/rust/blob/master/LICENSE-APACHE)).\n"
  },
  {
    "path": "build.sh",
    "content": "#! /bin/sh\n\nRUN=\"cargo run --release --\"\n\n$RUN --prefix=trpl --source=trpl --meta=trpl_meta.yml && \\\n$RUN --prefix=nomicon --source=nomicon --meta=nomicon_meta.yml\n"
  },
  {
    "path": "lib/epub.css",
    "content": "/* based on https://github.com/jgm/pandoc/blob/c9cb313a479f3d134d5df1cffe5e340034fb44b4/data/epub.css */\nbody { margin: 5%; text-align: justify; font-size: medium; }\ncode { font-family: monospace; word-wrap: break-word }\nh1 { text-align: left; }\nh2 { text-align: left; }\nh3 { text-align: left; }\nh4 { text-align: left; }\nh5 { text-align: left; }\nh6 { text-align: left; }\nh1.title { }\nh2.author { }\nh3.date { }\nol.toc { padding: 0; margin-left: 1em; }\nol.toc li { list-style-type: none; margin: 0; padding: 0; }\na.footnoteRef { vertical-align: super; }\n\npre { text-align: left; white-space: pre-wrap; font-size: 0.6em; }\n"
  },
  {
    "path": "lib/index.css",
    "content": "body { max-width: 40em; margin: 6em auto 2em; font-size: 16px; font-family: sans-serif; line-height: 1.3; padding: 0.6em; }\n@media screen and (max-width:800px){\n    body { margin-top: 1em;}\n}\narticle, header, footer, aside { display: block; }\nli { margin-bottom: 0.5em; }\nfooter { text-align: center; margin-top: 4em; font-size: 0.8em; }\naside { position: absolute; top: 0; right: 0; border: 0; }\naside img { border: 0; }\n\n/* from https://codepo8.github.io/css-fork-on-github-ribbon/ */\n#forkongithub a{background:#666;color:#fff;text-decoration:none;font-family:arial,sans-serif;text-align:center;font-weight:bold;padding:5px 40px;font-size:1rem;line-height:2rem;position:relative;transition:0.2s;}\n#forkongithub a:hover{background:#000;color:#fff;}\n#forkongithub a::before,#forkongithub a::after{content:\"\";width:100%;display:block;position:absolute;top:1px;left:0;height:1px;background:#fff;}\n#forkongithub a::after{bottom:1px;top:auto;}\n@media screen and (min-width:800px){\n    #forkongithub{position:absolute;display:block;top:0;right:0;width:200px;overflow:hidden;height:200px;z-index:9999;}\n    #forkongithub a{width:200px;position:absolute;top:60px;right:-60px;transform:rotate(45deg);-webkit-transform:rotate(45deg);-ms-transform:rotate(45deg);-moz-transform:rotate(45deg);-o-transform:rotate(45deg);box-shadow:2px 2px 5px rgba(0,0,0,0.3);}\n}\n"
  },
  {
    "path": "lib/index_template.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Download 'The Rust Programming Language' E-Books (PDF, EPUB, MOBI)</title>\n    <meta name=\"viewport\" content=\"width=device-width\"/>\n    <style>\n        {css}\n    </style>\n</head>\n<body>\n    <article role=\"main\">\n        <header>\n            <h1>'The Rust Programming Language' E-Books</h1>\n            <span id=\"forkongithub\"><a href=\"https://github.com/killercup/trpl-ebook\">Fork me on GitHub</a></span>\n        </header>\n        <ul>\n            <li>\n                <a href=\"http://doc.rust-lang.org/nightly/book/\">Read the original 'The Rust Programming Language' on rust-lang.org</a>\n            </li>\n            <li>\n                <a href=\"http://doc.rust-lang.org/nightly/nomicon/\">Read the original 'The Rustonomicon' on rust-lang.org</a>\n            </li>\n            {file_listing}\n        </ul>\n        <footer>\n            Made with ♥︎, too much RegEx and <a href=\"http://pandoc.org/\">Pandoc</a> by <a href=\"http://pascalhertleif.de/\">Pascal Hertleif</a>\n        </footer>\n    </article>\n</body>\n</html>\n"
  },
  {
    "path": "lib/pandoc.css",
    "content": "/**\n * # Stylesheet for Pandoc Documents\n */\n\n/**\n * ## Fonts\n */\n\nbody {\n  font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;\n  font-size: 12px;\n  line-height: 1.7;\n  max-width: 42em;\n}\n\n@media only screen and (min-width: 480px) {\n  body {\n    font-size: 14px;\n  }\n}\n@media only screen and (min-width: 768px) {\n  body {\n    font-size: 16px;\n  }\n}\n\nh1, h2, h3, h4, h5, h6 {\n  line-height: 125%;\n}\n\nh1, h2, h3 {\n  font-weight: normal;\n}\n\nh4, h5, h6 {\n  font-weight: bold;\n}\n\nh1 {\n  font-size: 2em;\n}\n\nh2 {\n  font-size: 1.8em;\n}\n\nh3 {\n  font-size: 1.5em;\n}\n\nh4 {\n  font-size: 1.2em;\n}\n\nh5 {\n  font-size: 1em;\n}\n\nh6 {\n  font-size: 0.9em;\n}\n\npre, code, kbd, samp {\n  font-family: monospace;\n  font-size: 0.98em;\n}\n\n/**\n * ## Other Styles\n */\n\nhtml {\n  font-size: 100%;\n  overflow-y: scroll;\n  -webkit-text-size-adjust: 100%;\n  -ms-text-size-adjust: 100%;\n}\n\nbody {\n  color: #444;\n  padding: 1em;\n  margin: auto;\n  background: #fefefe;\n}\n\na {\n  color: #0645ad;\n  text-decoration: none;\n}\n\na:visited {\n  color: #0b0080;\n}\n\na:hover {\n  color: #06e;\n}\n\na:active {\n  color: #faa700;\n}\n\na:focus {\n  outline: thin dotted;\n}\n\n*::-moz-selection {\n  background: rgba(255, 255, 0, 0.3);\n  color: #000;\n}\n\n*::selection {\n  background: rgba(255, 255, 0, 0.3);\n  color: #000;\n}\n\na::-moz-selection {\n  background: rgba(255, 255, 0, 0.3);\n  color: #0645ad;\n}\n\na::selection {\n  background: rgba(255, 255, 0, 0.3);\n  color: #0645ad;\n}\n\nh1, h2, h3, h4, h5, h6 {\n  color: #111;\n  margin-top: 2em;\n}\n\np {\n  margin: 1em 0;\n}\n\nimg {\n  max-width: 100%;\n}\n\nq { quotes: \"\\201C\" \"\\201D\" \"\\2018\" \"\\2019\"; }\n\n[lang=de] q {\n  quotes: \"\\00bb\" \"\\00ab\" \"\\203A\" \"\\2039\";\n}\n\nblockquote,\naside.notes {\n  color: #666;\n  margin: 0;\n  padding-left: 3em;\n  border-left: 0.5em #EEE solid;\n}\n\naside.notes {\n  color: #999;\n  border-left-color: #ffa;\n}\n\nhr {\n  display: block;\n  height: 2px;\n  border: 0;\n  border-top: 1px solid #aaa;\n  border-bottom: 1px solid #eee;\n  margin: 1em 0;\n  padding: 0;\n}\n\npre, code, kbd, samp {\n  color: #000;\n}\n\npre {\n  white-space: pre;\n  white-space: pre-wrap;\n  word-wrap: break-word;\n  padding: 0.1em 0.4em;\n  text-indent: 1em;\n}\n\nb, strong {\n  font-weight: bold;\n}\n\ndfn {\n  font-style: italic;\n}\n\nins {\n  background: #ff9;\n  color: #000;\n  text-decoration: none;\n}\n\nmark {\n  background: #ff0;\n  color: #000;\n  font-style: italic;\n  font-weight: bold;\n}\n\nsub, sup {\n  font-size: 75%;\n  line-height: 0;\n  position: relative;\n  vertical-align: baseline;\n}\n\nsup {\n  top: -0.5em;\n}\n\nsub {\n  bottom: -0.25em;\n}\n\nul, ol {\n  margin: 1em 0;\n  padding: 0 0 0 2em;\n}\n\nli p:last-child {\n  margin-bottom: 0;\n}\n\nul ul, ol ol {\n  margin: .3em 0;\n}\n\ndl {\n  margin-bottom: 1em;\n}\n\ndt {\n  font-weight: bold;\n  margin-bottom: .8em;\n}\n\ndd {\n  margin: 0 0 .8em 2em;\n}\n\ndd:last-child {\n  margin-bottom: 0;\n}\n\nimg {\n  border: 0;\n  -ms-interpolation-mode: bicubic;\n  vertical-align: middle;\n}\n\nfigure {\n  display: block;\n  text-align: center;\n  margin: 2em 0;\n}\n\nfigure img {\n  border: none;\n  margin: 0 auto 1em;\n}\n\nfigcaption {\n  font-size: 0.8em;\n  font-style: italic;\n  margin: 0 0 .8em;\n}\n\ntable {\n  margin-bottom: 2em;\n  border-bottom: 1px solid #ddd;\n  border-right: 1px solid #ddd;\n  border-spacing: 0;\n  border-collapse: collapse;\n}\n\ntable th {\n  padding: .2em 1em;\n  background-color: #eee;\n  border-top: 1px solid #ddd;\n  border-left: 1px solid #ddd;\n}\n\ntable td {\n  padding: .2em 1em;\n  border-top: 1px solid #ddd;\n  border-left: 1px solid #ddd;\n  vertical-align: top;\n}\n\n.byline {\n  font-size: 1.2em;\n  text-align: center;\n}\n\n.references a.uri {word-break: break-all;}\n\nnav.toc ul {\n  list-style-type: decimal;\n}\n\nnav.toc.already-numbered ul {\n  list-style-type: none;\n}\n\nnav.toc.already-numbered > ul {\n  padding: 0;\n}\n\n/**\n * ## Print Styles\n */\n\n@media print {\n  * {\n    background: transparent !important;\n    color: black !important;\n    filter: none !important;\n    -ms-filter: none !important;\n  }\n\n  body {\n    font-size: 9pt;\n    line-height: 1.2;\n    max-width: 100%;\n  }\n\n  a, a:visited {\n    text-decoration: underline;\n  }\n\n  hr {\n    height: 1px;\n    border: 0;\n    border-bottom: 1px solid black;\n  }\n\n  /*a[href]:after {\n    content: \" (\" attr(href) \")\";\n  }*/\n\n  abbr[title]:after {\n    content: \" (\" attr(title) \")\";\n  }\n\n  .ir a:after, a[href^=\"javascript:\"]:after, a[href^=\"#\"]:after {\n    content: \"\";\n  }\n\n  pre, blockquote {\n    border: 1px solid #999;\n    padding-right: 1em;\n    page-break-inside: avoid;\n  }\n\n  tr, img {\n    page-break-inside: avoid;\n  }\n\n  img {\n    max-width: 100% !important;\n  }\n\n  @page :left {\n    margin: 25mm 30mm 25mm 20mm;\n  }\n\n  @page :right {\n    margin: 25mm 20mm 25mm 30mm;\n  }\n\n  p, h2, h3 {\n    orphans: 3;\n    widows: 3;\n  }\n\n  h1, h2, h3, h4 {\n    page-break-after: avoid;\n  }\n}\n"
  },
  {
    "path": "lib/template.html",
    "content": "<!DOCTYPE html>\n<html$if(locale)$ lang=\"$locale$\"$endif$>\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"generator\" content=\"pandoc\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">\n$for(author-meta)$\n  <meta name=\"author\" content=\"$author-meta$\">\n$endfor$\n$if(date-meta)$\n  <meta name=\"dcterms.date\" content=\"$date-meta$\">\n$endif$\n  <title>$if(title-prefix)$$title-prefix$ - $endif$$pagetitle$</title>\n  <!--[if lt IE 9]>\n    <script src=\"http://html5shim.googlecode.com/svn/trunk/html5.js\"></script>\n  <![endif]-->\n$if(highlighting-css)$\n  <style type=\"text/css\">\n$highlighting-css$\n  </style>\n$endif$\n$for(css)$\n  <link rel=\"stylesheet\" href=\"$css$\">\n$endfor$\n$if(math)$\n  $math$\n$endif$\n$for(header-includes)$\n  $header-includes$\n$endfor$\n</head>\n<body role=\"document\">\n\n$for(include-before)$\n  $include-before$\n$endfor$\n\n$if(title)$\n<header>\n  <h1 class=\"title\">$title$</h1>\n\n  $if(subtitle)$\n    <h1 class=\"subtitle\">$subtitle$</h1>\n  $endif$\n\n  <div class=\"byline vcard\">\n    <address>\n    $for(author)$\n      <p class=\"author\">$author$</p>\n    $endfor$\n    </address>\n  $if(date)$\n    <time pubdate=\"pubdate\" date=\"$date$\" class=\"date\">$date$</time>\n  $endif$\n  </div>\n</header>\n$endif$\n\n$if(abstract)$\n<article role=\"contentinfo\" class=\"abstract\">\n  $abstract$\n</article>\n$endif$\n\n$if(toc)$\n<nav class=\"toc$if(numberedSections)$ already-numbered$endif$\" id=\"$idprefix$TOC\">\n  <h2>Table of Contents</h2>\n  $toc$\n</nav>\n$endif$\n\n<article role=\"main\">\n  $body$\n</article>\n\n$for(include-after)$\n  $include-after$\n$endfor$\n</body>\n</html>\n"
  },
  {
    "path": "lib/template.tex",
    "content": "% \\documentclass[12pt]{article}\n\\documentclass[$if(fontsize)$$fontsize$,$endif$$if(lang)$$lang$,$endif$$if(papersize)$$papersize$,$else$a4paper,$endif$$for(classoption)$$classoption$$sep$,$endfor$]{$documentclass$}\n\n$if(fontfamily)$\n  \\usepackage{$fontfamily$}\n$else$\n  \\usepackage{lmodern}\n$endif$\n\n$if(lang)$\n\\ifxetex\n  \\usepackage{polyglossia}\n  \\setmainlanguage{$lang$}\n\\else\n  \\usepackage[shorthands=off,$lang$]{babel}\n\\fi\n$endif$\n\n\\usepackage[$if(papersize)$$papersize$$else$a4paper$endif$]{geometry}\n\n\\usepackage{graphicx}\n\n\\usepackage{longtable}\n\\usepackage{booktabs}\n\\usepackage[htt]{hyphenat}\n\n\\usepackage{amssymb}\n\n% use upquote if available, for straight quotes in verbatim environments\n\\IfFileExists{upquote.sty}{\\usepackage{upquote}}{}\n% use microtype if available\n\\IfFileExists{microtype.sty}{\\usepackage{microtype}}{}\n\n\\ifxetex\n  \\usepackage[setpagesize=false, % page size defined by xetex\n              unicode=false, % unicode breaks when used with xetex\n              xetex]{hyperref}\n\\else\n  \\usepackage[unicode=true]{hyperref}\n\\fi\n\n% Break URLs in a few more places. (For breaking lines, not functionality!)\n% cf. http://tex.stackexchange.com/questions/3033/forcing-linebreaks-in-url\n\\expandafter\\def\\expandafter\\UrlBreaks\\expandafter{\\UrlBreaks%  save the current one\n  \\do\\*\\do\\-\\do\\~\\do\\'\\do\\\"\\do\\-}\n\n\\hypersetup{breaklinks=true,\n            bookmarks=true,\n            pdfauthor={$author-meta$},\n            pdftitle={$title-meta$},\n            colorlinks=false,\n            citecolor=$if(citecolor)$$citecolor$$else$blue$endif$,\n            urlcolor=$if(urlcolor)$$urlcolor$$else$blue$endif$,\n            linkcolor=$if(linkcolor)$$linkcolor$$else$magenta$endif$,\n            pdfborder={0 0 0}}\n\\urlstyle{same}  % don't use monospace font for urls\n\n\\renewcommand*{\\hypertarget}[3][\\ar]{%\n  \\def\\ar{#2}%\n  \\label{#1}%\n  #3}\n\n\\renewcommand*{\\hyperlink}[2]{%\n #2 (\\autoref{#1}, page~\\pageref{#1})}\n\n\\ifnum 0\\ifxetex 1\\fi\\ifluatex 1\\fi=0 % if pdftex\n  \\usepackage[T1]{fontenc}\n  \\usepackage[utf8]{inputenc}\n  $if(euro)$\n    \\usepackage{eurosym}\n  $endif$\n\\else % if luatex or xelatex\n  \\ifxetex\n    \\usepackage{mathspec}\n    \\usepackage{xltxtra,xunicode}\n    \\usepackage{xeCJK}\n    \\setCJKmainfont{IPAexMincho}\n  \\else\n    \\usepackage{fontspec}\n  \\fi\n  \\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}\n  \\newcommand{\\euro}{€}\n\n  $if(mainfont)$\n    \\setmainfont{$mainfont$}\n  $endif$\n\n  $if(sansfont)$\n    \\setsansfont{$sansfont$}\n  $endif$\n\n  $if(monofont)$\n    \\setmonofont[Mapping=tex-ansi]{$monofont$}\n  $endif$\n\n  $if(mathfont)$\n    \\setmathfont(Digits,Latin,Greek){$mathfont$}\n  $endif$\n\\fi\n\n\\setlength{\\emergencystretch}{3em}  % prevent overfull lines\n\n% use upquote if available, for straight quotes in verbatim environments\n\\IfFileExists{upquote.sty}{\\usepackage{upquote}}{}\n% use microtype if available\n\\IfFileExists{microtype.sty}{\\usepackage{microtype}}{}\n\n$if(graphics)$\n  \\usepackage{graphicx}\n  \\makeatletter\n  \\def\\maxwidth{\\ifdim\\Gin@nat@width>\\linewidth\\linewidth\\else\\Gin@nat@width\\fi}\n  \\def\\maxheight{\\ifdim\\Gin@nat@height>\\textheight\\textheight\\else\\Gin@nat@height\\fi}\n  \\makeatother\n  % Scale images if necessary, so that they will not overflow the page\n  % margins by default, and it is still possible to overwrite the defaults\n  % using explicit options in \\includegraphics[width, height, ...]{}\n  \\setkeys{Gin}{width=\\maxwidth,height=\\maxheight,keepaspectratio}\n$endif$\n\n\\usepackage{xcolor}\n$if(listings)$\n  \\usepackage{listings}\n  % Setup of Code Highlighting\n  % cf. http://tex.stackexchange.com/a/179956/21830\n  \\lstset{\n      basicstyle=\\ttfamily,\n      numbers=left,\n      keywordstyle=\\color[rgb]{0.13,0.29,0.53}\\bfseries,\n      stringstyle=\\color[rgb]{0.31,0.60,0.02},\n      commentstyle=\\color[rgb]{0.56,0.35,0.01}\\itshape,\n      numberstyle=\\footnotesize,\n      stepnumber=5,\n      numbersep=5pt,\n      backgroundcolor=\\color[RGB]{248,248,248},\n      showspaces=false,\n      showstringspaces=false,\n      showtabs=false,\n      tabsize=2,\n      captionpos=b,\n      breaklines=true,\n      breakatwhitespace=true,\n      breakautoindent=true,\n      escapeinside={\\%*}{*)},\n      linewidth=\\textwidth,\n      basewidth=0.5em,\n  }\n$endif$\n\n$if(highlighting-macros)$\n  $highlighting-macros$\n$endif$\n\n$if(verbatim-in-note)$\n  \\usepackage{fancyvrb}\n$endif$\n\n$if(links-as-notes)$\n  % Make links footnotes instead of hotlinks:\n  \\renewcommand{\\href}[2]{#2\\footnote{\\url{#1}}}\n$endif$\n\n$if(verbatim-in-note)$\n  \\VerbatimFootnotes % allows verbatim text in footnotes\n$endif$\n\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{6pt plus 2pt minus 1pt}\n\\setlength{\\emergencystretch}{3em}  % prevent overfull lines\n\n\\providecommand{\\tightlist}{%\n  \\setlength{\\itemsep}{0pt}\\setlength{\\parskip}{0pt}}\n$if(numbersections)$\n\\setcounter{secnumdepth}{5}\n$else$\n\\setcounter{secnumdepth}{0}\n$endif$\n\n\\usepackage[font={footnotesize,sf}]{caption}\n\n% Redefines (sub)paragraphs to behave more like sections\n\\ifx\\paragraph\\undefined\\else\n\\let\\oldparagraph\\paragraph\n\\renewcommand{\\paragraph}[1]{\\oldparagraph{#1}\\mbox{}}\n\\fi\n\\ifx\\subparagraph\\undefined\\else\n\\let\\oldsubparagraph\\subparagraph\n\\renewcommand{\\subparagraph}[1]{\\oldsubparagraph{#1}\\mbox{}}\n\\fi\n\n% - - -\n% Make it fancy\n\n% Headers and page numbering\n\\usepackage{fancyhdr}\n\n% Set figure legends and captions to be smaller sized sans serif font\n\\usepackage[font={footnotesize,sf}]{caption}\n\n% Chapter styling\n\\usepackage[grey]{quotchap}\n\\makeatletter\n\\renewcommand*{\\chapnumfont}{%\n  \\thispagestyle{empty}\n  \\usefont{T1}{\\@defaultcnfont}{b}{n}\\fontsize{80}{100}\\selectfont% Default: 100/130\n  \\color{chaptergrey}%\n}\n\\makeatother\n\n% - - -\n\n$if(title)$\n  \\title{$title$}\n$endif$\n$if(subtitle)$\n  \\subtitle{$subtitle$}\n$endif$\n$if(author)$\n  \\author{$for(author)$$author$$sep$ \\and $endfor$}\n$endif$\n$if(date)$\n  \\date{$date$}\n$endif$\n\n\\begin{document}\n\n$if(title)$\n  \\maketitle\n$endif$\n\n$if(abstract)$\n  \\begin{abstract}\n    $abstract$\n  \\end{abstract}\n$endif$\n\n$for(include-before)$\n  $include-before$\n$endfor$\n\n$if(toc)$\n{\n  \\hypersetup{linkcolor=black}\n  \\setcounter{tocdepth}{$toc-depth$}\n  \\tableofcontents\n  \\newpage\n}\n$endif$\n\n$body$\n\n$if(natbib)$\n  $if(biblio-files)$\n    $if(biblio-title)$\n      $if(book-class)$\n        \\renewcommand\\bibname{$biblio-title$}\n      $else$\n        \\renewcommand\\refname{$biblio-title$}\n      $endif$\n    $endif$\n    \\bibliography{$biblio-files$}\n  $endif$\n$endif$\n\n$if(biblatex)$\n  \\printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$\n$endif$\n\n$for(include-after)$\n  $include-after$\n$endfor$\n\\end{document}\n"
  },
  {
    "path": "nomicon/README.md",
    "content": "% The Rustonomicon\n\n#### The Dark Arts of Advanced and Unsafe Rust Programming\n\n**NOTE: This is a draft document, and may contain serious errors**\n\n> Instead of the programs I had hoped for, there came only a shuddering blackness\nand ineffable loneliness; and I saw at last a fearful truth which no one had\never dared to breathe before — the unwhisperable secret of secrets — The fact\nthat this language of stone and stridor is not a sentient perpetuation of Rust\nas London is of Old London and Paris of Old Paris, but that it is in fact\nquite unsafe, its sprawling body imperfectly embalmed and infested with queer\nanimate things which have nothing to do with it as it was in compilation.\n\nThis book digs into all the awful details that are necessary to understand in\norder to write correct Unsafe Rust programs. Due to the nature of this problem,\nit may lead to unleashing untold horrors that shatter your psyche into a billion\ninfinitesimal fragments of despair.\n\nShould you wish a long and happy career of writing Rust programs, you should\nturn back now and forget you ever saw this book. It is not necessary. However\nif you intend to write unsafe code -- or just want to dig into the guts of the\nlanguage -- this book contains invaluable information.\n\nUnlike [The Book][trpl] we will be assuming considerable prior knowledge. In\nparticular, you should be comfortable with basic systems programming and Rust.\nIf you don't feel comfortable with these topics, you should consider [reading\nThe Book][trpl] first. Though we will not be assuming that you have, and will\ntake care to occasionally give a refresher on the basics where appropriate. You\ncan skip straight to this book if you want; just know that we won't be\nexplaining everything from the ground up.\n\nTo be clear, this book goes into deep detail. We're going to dig into\nexception-safety, pointer aliasing, memory models, and even some type-theory.\nWe will also be spending a lot of time talking about the different kinds\nof safety and guarantees.\n\n[trpl]: ../book/\n"
  },
  {
    "path": "nomicon/SUMMARY.md",
    "content": "# Summary\n\n* [Meet Safe and Unsafe](meet-safe-and-unsafe.md)\n\t* [How Safe and Unsafe Interact](safe-unsafe-meaning.md)\n\t* [Working with Unsafe](working-with-unsafe.md)\n* [Data Layout](data.md)\n\t* [repr(Rust)](repr-rust.md)\n\t* [Exotically Sized Types](exotic-sizes.md)\n\t* [Other reprs](other-reprs.md)\n* [Ownership](ownership.md)\n\t* [References](references.md)\n\t* [Lifetimes](lifetimes.md)\n\t* [Limits of Lifetimes](lifetime-mismatch.md)\n\t* [Lifetime Elision](lifetime-elision.md)\n\t* [Unbounded Lifetimes](unbounded-lifetimes.md)\n\t* [Higher-Rank Trait Bounds](hrtb.md)\n\t* [Subtyping and Variance](subtyping.md)\n\t* [Drop Check](dropck.md)\n\t* [PhantomData](phantom-data.md)\n\t* [Splitting Borrows](borrow-splitting.md)\n* [Type Conversions](conversions.md)\n\t* [Coercions](coercions.md)\n\t* [The Dot Operator](dot-operator.md)\n\t* [Casts](casts.md)\n\t* [Transmutes](transmutes.md)\n* [Uninitialized Memory](uninitialized.md)\n\t* [Checked](checked-uninit.md)\n\t* [Drop Flags](drop-flags.md)\n\t* [Unchecked](unchecked-uninit.md)\n* [Ownership Based Resource Management](obrm.md)\n\t* [Constructors](constructors.md)\n\t* [Destructors](destructors.md)\n\t* [Leaking](leaking.md)\n* [Unwinding](unwinding.md)\n\t* [Exception Safety](exception-safety.md)\n\t* [Poisoning](poisoning.md)\n* [Concurrency](concurrency.md)\n\t* [Races](races.md)\n\t* [Send and Sync](send-and-sync.md)\n\t* [Atomics](atomics.md)\n* [Implementing Vec](vec.md)\n\t* [Layout](vec-layout.md)\n\t* [Allocating](vec-alloc.md)\n\t* [Push and Pop](vec-push-pop.md)\n\t* [Deallocating](vec-dealloc.md)\n\t* [Deref](vec-deref.md)\n\t* [Insert and Remove](vec-insert-remove.md)\n\t* [IntoIter](vec-into-iter.md)\n\t* [RawVec](vec-raw.md)\n\t* [Drain](vec-drain.md)\n\t* [Handling Zero-Sized Types](vec-zsts.md)\n\t* [Final Code](vec-final.md)\n* [Implementing Arc and Mutex](arc-and-mutex.md)\n"
  },
  {
    "path": "nomicon/arc-and-mutex.md",
    "content": "% Implementing Arc and Mutex\n\nKnowing the theory is all fine and good, but the *best* way to understand\nsomething is to use it. To better understand atomics and interior mutability,\nwe'll be implementing versions of the standard library's Arc and Mutex types.\n\nTODO: ALL OF THIS OMG\n"
  },
  {
    "path": "nomicon/atomics.md",
    "content": "% Atomics\n\nRust pretty blatantly just inherits C11's memory model for atomics. This is not\ndue to this model being particularly excellent or easy to understand. Indeed,\nthis model is quite complex and known to have [several flaws][C11-busted].\nRather, it is a pragmatic concession to the fact that *everyone* is pretty bad\nat modeling atomics. At very least, we can benefit from existing tooling and\nresearch around C.\n\nTrying to fully explain the model in this book is fairly hopeless. It's defined\nin terms of madness-inducing causality graphs that require a full book to\nproperly understand in a practical way. If you want all the nitty-gritty\ndetails, you should check out [C's specification (Section 7.17)][C11-model].\nStill, we'll try to cover the basics and some of the problems Rust developers\nface.\n\nThe C11 memory model is fundamentally about trying to bridge the gap between the\nsemantics we want, the optimizations compilers want, and the inconsistent chaos\nour hardware wants. *We* would like to just write programs and have them do\nexactly what we said but, you know, fast. Wouldn't that be great?\n\n\n\n\n# Compiler Reordering\n\nCompilers fundamentally want to be able to do all sorts of crazy transformations\nto reduce data dependencies and eliminate dead code. In particular, they may\nradically change the actual order of events, or make events never occur! If we\nwrite something like\n\n```rust,ignore\nx = 1;\ny = 3;\nx = 2;\n```\n\nThe compiler may conclude that it would be best if your program did\n\n```rust,ignore\nx = 2;\ny = 3;\n```\n\nThis has inverted the order of events and completely eliminated one event.\nFrom a single-threaded perspective this is completely unobservable: after all\nthe statements have executed we are in exactly the same state. But if our\nprogram is multi-threaded, we may have been relying on `x` to actually be\nassigned to 1 before `y` was assigned. We would like the compiler to be\nable to make these kinds of optimizations, because they can seriously improve\nperformance. On the other hand, we'd also like to be able to depend on our\nprogram *doing the thing we said*.\n\n\n\n\n# Hardware Reordering\n\nOn the other hand, even if the compiler totally understood what we wanted and\nrespected our wishes, our hardware might instead get us in trouble. Trouble\ncomes from CPUs in the form of memory hierarchies. There is indeed a global\nshared memory space somewhere in your hardware, but from the perspective of each\nCPU core it is *so very far away* and *so very slow*. Each CPU would rather work\nwith its local cache of the data and only go through all the anguish of\ntalking to shared memory only when it doesn't actually have that memory in\ncache.\n\nAfter all, that's the whole point of the cache, right? If every read from the\ncache had to run back to shared memory to double check that it hadn't changed,\nwhat would the point be? The end result is that the hardware doesn't guarantee\nthat events that occur in the same order on *one* thread, occur in the same\norder on *another* thread. To guarantee this, we must issue special instructions\nto the CPU telling it to be a bit less smart.\n\nFor instance, say we convince the compiler to emit this logic:\n\n```text\ninitial state: x = 0, y = 1\n\nTHREAD 1        THREAD2\ny = 3;          if x == 1 {\nx = 1;              y *= 2;\n                }\n```\n\nIdeally this program has 2 possible final states:\n\n* `y = 3`: (thread 2 did the check before thread 1 completed)\n* `y = 6`: (thread 2 did the check after thread 1 completed)\n\nHowever there's a third potential state that the hardware enables:\n\n* `y = 2`: (thread 2 saw `x = 1`, but not `y = 3`, and then overwrote `y = 3`)\n\nIt's worth noting that different kinds of CPU provide different guarantees. It\nis common to separate hardware into two categories: strongly-ordered and weakly-\nordered. Most notably x86/64 provides strong ordering guarantees, while ARM\nprovides weak ordering guarantees. This has two consequences for concurrent\nprogramming:\n\n* Asking for stronger guarantees on strongly-ordered hardware may be cheap or\n  even free because they already provide strong guarantees unconditionally.\n  Weaker guarantees may only yield performance wins on weakly-ordered hardware.\n\n* Asking for guarantees that are too weak on strongly-ordered hardware is\n  more likely to *happen* to work, even though your program is strictly\n  incorrect. If possible, concurrent algorithms should be tested on\n  weakly-ordered hardware.\n\n\n\n\n\n# Data Accesses\n\nThe C11 memory model attempts to bridge the gap by allowing us to talk about the\n*causality* of our program. Generally, this is by establishing a *happens\nbefore* relationship between parts of the program and the threads that are\nrunning them. This gives the hardware and compiler room to optimize the program\nmore aggressively where a strict happens-before relationship isn't established,\nbut forces them to be more careful where one is established. The way we\ncommunicate these relationships are through *data accesses* and *atomic\naccesses*.\n\nData accesses are the bread-and-butter of the programming world. They are\nfundamentally unsynchronized and compilers are free to aggressively optimize\nthem. In particular, data accesses are free to be reordered by the compiler on\nthe assumption that the program is single-threaded. The hardware is also free to\npropagate the changes made in data accesses to other threads as lazily and\ninconsistently as it wants. Most critically, data accesses are how data races\nhappen. Data accesses are very friendly to the hardware and compiler, but as\nwe've seen they offer *awful* semantics to try to write synchronized code with.\nActually, that's too weak.\n\n**It is literally impossible to write correct synchronized code using only data\naccesses.**\n\nAtomic accesses are how we tell the hardware and compiler that our program is\nmulti-threaded. Each atomic access can be marked with an *ordering* that\nspecifies what kind of relationship it establishes with other accesses. In\npractice, this boils down to telling the compiler and hardware certain things\nthey *can't* do. For the compiler, this largely revolves around re-ordering of\ninstructions. For the hardware, this largely revolves around how writes are\npropagated to other threads. The set of orderings Rust exposes are:\n\n* Sequentially Consistent (SeqCst)\n* Release\n* Acquire\n* Relaxed\n\n(Note: We explicitly do not expose the C11 *consume* ordering)\n\nTODO: negative reasoning vs positive reasoning? TODO: \"can't forget to\nsynchronize\"\n\n\n\n# Sequentially Consistent\n\nSequentially Consistent is the most powerful of all, implying the restrictions\nof all other orderings. Intuitively, a sequentially consistent operation\ncannot be reordered: all accesses on one thread that happen before and after a\nSeqCst access stay before and after it. A data-race-free program that uses\nonly sequentially consistent atomics and data accesses has the very nice\nproperty that there is a single global execution of the program's instructions\nthat all threads agree on. This execution is also particularly nice to reason\nabout: it's just an interleaving of each thread's individual executions. This\ndoes not hold if you start using the weaker atomic orderings.\n\nThe relative developer-friendliness of sequential consistency doesn't come for\nfree. Even on strongly-ordered platforms sequential consistency involves\nemitting memory fences.\n\nIn practice, sequential consistency is rarely necessary for program correctness.\nHowever sequential consistency is definitely the right choice if you're not\nconfident about the other memory orders. Having your program run a bit slower\nthan it needs to is certainly better than it running incorrectly! It's also\nmechanically trivial to downgrade atomic operations to have a weaker\nconsistency later on. Just change `SeqCst` to `Relaxed` and you're done! Of\ncourse, proving that this transformation is *correct* is a whole other matter.\n\n\n\n\n# Acquire-Release\n\nAcquire and Release are largely intended to be paired. Their names hint at their\nuse case: they're perfectly suited for acquiring and releasing locks, and\nensuring that critical sections don't overlap.\n\nIntuitively, an acquire access ensures that every access after it stays after\nit. However operations that occur before an acquire are free to be reordered to\noccur after it. Similarly, a release access ensures that every access before it\nstays before it. However operations that occur after a release are free to be\nreordered to occur before it.\n\nWhen thread A releases a location in memory and then thread B subsequently\nacquires *the same* location in memory, causality is established. Every write\nthat happened before A's release will be observed by B after its release.\nHowever no causality is established with any other threads. Similarly, no\ncausality is established if A and B access *different* locations in memory.\n\nBasic use of release-acquire is therefore simple: you acquire a location of\nmemory to begin the critical section, and then release that location to end it.\nFor instance, a simple spinlock might look like:\n\n```rust\nuse std::sync::Arc;\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::thread;\n\nfn main() {\n    let lock = Arc::new(AtomicBool::new(false)); // value answers \"am I locked?\"\n\n    // ... distribute lock to threads somehow ...\n\n    // Try to acquire the lock by setting it to true\n    while lock.compare_and_swap(false, true, Ordering::Acquire) { }\n    // broke out of the loop, so we successfully acquired the lock!\n\n    // ... scary data accesses ...\n\n    // ok we're done, release the lock\n    lock.store(false, Ordering::Release);\n}\n```\n\nOn strongly-ordered platforms most accesses have release or acquire semantics,\nmaking release and acquire often totally free. This is not the case on\nweakly-ordered platforms.\n\n\n\n\n# Relaxed\n\nRelaxed accesses are the absolute weakest. They can be freely re-ordered and\nprovide no happens-before relationship. Still, relaxed operations are still\natomic. That is, they don't count as data accesses and any read-modify-write\noperations done to them occur atomically. Relaxed operations are appropriate for\nthings that you definitely want to happen, but don't particularly otherwise care\nabout. For instance, incrementing a counter can be safely done by multiple\nthreads using a relaxed `fetch_add` if you're not using the counter to\nsynchronize any other accesses.\n\nThere's rarely a benefit in making an operation relaxed on strongly-ordered\nplatforms, since they usually provide release-acquire semantics anyway. However\nrelaxed operations can be cheaper on weakly-ordered platforms.\n\n\n\n\n\n[C11-busted]: http://plv.mpi-sws.org/c11comp/popl15.pdf\n[C11-model]: http://www.open-std.org/jtc1/sc22/wg14/www/standards.html#9899\n"
  },
  {
    "path": "nomicon/borrow-splitting.md",
    "content": "% Splitting Borrows\n\nThe mutual exclusion property of mutable references can be very limiting when\nworking with a composite structure. The borrow checker understands some basic\nstuff, but will fall over pretty easily. It does understand structs\nsufficiently to know that it's possible to borrow disjoint fields of a struct\nsimultaneously. So this works today:\n\n```rust\nstruct Foo {\n    a: i32,\n    b: i32,\n    c: i32,\n}\n\nlet mut x = Foo {a: 0, b: 0, c: 0};\nlet a = &mut x.a;\nlet b = &mut x.b;\nlet c = &x.c;\n*b += 1;\nlet c2 = &x.c;\n*a += 10;\nprintln!(\"{} {} {} {}\", a, b, c, c2);\n```\n\nHowever borrowck doesn't understand arrays or slices in any way, so this doesn't\nwork:\n\n```rust,ignore\nlet mut x = [1, 2, 3];\nlet a = &mut x[0];\nlet b = &mut x[1];\nprintln!(\"{} {}\", a, b);\n```\n\n```text\n<anon>:4:14: 4:18 error: cannot borrow `x[..]` as mutable more than once at a time\n<anon>:4 let b = &mut x[1];\n                      ^~~~\n<anon>:3:14: 3:18 note: previous borrow of `x[..]` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x[..]` until the borrow ends\n<anon>:3 let a = &mut x[0];\n                      ^~~~\n<anon>:6:2: 6:2 note: previous borrow ends here\n<anon>:1 fn main() {\n<anon>:2 let mut x = [1, 2, 3];\n<anon>:3 let a = &mut x[0];\n<anon>:4 let b = &mut x[1];\n<anon>:5 println!(\"{} {}\", a, b);\n<anon>:6 }\n         ^\nerror: aborting due to 2 previous errors\n```\n\nWhile it was plausible that borrowck could understand this simple case, it's\npretty clearly hopeless for borrowck to understand disjointness in general\ncontainer types like a tree, especially if distinct keys actually *do* map\nto the same value.\n\nIn order to \"teach\" borrowck that what we're doing is ok, we need to drop down\nto unsafe code. For instance, mutable slices expose a `split_at_mut` function\nthat consumes the slice and returns two mutable slices. One for everything to\nthe left of the index, and one for everything to the right. Intuitively we know\nthis is safe because the slices don't overlap, and therefore alias. However\nthe implementation requires some unsafety:\n\n```rust,ignore\nfn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {\n    let len = self.len();\n    let ptr = self.as_mut_ptr();\n    assert!(mid <= len);\n    unsafe {\n        (from_raw_parts_mut(ptr, mid),\n         from_raw_parts_mut(ptr.offset(mid as isize), len - mid))\n    }\n}\n```\n\nThis is actually a bit subtle. So as to avoid ever making two `&mut`'s to the\nsame value, we explicitly construct brand-new slices through raw pointers.\n\nHowever more subtle is how iterators that yield mutable references work.\nThe iterator trait is defined as follows:\n\n```rust\ntrait Iterator {\n    type Item;\n\n    fn next(&mut self) -> Option<Self::Item>;\n}\n```\n\nGiven this definition, Self::Item has *no* connection to `self`. This means that\nwe can call `next` several times in a row, and hold onto all the results\n*concurrently*. This is perfectly fine for by-value iterators, which have\nexactly these semantics. It's also actually fine for shared references, as they\nadmit arbitrarily many references to the same thing (although the iterator needs\nto be a separate object from the thing being shared).\n\nBut mutable references make this a mess. At first glance, they might seem\ncompletely incompatible with this API, as it would produce multiple mutable\nreferences to the same object!\n\nHowever it actually *does* work, exactly because iterators are one-shot objects.\nEverything an IterMut yields will be yielded at most once, so we don't\nactually ever yield multiple mutable references to the same piece of data.\n\nPerhaps surprisingly, mutable iterators don't require unsafe code to be\nimplemented for many types!\n\nFor instance here's a singly linked list:\n\n```rust\n# fn main() {}\ntype Link<T> = Option<Box<Node<T>>>;\n\nstruct Node<T> {\n    elem: T,\n    next: Link<T>,\n}\n\npub struct LinkedList<T> {\n    head: Link<T>,\n}\n\npub struct IterMut<'a, T: 'a>(Option<&'a mut Node<T>>);\n\nimpl<T> LinkedList<T> {\n    fn iter_mut(&mut self) -> IterMut<T> {\n        IterMut(self.head.as_mut().map(|node| &mut **node))\n    }\n}\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n    type Item = &'a mut T;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        self.0.take().map(|node| {\n            self.0 = node.next.as_mut().map(|node| &mut **node);\n            &mut node.elem\n        })\n    }\n}\n```\n\nHere's a mutable slice:\n\n```rust\n# fn main() {}\nuse std::mem;\n\npub struct IterMut<'a, T: 'a>(&'a mut[T]);\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n    type Item = &'a mut T;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        let slice = mem::replace(&mut self.0, &mut []);\n        if slice.is_empty() { return None; }\n\n        let (l, r) = slice.split_at_mut(1);\n        self.0 = r;\n        l.get_mut(0)\n    }\n}\n\nimpl<'a, T> DoubleEndedIterator for IterMut<'a, T> {\n    fn next_back(&mut self) -> Option<Self::Item> {\n        let slice = mem::replace(&mut self.0, &mut []);\n        if slice.is_empty() { return None; }\n\n        let new_len = slice.len() - 1;\n        let (l, r) = slice.split_at_mut(new_len);\n        self.0 = l;\n        r.get_mut(0)\n    }\n}\n```\n\nAnd here's a binary tree:\n\n```rust\n# fn main() {}\nuse std::collections::VecDeque;\n\ntype Link<T> = Option<Box<Node<T>>>;\n\nstruct Node<T> {\n    elem: T,\n    left: Link<T>,\n    right: Link<T>,\n}\n\npub struct Tree<T> {\n    root: Link<T>,\n}\n\nstruct NodeIterMut<'a, T: 'a> {\n    elem: Option<&'a mut T>,\n    left: Option<&'a mut Node<T>>,\n    right: Option<&'a mut Node<T>>,\n}\n\nenum State<'a, T: 'a> {\n    Elem(&'a mut T),\n    Node(&'a mut Node<T>),\n}\n\npub struct IterMut<'a, T: 'a>(VecDeque<NodeIterMut<'a, T>>);\n\nimpl<T> Tree<T> {\n    pub fn iter_mut(&mut self) -> IterMut<T> {\n        let mut deque = VecDeque::new();\n        self.root.as_mut().map(|root| deque.push_front(root.iter_mut()));\n        IterMut(deque)\n    }\n}\n\nimpl<T> Node<T> {\n    pub fn iter_mut(&mut self) -> NodeIterMut<T> {\n        NodeIterMut {\n            elem: Some(&mut self.elem),\n            left: self.left.as_mut().map(|node| &mut **node),\n            right: self.right.as_mut().map(|node| &mut **node),\n        }\n    }\n}\n\n\nimpl<'a, T> Iterator for NodeIterMut<'a, T> {\n    type Item = State<'a, T>;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        match self.left.take() {\n            Some(node) => Some(State::Node(node)),\n            None => match self.elem.take() {\n                Some(elem) => Some(State::Elem(elem)),\n                None => match self.right.take() {\n                    Some(node) => Some(State::Node(node)),\n                    None => None,\n                }\n            }\n        }\n    }\n}\n\nimpl<'a, T> DoubleEndedIterator for NodeIterMut<'a, T> {\n    fn next_back(&mut self) -> Option<Self::Item> {\n        match self.right.take() {\n            Some(node) => Some(State::Node(node)),\n            None => match self.elem.take() {\n                Some(elem) => Some(State::Elem(elem)),\n                None => match self.left.take() {\n                    Some(node) => Some(State::Node(node)),\n                    None => None,\n                }\n            }\n        }\n    }\n}\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n    type Item = &'a mut T;\n    fn next(&mut self) -> Option<Self::Item> {\n        loop {\n            match self.0.front_mut().and_then(|node_it| node_it.next()) {\n                Some(State::Elem(elem)) => return Some(elem),\n                Some(State::Node(node)) => self.0.push_front(node.iter_mut()),\n                None => if let None = self.0.pop_front() { return None },\n            }\n        }\n    }\n}\n\nimpl<'a, T> DoubleEndedIterator for IterMut<'a, T> {\n    fn next_back(&mut self) -> Option<Self::Item> {\n        loop {\n            match self.0.back_mut().and_then(|node_it| node_it.next_back()) {\n                Some(State::Elem(elem)) => return Some(elem),\n                Some(State::Node(node)) => self.0.push_back(node.iter_mut()),\n                None => if let None = self.0.pop_back() { return None },\n            }\n        }\n    }\n}\n```\n\nAll of these are completely safe and work on stable Rust! This ultimately\nfalls out of the simple struct case we saw before: Rust understands that you\ncan safely split a mutable reference into subfields. We can then encode\npermanently consuming a reference via Options (or in the case of slices,\nreplacing with an empty slice).\n"
  },
  {
    "path": "nomicon/casts.md",
    "content": "% Casts\n\nCasts are a superset of coercions: every coercion can be explicitly\ninvoked via a cast. However some conversions require a cast.\nWhile coercions are pervasive and largely harmless, these \"true casts\"\nare rare and potentially dangerous. As such, casts must be explicitly invoked\nusing the `as` keyword: `expr as Type`.\n\nTrue casts generally revolve around raw pointers and the primitive numeric\ntypes. Even though they're dangerous, these casts are infallible at runtime.\nIf a cast triggers some subtle corner case no indication will be given that\nthis occurred. The cast will simply succeed. That said, casts must be valid\nat the type level, or else they will be prevented statically. For instance,\n`7u8 as bool` will not compile.\n\nThat said, casts aren't `unsafe` because they generally can't violate memory\nsafety *on their own*. For instance, converting an integer to a raw pointer can\nvery easily lead to terrible things. However the act of creating the pointer\nitself is safe, because actually using a raw pointer is already marked as\n`unsafe`.\n\nHere's an exhaustive list of all the true casts. For brevity, we will use `*`\nto denote either a `*const` or `*mut`, and `integer` to denote any integral\nprimitive:\n\n * `*T as *U` where `T, U: Sized`\n * `*T as *U` TODO: explain unsized situation\n * `*T as integer`\n * `integer as *T`\n * `number as number`\n * `C-like-enum as integer`\n * `bool as integer`\n * `char as integer`\n * `u8 as char`\n * `&[T; n] as *const T`\n * `fn as *T` where `T: Sized`\n * `fn as integer`\n\nNote that lengths are not adjusted when casting raw slices -\n`*const [u16] as *const [u8]` creates a slice that only includes\nhalf of the original memory.\n\nCasting is not transitive, that is, even if `e as U1 as U2` is a valid\nexpression, `e as U2` is not necessarily so.\n\nFor numeric casts, there are quite a few cases to consider:\n\n* casting between two integers of the same size (e.g. i32 -> u32) is a no-op\n* casting from a larger integer to a smaller integer (e.g. u32 -> u8) will\n  truncate\n* casting from a smaller integer to a larger integer (e.g. u8 -> u32) will\n    * zero-extend if the source is unsigned\n    * sign-extend if the source is signed\n* casting from a float to an integer will round the float towards zero\n    * **[NOTE: currently this will cause Undefined Behavior if the rounded\n      value cannot be represented by the target integer type][float-int]**.\n      This includes Inf and NaN. This is a bug and will be fixed.\n* casting from an integer to float will produce the floating point\n  representation of the integer, rounded if necessary (rounding strategy\n  unspecified)\n* casting from an f32 to an f64 is perfect and lossless\n* casting from an f64 to an f32 will produce the closest possible value\n  (rounding strategy unspecified)\n    * **[NOTE: currently this will cause Undefined Behavior if the value\n      is finite but larger or smaller than the largest or smallest finite\n      value representable by f32][float-float]**. This is a bug and will\n      be fixed.\n\n\n[float-int]: https://github.com/rust-lang/rust/issues/10184\n[float-float]: https://github.com/rust-lang/rust/issues/15536\n"
  },
  {
    "path": "nomicon/checked-uninit.md",
    "content": "% Checked Uninitialized Memory\n\nLike C, all stack variables in Rust are uninitialized until a value is\nexplicitly assigned to them. Unlike C, Rust statically prevents you from ever\nreading them until you do:\n\n```rust,ignore\nfn main() {\n    let x: i32;\n    println!(\"{}\", x);\n}\n```\n\n```text\nsrc/main.rs:3:20: 3:21 error: use of possibly uninitialized variable: `x`\nsrc/main.rs:3     println!(\"{}\", x);\n                                 ^\n```\n\nThis is based off of a basic branch analysis: every branch must assign a value\nto `x` before it is first used. Interestingly, Rust doesn't require the variable\nto be mutable to perform a delayed initialization if every branch assigns\nexactly once. However the analysis does not take advantage of constant analysis\nor anything like that. So this compiles:\n\n```rust\nfn main() {\n    let x: i32;\n\n    if true {\n        x = 1;\n    } else {\n        x = 2;\n    }\n\n    println!(\"{}\", x);\n}\n```\n\nbut this doesn't:\n\n```rust,ignore\nfn main() {\n    let x: i32;\n    if true {\n        x = 1;\n    }\n    println!(\"{}\", x);\n}\n```\n\n```text\nsrc/main.rs:6:17: 6:18 error: use of possibly uninitialized variable: `x`\nsrc/main.rs:6   println!(\"{}\", x);\n```\n\nwhile this does:\n\n```rust\nfn main() {\n    let x: i32;\n    if true {\n        x = 1;\n        println!(\"{}\", x);\n    }\n    // Don't care that there are branches where it's not initialized\n    // since we don't use the value in those branches\n}\n```\n\nOf course, while the analysis doesn't consider actual values, it does\nhave a relatively sophisticated understanding of dependencies and control\nflow. For instance, this works:\n\n```rust\nlet x: i32;\n\nloop {\n    // Rust doesn't understand that this branch will be taken unconditionally,\n    // because it relies on actual values.\n    if true {\n        // But it does understand that it will only be taken once because\n        // we unconditionally break out of it. Therefore `x` doesn't\n        // need to be marked as mutable.\n        x = 0;\n        break;\n    }\n}\n// It also knows that it's impossible to get here without reaching the break.\n// And therefore that `x` must be initialized here!\nprintln!(\"{}\", x);\n```\n\nIf a value is moved out of a variable, that variable becomes logically\nuninitialized if the type of the value isn't Copy. That is:\n\n```rust\nfn main() {\n    let x = 0;\n    let y = Box::new(0);\n    let z1 = x; // x is still valid because i32 is Copy\n    let z2 = y; // y is now logically uninitialized because Box isn't Copy\n}\n```\n\nHowever reassigning `y` in this example *would* require `y` to be marked as\nmutable, as a Safe Rust program could observe that the value of `y` changed:\n\n```rust\nfn main() {\n    let mut y = Box::new(0);\n    let z = y; // y is now logically uninitialized because Box isn't Copy\n    y = Box::new(1); // reinitialize y\n}\n```\n\nOtherwise it's like `y` is a brand new variable.\n"
  },
  {
    "path": "nomicon/coercions.md",
    "content": "% Coercions\n\nTypes can implicitly be coerced to change in certain contexts. These changes are\ngenerally just *weakening* of types, largely focused around pointers and\nlifetimes. They mostly exist to make Rust \"just work\" in more cases, and are\nlargely harmless.\n\nHere's all the kinds of coercion:\n\nCoercion is allowed between the following types:\n\n* Transitivity: `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to\n  `T_3`\n* Pointer Weakening:\n    * `&mut T` to `&T`\n    * `*mut T` to `*const T`\n    * `&T` to `*const T`\n    * `&mut T` to `*mut T`\n* Unsizing: `T` to `U` if `T` implements `CoerceUnsized<U>`\n\n`CoerceUnsized<Pointer<U>> for Pointer<T> where T: Unsize<U>` is implemented\nfor all pointer types (including smart pointers like Box and Rc). Unsize is\nonly implemented automatically, and enables the following transformations:\n\n* `[T; n]` => `[T]`\n* `T` => `Trait` where `T: Trait`\n* `Foo<..., T, ...>` => `Foo<..., U, ...>` where:\n    * `T: Unsize<U>`\n    * `Foo` is a struct\n    * Only the last field of `Foo` has type `T`\n    * `T` is not part of the type of any other fields\n\nCoercions occur at a *coercion site*. Any location that is explicitly typed\nwill cause a coercion to its type. If inference is necessary, the coercion will\nnot be performed. Exhaustively, the coercion sites for an expression `e` to\ntype `U` are:\n\n* let statements, statics, and consts: `let x: U = e`\n* Arguments to functions: `takes_a_U(e)`\n* Any expression that will be returned: `fn foo() -> U { e }`\n* Struct literals: `Foo { some_u: e }`\n* Array literals: `let x: [U; 10] = [e, ..]`\n* Tuple literals: `let x: (U, ..) = (e, ..)`\n* The last expression in a block: `let x: U = { ..; e }`\n\nNote that we do not perform coercions when matching traits (except for\nreceivers, see below). If there is an impl for some type `U` and `T` coerces to\n`U`, that does not constitute an implementation for `T`. For example, the\nfollowing will not type check, even though it is OK to coerce `t` to `&T` and\nthere is an impl for `&T`:\n\n```rust,ignore\ntrait Trait {}\n\nfn foo<X: Trait>(t: X) {}\n\nimpl<'a> Trait for &'a i32 {}\n\n\nfn main() {\n    let t: &mut i32 = &mut 0;\n    foo(t);\n}\n```\n\n```text\n<anon>:10:5: 10:8 error: the trait bound `&mut i32 : Trait` is not satisfied [E0277]\n<anon>:10     foo(t);\n              ^~~\n```\n"
  },
  {
    "path": "nomicon/concurrency.md",
    "content": "% Concurrency and Parallelism\n\nRust as a language doesn't *really* have an opinion on how to do concurrency or\nparallelism. The standard library exposes OS threads and blocking sys-calls\nbecause everyone has those, and they're uniform enough that you can provide\nan abstraction over them in a relatively uncontroversial way. Message passing,\ngreen threads, and async APIs are all diverse enough that any abstraction over\nthem tends to involve trade-offs that we weren't willing to commit to for 1.0.\n\nHowever the way Rust models concurrency makes it relatively easy to design your own\nconcurrency paradigm as a library and have everyone else's code Just Work\nwith yours. Just require the right lifetimes and Send and Sync where appropriate\nand you're off to the races. Or rather, off to the... not... having... races.\n"
  },
  {
    "path": "nomicon/constructors.md",
    "content": "% Constructors\n\nThere is exactly one way to create an instance of a user-defined type: name it,\nand initialize all its fields at once:\n\n```rust\nstruct Foo {\n    a: u8,\n    b: u32,\n    c: bool,\n}\n\nenum Bar {\n    X(u32),\n    Y(bool),\n}\n\nstruct Unit;\n\nlet foo = Foo { a: 0, b: 1, c: false };\nlet bar = Bar::X(0);\nlet empty = Unit;\n```\n\nThat's it. Every other way you make an instance of a type is just calling a\ntotally vanilla function that does some stuff and eventually bottoms out to The\nOne True Constructor.\n\nUnlike C++, Rust does not come with a slew of built-in kinds of constructor.\nThere are no Copy, Default, Assignment, Move, or whatever constructors. The\nreasons for this are varied, but it largely boils down to Rust's philosophy of\n*being explicit*.\n\nMove constructors are meaningless in Rust because we don't enable types to\n\"care\" about their location in memory. Every type must be ready for it to be\nblindly memcopied to somewhere else in memory. This means pure on-the-stack-but-\nstill-movable intrusive linked lists are simply not happening in Rust (safely).\n\nAssignment and copy constructors similarly don't exist because move semantics\nare the only semantics in Rust. At most `x = y` just moves the bits of y into\nthe x variable. Rust does provide two facilities for providing C++'s copy-\noriented semantics: `Copy` and `Clone`. Clone is our moral equivalent of a copy\nconstructor, but it's never implicitly invoked. You have to explicitly call\n`clone` on an element you want to be cloned. Copy is a special case of Clone\nwhere the implementation is just \"copy the bits\". Copy types *are* implicitly\ncloned whenever they're moved, but because of the definition of Copy this just\nmeans not treating the old copy as uninitialized -- a no-op.\n\nWhile Rust provides a `Default` trait for specifying the moral equivalent of a\ndefault constructor, it's incredibly rare for this trait to be used. This is\nbecause variables [aren't implicitly initialized][uninit]. Default is basically\nonly useful for generic programming. In concrete contexts, a type will provide a\nstatic `new` method for any kind of \"default\" constructor. This has no relation\nto `new` in other languages and has no special meaning. It's just a naming\nconvention.\n\nTODO: talk about \"placement new\"?\n\n[uninit]: uninitialized.html\n"
  },
  {
    "path": "nomicon/conversions.md",
    "content": "% Type Conversions\n\nAt the end of the day, everything is just a pile of bits somewhere, and type\nsystems are just there to help us use those bits right. There are two common\nproblems with typing bits: needing to reinterpret those exact bits as a\ndifferent type, and needing to change the bits to have equivalent meaning for\na different type. Because Rust encourages encoding important properties in the\ntype system, these problems are incredibly pervasive. As such, Rust\nconsequently gives you several ways to solve them.\n\nFirst we'll look at the ways that Safe Rust gives you to reinterpret values.\nThe most trivial way to do this is to just destructure a value into its\nconstituent parts and then build a new type out of them. e.g.\n\n```rust\nstruct Foo {\n    x: u32,\n    y: u16,\n}\n\nstruct Bar {\n    a: u32,\n    b: u16,\n}\n\nfn reinterpret(foo: Foo) -> Bar {\n    let Foo { x, y } = foo;\n    Bar { a: x, b: y }\n}\n```\n\nBut this is, at best, annoying. For common conversions, Rust provides\nmore ergonomic alternatives.\n\n"
  },
  {
    "path": "nomicon/data.md",
    "content": "% Data Representation in Rust\n\nLow-level programming cares a lot about data layout. It's a big deal. It also\npervasively influences the rest of the language, so we're going to start by\ndigging into how data is represented in Rust.\n"
  },
  {
    "path": "nomicon/destructors.md",
    "content": "% Destructors\n\nWhat the language *does* provide is full-blown automatic destructors through the\n`Drop` trait, which provides the following method:\n\n```rust,ignore\nfn drop(&mut self);\n```\n\nThis method gives the type time to somehow finish what it was doing.\n\n**After `drop` is run, Rust will recursively try to drop all of the fields\nof `self`.**\n\nThis is a convenience feature so that you don't have to write \"destructor\nboilerplate\" to drop children. If a struct has no special logic for being\ndropped other than dropping its children, then it means `Drop` doesn't need to\nbe implemented at all!\n\n**There is no stable way to prevent this behavior in Rust 1.0.**\n\nNote that taking `&mut self` means that even if you could suppress recursive\nDrop, Rust will prevent you from e.g. moving fields out of self. For most types,\nthis is totally fine.\n\nFor instance, a custom implementation of `Box` might write `Drop` like this:\n\n```rust\n#![feature(alloc, heap_api, drop_in_place, unique)]\n\nextern crate alloc;\n\nuse std::ptr::{drop_in_place, Unique};\nuse std::mem;\n\nuse alloc::heap;\n\nstruct Box<T>{ ptr: Unique<T> }\n\nimpl<T> Drop for Box<T> {\n    fn drop(&mut self) {\n        unsafe {\n            drop_in_place(*self.ptr);\n            heap::deallocate((*self.ptr) as *mut u8,\n                             mem::size_of::<T>(),\n                             mem::align_of::<T>());\n        }\n    }\n}\n# fn main() {}\n```\n\nand this works fine because when Rust goes to drop the `ptr` field it just sees\na [Unique] that has no actual `Drop` implementation. Similarly nothing can\nuse-after-free the `ptr` because when drop exits, it becomes inaccessible.\n\nHowever this wouldn't work:\n\n```rust\n#![feature(alloc, heap_api, drop_in_place, unique)]\n\nextern crate alloc;\n\nuse std::ptr::{drop_in_place, Unique};\nuse std::mem;\n\nuse alloc::heap;\n\nstruct Box<T>{ ptr: Unique<T> }\n\nimpl<T> Drop for Box<T> {\n    fn drop(&mut self) {\n        unsafe {\n            drop_in_place(*self.ptr);\n            heap::deallocate((*self.ptr) as *mut u8,\n                             mem::size_of::<T>(),\n                             mem::align_of::<T>());\n        }\n    }\n}\n\nstruct SuperBox<T> { my_box: Box<T> }\n\nimpl<T> Drop for SuperBox<T> {\n    fn drop(&mut self) {\n        unsafe {\n            // Hyper-optimized: deallocate the box's contents for it\n            // without `drop`ing the contents\n            heap::deallocate((*self.my_box.ptr) as *mut u8,\n                             mem::size_of::<T>(),\n                             mem::align_of::<T>());\n        }\n    }\n}\n# fn main() {}\n```\n\nAfter we deallocate the `box`'s ptr in SuperBox's destructor, Rust will\nhappily proceed to tell the box to Drop itself and everything will blow up with\nuse-after-frees and double-frees.\n\nNote that the recursive drop behavior applies to all structs and enums\nregardless of whether they implement Drop. Therefore something like\n\n```rust\nstruct Boxy<T> {\n    data1: Box<T>,\n    data2: Box<T>,\n    info: u32,\n}\n```\n\nwill have its data1 and data2's fields destructors whenever it \"would\" be\ndropped, even though it itself doesn't implement Drop. We say that such a type\n*needs Drop*, even though it is not itself Drop.\n\nSimilarly,\n\n```rust\nenum Link {\n    Next(Box<Link>),\n    None,\n}\n```\n\nwill have its inner Box field dropped if and only if an instance stores the\nNext variant.\n\nIn general this works really nicely because you don't need to worry about\nadding/removing drops when you refactor your data layout. Still there's\ncertainly many valid usecases for needing to do trickier things with\ndestructors.\n\nThe classic safe solution to overriding recursive drop and allowing moving out\nof Self during `drop` is to use an Option:\n\n```rust\n#![feature(alloc, heap_api, drop_in_place, unique)]\n\nextern crate alloc;\n\nuse std::ptr::{drop_in_place, Unique};\nuse std::mem;\n\nuse alloc::heap;\n\nstruct Box<T>{ ptr: Unique<T> }\n\nimpl<T> Drop for Box<T> {\n    fn drop(&mut self) {\n        unsafe {\n            drop_in_place(*self.ptr);\n            heap::deallocate((*self.ptr) as *mut u8,\n                             mem::size_of::<T>(),\n                             mem::align_of::<T>());\n        }\n    }\n}\n\nstruct SuperBox<T> { my_box: Option<Box<T>> }\n\nimpl<T> Drop for SuperBox<T> {\n    fn drop(&mut self) {\n        unsafe {\n            // Hyper-optimized: deallocate the box's contents for it\n            // without `drop`ing the contents. Need to set the `box`\n            // field as `None` to prevent Rust from trying to Drop it.\n            let my_box = self.my_box.take().unwrap();\n            heap::deallocate((*my_box.ptr) as *mut u8,\n                             mem::size_of::<T>(),\n                             mem::align_of::<T>());\n            mem::forget(my_box);\n        }\n    }\n}\n# fn main() {}\n```\n\nHowever this has fairly odd semantics: you're saying that a field that *should*\nalways be Some *may* be None, just because that happens in the destructor. Of\ncourse this conversely makes a lot of sense: you can call arbitrary methods on\nself during the destructor, and this should prevent you from ever doing so after\ndeinitializing the field. Not that it will prevent you from producing any other\narbitrarily invalid state in there.\n\nOn balance this is an ok choice. Certainly what you should reach for by default.\nHowever, in the future we expect there to be a first-class way to announce that\na field shouldn't be automatically dropped.\n\n[Unique]: phantom-data.html\n"
  },
  {
    "path": "nomicon/dot-operator.md",
    "content": "% The Dot Operator\n\nThe dot operator will perform a lot of magic to convert types. It will perform\nauto-referencing, auto-dereferencing, and coercion until types match.\n\nTODO: steal information from http://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules/28552082#28552082\n"
  },
  {
    "path": "nomicon/drop-flags.md",
    "content": "% Drop Flags\n\nThe examples in the previous section introduce an interesting problem for Rust.\nWe have seen that it's possible to conditionally initialize, deinitialize, and\nreinitialize locations of memory totally safely. For Copy types, this isn't\nparticularly notable since they're just a random pile of bits. However types\nwith destructors are a different story: Rust needs to know whether to call a\ndestructor whenever a variable is assigned to, or a variable goes out of scope.\nHow can it do this with conditional initialization?\n\nNote that this is not a problem that all assignments need worry about. In\nparticular, assigning through a dereference unconditionally drops, and assigning\nin a `let` unconditionally doesn't drop:\n\n```\nlet mut x = Box::new(0); // let makes a fresh variable, so never need to drop\nlet y = &mut x;\n*y = Box::new(1); // Deref assumes the referent is initialized, so always drops\n```\n\nThis is only a problem when overwriting a previously initialized variable or\none of its subfields.\n\nIt turns out that Rust actually tracks whether a type should be dropped or not\n*at runtime*. As a variable becomes initialized and uninitialized, a *drop flag*\nfor that variable is toggled. When a variable might need to be dropped, this\nflag is evaluated to determine if it should be dropped.\n\nOf course, it is often the case that a value's initialization state can be\nstatically known at every point in the program. If this is the case, then the\ncompiler can theoretically generate more efficient code! For instance, straight-\nline code has such *static drop semantics*:\n\n```rust\nlet mut x = Box::new(0); // x was uninit; just overwrite.\nlet mut y = x;           // y was uninit; just overwrite and make x uninit.\nx = Box::new(0);         // x was uninit; just overwrite.\ny = x;                   // y was init; Drop y, overwrite it, and make x uninit!\n                         // y goes out of scope; y was init; Drop y!\n                         // x goes out of scope; x was uninit; do nothing.\n```\n\nSimilarly, branched code where all branches have the same behavior with respect\nto initialization has static drop semantics:\n\n```rust\n# let condition = true;\nlet mut x = Box::new(0);    // x was uninit; just overwrite.\nif condition {\n    drop(x)                 // x gets moved out; make x uninit.\n} else {\n    println!(\"{}\", x);\n    drop(x)                 // x gets moved out; make x uninit.\n}\nx = Box::new(0);            // x was uninit; just overwrite.\n                            // x goes out of scope; x was init; Drop x!\n```\n\nHowever code like this *requires* runtime information to correctly Drop:\n\n```rust\n# let condition = true;\nlet x;\nif condition {\n    x = Box::new(0);        // x was uninit; just overwrite.\n    println!(\"{}\", x);\n}\n                            // x goes out of scope; x might be uninit;\n                            // check the flag!\n```\n\nOf course, in this case it's trivial to retrieve static drop semantics:\n\n```rust\n# let condition = true;\nif condition {\n    let x = Box::new(0);\n    println!(\"{}\", x);\n}\n```\n\nAs of Rust 1.0, the drop flags are actually not-so-secretly stashed in a hidden\nfield of any type that implements Drop. Rust sets the drop flag by overwriting\nthe entire value with a particular bit pattern. This is pretty obviously Not\nThe Fastest and causes a bunch of trouble with optimizing code. It's legacy from\na time when you could do much more complex conditional initialization.\n\nAs such work is currently under way to move the flags out onto the stack frame\nwhere they more reasonably belong. Unfortunately, this work will take some time\nas it requires fairly substantial changes to the compiler.\n\nRegardless, Rust programs don't need to worry about uninitialized values on\nthe stack for correctness. Although they might care for performance. Thankfully,\nRust makes it easy to take control here! Uninitialized values are there, and\nyou can work with them in Safe Rust, but you're never in danger.\n"
  },
  {
    "path": "nomicon/dropck.md",
    "content": "% Drop Check\n\nWe have seen how lifetimes provide us some fairly simple rules for ensuring\nthat we never read dangling references. However up to this point we have only ever\ninteracted with the *outlives* relationship in an inclusive manner. That is,\nwhen we talked about `'a: 'b`, it was ok for `'a` to live *exactly* as long as\n`'b`. At first glance, this seems to be a meaningless distinction. Nothing ever\ngets dropped at the same time as another, right? This is why we used the\nfollowing desugaring of `let` statements:\n\n```rust,ignore\nlet x;\nlet y;\n```\n\n```rust,ignore\n{\n    let x;\n    {\n        let y;\n    }\n}\n```\n\nEach creates its own scope, clearly establishing that one drops before the\nother. However, what if we do the following?\n\n```rust,ignore\nlet (x, y) = (vec![], vec![]);\n```\n\nDoes either value strictly outlive the other? The answer is in fact *no*,\nneither value strictly outlives the other. Of course, one of x or y will be\ndropped before the other, but the actual order is not specified. Tuples aren't\nspecial in this regard; composite structures just don't guarantee their\ndestruction order as of Rust 1.0.\n\nWe *could* specify this for the fields of built-in composites like tuples and\nstructs. However, what about something like Vec? Vec has to manually drop its\nelements via pure-library code. In general, anything that implements Drop has\na chance to fiddle with its innards during its final death knell. Therefore\nthe compiler can't sufficiently reason about the actual destruction order\nof the contents of any type that implements Drop.\n\nSo why do we care? We care because if the type system isn't careful, it could\naccidentally make dangling pointers. Consider the following simple program:\n\n```rust\nstruct Inspector<'a>(&'a u8);\n\nfn main() {\n    let (inspector, days);\n    days = Box::new(1);\n    inspector = Inspector(&days);\n}\n```\n\nThis program is totally sound and compiles today. The fact that `days` does\nnot *strictly* outlive `inspector` doesn't matter. As long as the `inspector`\nis alive, so is days.\n\nHowever if we add a destructor, the program will no longer compile!\n\n```rust,ignore\nstruct Inspector<'a>(&'a u8);\n\nimpl<'a> Drop for Inspector<'a> {\n    fn drop(&mut self) {\n        println!(\"I was only {} days from retirement!\", self.0);\n    }\n}\n\nfn main() {\n    let (inspector, days);\n    days = Box::new(1);\n    inspector = Inspector(&days);\n    // Let's say `days` happens to get dropped first.\n    // Then when Inspector is dropped, it will try to read free'd memory!\n}\n```\n\n```text\n<anon>:12:28: 12:32 error: `days` does not live long enough\n<anon>:12     inspector = Inspector(&days);\n                                     ^~~~\n<anon>:9:11: 15:2 note: reference must be valid for the block at 9:10...\n<anon>:9 fn main() {\n<anon>:10     let (inspector, days);\n<anon>:11     days = Box::new(1);\n<anon>:12     inspector = Inspector(&days);\n<anon>:13     // Let's say `days` happens to get dropped first.\n<anon>:14     // Then when Inspector is dropped, it will try to read free'd memory!\n          ...\n<anon>:10:27: 15:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 10:26\n<anon>:10     let (inspector, days);\n<anon>:11     days = Box::new(1);\n<anon>:12     inspector = Inspector(&days);\n<anon>:13     // Let's say `days` happens to get dropped first.\n<anon>:14     // Then when Inspector is dropped, it will try to read free'd memory!\n<anon>:15 }\n```\n\nImplementing Drop lets the Inspector execute some arbitrary code during its\ndeath. This means it can potentially observe that types that are supposed to\nlive as long as it does actually were destroyed first.\n\nInterestingly, only generic types need to worry about this. If they aren't\ngeneric, then the only lifetimes they can harbor are `'static`, which will truly\nlive *forever*. This is why this problem is referred to as *sound generic drop*.\nSound generic drop is enforced by the *drop checker*. As of this writing, some\nof the finer details of how the drop checker validates types is totally up in\nthe air. However The Big Rule is the subtlety that we have focused on this whole\nsection:\n\n**For a generic type to soundly implement drop, its generics arguments must\nstrictly outlive it.**\n\nObeying this rule is (usually) necessary to satisfy the borrow\nchecker; obeying it is sufficient but not necessary to be\nsound. That is, if your type obeys this rule then it's definitely\nsound to drop.\n\nThe reason that it is not always necessary to satisfy the above rule\nis that some Drop implementations will not access borrowed data even\nthough their type gives them the capability for such access.\n\nFor example, this variant of the above `Inspector` example will never\naccessed borrowed data:\n\n```rust,ignore\nstruct Inspector<'a>(&'a u8, &'static str);\n\nimpl<'a> Drop for Inspector<'a> {\n    fn drop(&mut self) {\n        println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n    }\n}\n\nfn main() {\n    let (inspector, days);\n    days = Box::new(1);\n    inspector = Inspector(&days, \"gadget\");\n    // Let's say `days` happens to get dropped first.\n    // Even when Inspector is dropped, its destructor will not access the\n    // borrowed `days`.\n}\n```\n\nLikewise, this variant will also never access borrowed data:\n\n```rust,ignore\nuse std::fmt;\n\nstruct Inspector<T: fmt::Display>(T, &'static str);\n\nimpl<T: fmt::Display> Drop for Inspector<T> {\n    fn drop(&mut self) {\n        println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n    }\n}\n\nfn main() {\n    let (inspector, days): (Inspector<&u8>, Box<u8>);\n    days = Box::new(1);\n    inspector = Inspector(&days, \"gadget\");\n    // Let's say `days` happens to get dropped first.\n    // Even when Inspector is dropped, its destructor will not access the\n    // borrowed `days`.\n}\n```\n\nHowever, *both* of the above variants are rejected by the borrow\nchecker during the analysis of `fn main`, saying that `days` does not\nlive long enough.\n\nThe reason is that the borrow checking analysis of `main` does not\nknow about the internals of each Inspector's Drop implementation.  As\nfar as the borrow checker knows while it is analyzing `main`, the body\nof an inspector's destructor might access that borrowed data.\n\nTherefore, the drop checker forces all borrowed data in a value to\nstrictly outlive that value.\n\n# An Escape Hatch\n\nThe precise rules that govern drop checking may be less restrictive in\nthe future.\n\nThe current analysis is deliberately conservative and trivial; it forces all\nborrowed data in a value to outlive that value, which is certainly sound.\n\nFuture versions of the language may make the analysis more precise, to\nreduce the number of cases where sound code is rejected as unsafe.\nThis would help address cases such as the two Inspectors above that\nknow not to inspect during destruction.\n\nIn the meantime, there is an unstable attribute that one can use to\nassert (unsafely) that a generic type's destructor is *guaranteed* to\nnot access any expired data, even if its type gives it the capability\nto do so.\n\nThat attribute is called `unsafe_destructor_blind_to_params`.\nTo deploy it on the Inspector example from above, we would write:\n\n```rust,ignore\nstruct Inspector<'a>(&'a u8, &'static str);\n\nimpl<'a> Drop for Inspector<'a> {\n    #[unsafe_destructor_blind_to_params]\n    fn drop(&mut self) {\n        println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n    }\n}\n```\n\nThis attribute has the word `unsafe` in it because the compiler is not\nchecking the implicit assertion that no potentially expired data\n(e.g. `self.0` above) is accessed.\n\nIt is sometimes obvious that no such access can occur, like the case above.\nHowever, when dealing with a generic type parameter, such access can\noccur indirectly. Examples of such indirect access are:\n\n * invoking a callback,\n * via a trait method call.\n\n(Future changes to the language, such as impl specialization, may add\nother avenues for such indirect access.)\n\nHere is an example of invoking a callback:\n\n```rust,ignore\nstruct Inspector<T>(T, &'static str, Box<for <'r> fn(&'r T) -> String>);\n\nimpl<T> Drop for Inspector<T> {\n    fn drop(&mut self) {\n        // The `self.2` call could access a borrow e.g. if `T` is `&'a _`.\n        println!(\"Inspector({}, {}) unwittingly inspects expired data.\",\n                 (self.2)(&self.0), self.1);\n    }\n}\n```\n\nHere is an example of a trait method call:\n\n```rust,ignore\nuse std::fmt;\n\nstruct Inspector<T: fmt::Display>(T, &'static str);\n\nimpl<T: fmt::Display> Drop for Inspector<T> {\n    fn drop(&mut self) {\n        // There is a hidden call to `<T as Display>::fmt` below, which\n        // could access a borrow e.g. if `T` is `&'a _`\n        println!(\"Inspector({}, {}) unwittingly inspects expired data.\",\n                 self.0, self.1);\n    }\n}\n```\n\nAnd of course, all of these accesses could be further hidden within\nsome other method invoked by the destructor, rather than being written\ndirectly within it.\n\nIn all of the above cases where the `&'a u8` is accessed in the\ndestructor, adding the `#[unsafe_destructor_blind_to_params]`\nattribute makes the type vulnerable to misuse that the borrower\nchecker will not catch, inviting havoc. It is better to avoid adding\nthe attribute.\n\n# Is that all about drop checker?\n\nIt turns out that when writing unsafe code, we generally don't need to\nworry at all about doing the right thing for the drop checker. However there\nis one special case that you need to worry about, which we will look at in\nthe next section.\n\n"
  },
  {
    "path": "nomicon/exception-safety.md",
    "content": "% Exception Safety\n\nAlthough programs should use unwinding sparingly, there's a lot of code that\n*can* panic. If you unwrap a None, index out of bounds, or divide by 0, your\nprogram will panic. On debug builds, every arithmetic operation can panic\nif it overflows. Unless you are very careful and tightly control what code runs,\npretty much everything can unwind, and you need to be ready for it.\n\nBeing ready for unwinding is often referred to as *exception safety*\nin the broader programming world. In Rust, there are two levels of exception\nsafety that one may concern themselves with:\n\n* In unsafe code, we *must* be exception safe to the point of not violating\n  memory safety. We'll call this *minimal* exception safety.\n\n* In safe code, it is *good* to be exception safe to the point of your program\n  doing the right thing. We'll call this *maximal* exception safety.\n\nAs is the case in many places in Rust, Unsafe code must be ready to deal with\nbad Safe code when it comes to unwinding. Code that transiently creates\nunsound states must be careful that a panic does not cause that state to be\nused. Generally this means ensuring that only non-panicking code is run while\nthese states exist, or making a guard that cleans up the state in the case of\na panic. This does not necessarily mean that the state a panic witnesses is a\nfully coherent state. We need only guarantee that it's a *safe* state.\n\nMost Unsafe code is leaf-like, and therefore fairly easy to make exception-safe.\nIt controls all the code that runs, and most of that code can't panic. However\nit is not uncommon for Unsafe code to work with arrays of temporarily\nuninitialized data while repeatedly invoking caller-provided code. Such code\nneeds to be careful and consider exception safety.\n\n\n\n\n\n## Vec::push_all\n\n`Vec::push_all` is a temporary hack to get extending a Vec by a slice reliably\nefficient without specialization. Here's a simple implementation:\n\n```rust,ignore\nimpl<T: Clone> Vec<T> {\n    fn push_all(&mut self, to_push: &[T]) {\n        self.reserve(to_push.len());\n        unsafe {\n            // can't overflow because we just reserved this\n            self.set_len(self.len() + to_push.len());\n\n            for (i, x) in to_push.iter().enumerate() {\n                self.ptr().offset(i as isize).write(x.clone());\n            }\n        }\n    }\n}\n```\n\nWe bypass `push` in order to avoid redundant capacity and `len` checks on the\nVec that we definitely know has capacity. The logic is totally correct, except\nthere's a subtle problem with our code: it's not exception-safe! `set_len`,\n`offset`, and `write` are all fine; `clone` is the panic bomb we over-looked.\n\nClone is completely out of our control, and is totally free to panic. If it\ndoes, our function will exit early with the length of the Vec set too large. If\nthe Vec is looked at or dropped, uninitialized memory will be read!\n\nThe fix in this case is fairly simple. If we want to guarantee that the values\nwe *did* clone are dropped, we can set the `len` every loop iteration. If we\njust want to guarantee that uninitialized memory can't be observed, we can set\nthe `len` after the loop.\n\n\n\n\n\n## BinaryHeap::sift_up\n\nBubbling an element up a heap is a bit more complicated than extending a Vec.\nThe pseudocode is as follows:\n\n```text\nbubble_up(heap, index):\n    while index != 0 && heap[index] < heap[parent(index)]:\n        heap.swap(index, parent(index))\n        index = parent(index)\n\n```\n\nA literal transcription of this code to Rust is totally fine, but has an annoying\nperformance characteristic: the `self` element is swapped over and over again\nuselessly. We would rather have the following:\n\n```text\nbubble_up(heap, index):\n    let elem = heap[index]\n    while index != 0 && element < heap[parent(index)]:\n        heap[index] = heap[parent(index)]\n        index = parent(index)\n    heap[index] = elem\n```\n\nThis code ensures that each element is copied as little as possible (it is in\nfact necessary that elem be copied twice in general). However it now exposes\nsome exception safety trouble! At all times, there exists two copies of one\nvalue. If we panic in this function something will be double-dropped.\nUnfortunately, we also don't have full control of the code: that comparison is\nuser-defined!\n\nUnlike Vec, the fix isn't as easy here. One option is to break the user-defined\ncode and the unsafe code into two separate phases:\n\n```text\nbubble_up(heap, index):\n    let end_index = index;\n    while end_index != 0 && heap[end_index] < heap[parent(end_index)]:\n        end_index = parent(end_index)\n\n    let elem = heap[index]\n    while index != end_index:\n        heap[index] = heap[parent(index)]\n        index = parent(index)\n    heap[index] = elem\n```\n\nIf the user-defined code blows up, that's no problem anymore, because we haven't\nactually touched the state of the heap yet. Once we do start messing with the\nheap, we're working with only data and functions that we trust, so there's no\nconcern of panics.\n\nPerhaps you're not happy with this design. Surely it's cheating! And we have\nto do the complex heap traversal *twice*! Alright, let's bite the bullet. Let's\nintermix untrusted and unsafe code *for reals*.\n\nIf Rust had `try` and `finally` like in Java, we could do the following:\n\n```text\nbubble_up(heap, index):\n    let elem = heap[index]\n    try:\n        while index != 0 && element < heap[parent(index)]:\n            heap[index] = heap[parent(index)]\n            index = parent(index)\n    finally:\n        heap[index] = elem\n```\n\nThe basic idea is simple: if the comparison panics, we just toss the loose\nelement in the logically uninitialized index and bail out. Anyone who observes\nthe heap will see a potentially *inconsistent* heap, but at least it won't\ncause any double-drops! If the algorithm terminates normally, then this\noperation happens to coincide precisely with the how we finish up regardless.\n\nSadly, Rust has no such construct, so we're going to need to roll our own! The\nway to do this is to store the algorithm's state in a separate struct with a\ndestructor for the \"finally\" logic. Whether we panic or not, that destructor\nwill run and clean up after us.\n\n```rust,ignore\nstruct Hole<'a, T: 'a> {\n    data: &'a mut [T],\n    /// `elt` is always `Some` from new until drop.\n    elt: Option<T>,\n    pos: usize,\n}\n\nimpl<'a, T> Hole<'a, T> {\n    fn new(data: &'a mut [T], pos: usize) -> Self {\n        unsafe {\n            let elt = ptr::read(&data[pos]);\n            Hole {\n                data: data,\n                elt: Some(elt),\n                pos: pos,\n            }\n        }\n    }\n\n    fn pos(&self) -> usize { self.pos }\n\n    fn removed(&self) -> &T { self.elt.as_ref().unwrap() }\n\n    unsafe fn get(&self, index: usize) -> &T { &self.data[index] }\n\n    unsafe fn move_to(&mut self, index: usize) {\n        let index_ptr: *const _ = &self.data[index];\n        let hole_ptr = &mut self.data[self.pos];\n        ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);\n        self.pos = index;\n    }\n}\n\nimpl<'a, T> Drop for Hole<'a, T> {\n    fn drop(&mut self) {\n        // fill the hole again\n        unsafe {\n            let pos = self.pos;\n            ptr::write(&mut self.data[pos], self.elt.take().unwrap());\n        }\n    }\n}\n\nimpl<T: Ord> BinaryHeap<T> {\n    fn sift_up(&mut self, pos: usize) {\n        unsafe {\n            // Take out the value at `pos` and create a hole.\n            let mut hole = Hole::new(&mut self.data, pos);\n\n            while hole.pos() != 0 {\n                let parent = parent(hole.pos());\n                if hole.removed() <= hole.get(parent) { break }\n                hole.move_to(parent);\n            }\n            // Hole will be unconditionally filled here; panic or not!\n        }\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/exotic-sizes.md",
    "content": "% Exotically Sized Types\n\nMost of the time, we think in terms of types with a fixed, positive size. This\nis not always the case, however.\n\n\n\n\n\n# Dynamically Sized Types (DSTs)\n\nRust in fact supports Dynamically Sized Types (DSTs): types without a statically\nknown size or alignment. On the surface, this is a bit nonsensical: Rust *must*\nknow the size and alignment of something in order to correctly work with it! In\nthis regard, DSTs are not normal types. Due to their lack of a statically known\nsize, these types can only exist behind some kind of pointer. Any pointer to a\nDST consequently becomes a *fat* pointer consisting of the pointer and the\ninformation that \"completes\" them (more on this below).\n\nThere are two major DSTs exposed by the language: trait objects, and slices.\n\nA trait object represents some type that implements the traits it specifies.\nThe exact original type is *erased* in favor of runtime reflection\nwith a vtable containing all the information necessary to use the type.\nThis is the information that completes a trait object: a pointer to its vtable.\n\nA slice is simply a view into some contiguous storage -- typically an array or\n`Vec`. The information that completes a slice is just the number of elements\nit points to.\n\nStructs can actually store a single DST directly as their last field, but this\nmakes them a DST as well:\n\n```rust\n// Can't be stored on the stack directly\nstruct Foo {\n    info: u32,\n    data: [u8],\n}\n```\n\n**NOTE: [As of Rust 1.0 struct DSTs are broken if the last field has\na variable position based on its alignment][dst-issue].**\n\n\n\n\n\n# Zero Sized Types (ZSTs)\n\nRust actually allows types to be specified that occupy no space:\n\n```rust\nstruct Foo; // No fields = no size\n\n// All fields have no size = no size\nstruct Baz {\n    foo: Foo,\n    qux: (),      // empty tuple has no size\n    baz: [u8; 0], // empty array has no size\n}\n```\n\nOn their own, Zero Sized Types (ZSTs) are, for obvious reasons, pretty useless.\nHowever as with many curious layout choices in Rust, their potential is realized\nin a generic context: Rust largely understands that any operation that  produces\nor stores a ZST can be reduced to a no-op. First off, storing it  doesn't even\nmake sense -- it doesn't occupy any space. Also there's only one  value of that\ntype, so anything that loads it can just produce it from the  aether -- which is\nalso a no-op since it doesn't occupy any space.\n\nOne of the most extreme example's of this is Sets and Maps. Given a\n`Map<Key, Value>`, it is common to implement a `Set<Key>` as just a thin wrapper\naround `Map<Key, UselessJunk>`. In many languages, this would necessitate\nallocating space for UselessJunk and doing work to store and load UselessJunk\nonly to discard it. Proving this unnecessary would be a difficult analysis for\nthe compiler.\n\nHowever in Rust, we can just say that  `Set<Key> = Map<Key, ()>`. Now Rust\nstatically knows that every load and store is useless, and no allocation has any\nsize. The result is that the monomorphized code is basically a custom\nimplementation of a HashSet with none of the overhead that HashMap would have to\nsupport values.\n\nSafe code need not worry about ZSTs, but *unsafe* code must be careful about the\nconsequence of types with no size. In particular, pointer offsets are no-ops,\nand standard allocators (including jemalloc, the one used by default in Rust)\nmay return `nullptr` when a zero-sized allocation is requested, which is\nindistinguishable from out of memory.\n\n\n\n\n\n# Empty Types\n\nRust also enables types to be declared that *cannot even be instantiated*. These\ntypes can only be talked about at the type level, and never at the value level.\nEmpty types can be declared by specifying an enum with no variants:\n\n```rust\nenum Void {} // No variants = EMPTY\n```\n\nEmpty types are even more marginal than ZSTs. The primary motivating example for\nVoid types is type-level unreachability. For instance, suppose an API needs to\nreturn a Result in general, but a specific case actually is infallible. It's\nactually possible to communicate this at the type level by returning a\n`Result<T, Void>`. Consumers of the API can confidently unwrap such a Result\nknowing that it's *statically impossible* for this value to be an `Err`, as\nthis would require providing a value of type `Void`.\n\nIn principle, Rust can do some interesting analyses and optimizations based\non this fact. For instance, `Result<T, Void>` could be represented as just `T`,\nbecause the `Err` case doesn't actually exist. The following *could* also\ncompile:\n\n```rust,ignore\nenum Void {}\n\nlet res: Result<u32, Void> = Ok(0);\n\n// Err doesn't exist anymore, so Ok is actually irrefutable.\nlet Ok(num) = res;\n```\n\nBut neither of these tricks work today, so all Void types get you is\nthe ability to be confident that certain situations are statically impossible.\n\nOne final subtle detail about empty types is that raw pointers to them are\nactually valid to construct, but dereferencing them is Undefined Behavior\nbecause that doesn't actually make sense. That is, you could model C's `void *`\ntype with `*const Void`, but this doesn't necessarily gain anything over using\ne.g. `*const ()`, which *is* safe to randomly dereference.\n\n\n[dst-issue]: https://github.com/rust-lang/rust/issues/26403\n"
  },
  {
    "path": "nomicon/hrtb.md",
    "content": "% Higher-Rank Trait Bounds (HRTBs)\n\nRust's `Fn` traits are a little bit magic. For instance, we can write the\nfollowing code:\n\n```rust\nstruct Closure<F> {\n    data: (u8, u16),\n    func: F,\n}\n\nimpl<F> Closure<F>\n    where F: Fn(&(u8, u16)) -> &u8,\n{\n    fn call(&self) -> &u8 {\n        (self.func)(&self.data)\n    }\n}\n\nfn do_it(data: &(u8, u16)) -> &u8 { &data.0 }\n\nfn main() {\n    let clo = Closure { data: (0, 1), func: do_it };\n    println!(\"{}\", clo.call());\n}\n```\n\nIf we try to naively desugar this code in the same way that we did in the\nlifetimes section, we run into some trouble:\n\n```rust,ignore\nstruct Closure<F> {\n    data: (u8, u16),\n    func: F,\n}\n\nimpl<F> Closure<F>\n    // where F: Fn(&'??? (u8, u16)) -> &'??? u8,\n{\n    fn call<'a>(&'a self) -> &'a u8 {\n        (self.func)(&self.data)\n    }\n}\n\nfn do_it<'b>(data: &'b (u8, u16)) -> &'b u8 { &'b data.0 }\n\nfn main() {\n    'x: {\n        let clo = Closure { data: (0, 1), func: do_it };\n        println!(\"{}\", clo.call());\n    }\n}\n```\n\nHow on earth are we supposed to express the lifetimes on `F`'s trait bound? We\nneed to provide some lifetime there, but the lifetime we care about can't be\nnamed until we enter the body of `call`! Also, that isn't some fixed lifetime;\n`call` works with *any* lifetime `&self` happens to have at that point.\n\nThis job requires The Magic of Higher-Rank Trait Bounds (HRTBs). The way we\ndesugar this is as follows:\n\n```rust,ignore\nwhere for<'a> F: Fn(&'a (u8, u16)) -> &'a u8,\n```\n\n(Where `Fn(a, b, c) -> d` is itself just sugar for the unstable *real* `Fn`\ntrait)\n\n`for<'a>` can be read as \"for all choices of `'a`\", and basically produces an\n*infinite list* of trait bounds that F must satisfy. Intense. There aren't many\nplaces outside of the `Fn` traits where we encounter HRTBs, and even for\nthose we have a nice magic sugar for the common cases.\n"
  },
  {
    "path": "nomicon/leaking.md",
    "content": "% Leaking\n\nOwnership-based resource management is intended to simplify composition. You\nacquire resources when you create the object, and you release the resources when\nit gets destroyed. Since destruction is handled for you, it means you can't\nforget to release the resources, and it happens as soon as possible! Surely this\nis perfect and all of our problems are solved.\n\nEverything is terrible and we have new and exotic problems to try to solve.\n\nMany people like to believe that Rust eliminates resource leaks. In practice,\nthis is basically true. You would be surprised to see a Safe Rust program\nleak resources in an uncontrolled way.\n\nHowever from a theoretical perspective this is absolutely not the case, no\nmatter how you look at it. In the strictest sense, \"leaking\" is so abstract as\nto be unpreventable. It's quite trivial to initialize a collection at the start\nof a program, fill it with tons of objects with destructors, and then enter an\ninfinite event loop that never refers to it. The collection will sit around\nuselessly, holding on to its precious resources until the program terminates (at\nwhich point all those resources would have been reclaimed by the OS anyway).\n\nWe may consider a more restricted form of leak: failing to drop a value that is\nunreachable. Rust also doesn't prevent this. In fact Rust *has a function for\ndoing this*: `mem::forget`. This function consumes the value it is passed *and\nthen doesn't run its destructor*.\n\nIn the past `mem::forget` was marked as unsafe as a sort of lint against using\nit, since failing to call a destructor is generally not a well-behaved thing to\ndo (though useful for some special unsafe code). However this was generally\ndetermined to be an untenable stance to take: there are many ways to fail to\ncall a destructor in safe code. The most famous example is creating a cycle of\nreference-counted pointers using interior mutability.\n\nIt is reasonable for safe code to assume that destructor leaks do not happen, as\nany program that leaks destructors is probably wrong. However *unsafe* code\ncannot rely on destructors to be run in order to be safe. For most types this\ndoesn't matter: if you leak the destructor then the type is by definition\ninaccessible, so it doesn't matter, right? For instance, if you leak a `Box<u8>`\nthen you waste some memory but that's hardly going to violate memory-safety.\n\nHowever where we must be careful with destructor leaks are *proxy* types. These\nare types which manage access to a distinct object, but don't actually own it.\nProxy objects are quite rare. Proxy objects you'll need to care about are even\nrarer. However we'll focus on three interesting examples in the standard\nlibrary:\n\n* `vec::Drain`\n* `Rc`\n* `thread::scoped::JoinGuard`\n\n\n\n## Drain\n\n`drain` is a collections API that moves data out of the container without\nconsuming the container. This enables us to reuse the allocation of a `Vec`\nafter claiming ownership over all of its contents. It produces an iterator\n(Drain) that returns the contents of the Vec by-value.\n\nNow, consider Drain in the middle of iteration: some values have been moved out,\nand others haven't. This means that part of the Vec is now full of logically\nuninitialized data! We could backshift all the elements in the Vec every time we\nremove a value, but this would have pretty catastrophic performance\nconsequences.\n\nInstead, we would like Drain to fix the Vec's backing storage when it is\ndropped. It should run itself to completion, backshift any elements that weren't\nremoved (drain supports subranges), and then fix Vec's `len`. It's even\nunwinding-safe! Easy!\n\nNow consider the following:\n\n```rust,ignore\nlet mut vec = vec![Box::new(0); 4];\n\n{\n    // start draining, vec can no longer be accessed\n    let mut drainer = vec.drain(..);\n\n    // pull out two elements and immediately drop them\n    drainer.next();\n    drainer.next();\n\n    // get rid of drainer, but don't call its destructor\n    mem::forget(drainer);\n}\n\n// Oops, vec[0] was dropped, we're reading a pointer into free'd memory!\nprintln!(\"{}\", vec[0]);\n```\n\nThis is pretty clearly Not Good. Unfortunately, we're kind of stuck between a\nrock and a hard place: maintaining consistent state at every step has an\nenormous cost (and would negate any benefits of the API). Failing to maintain\nconsistent state gives us Undefined Behavior in safe code (making the API\nunsound).\n\nSo what can we do? Well, we can pick a trivially consistent state: set the Vec's\nlen to be 0 when we start the iteration, and fix it up if necessary in the\ndestructor. That way, if everything executes like normal we get the desired\nbehavior with minimal overhead. But if someone has the *audacity* to\nmem::forget us in the middle of the iteration, all that does is *leak even more*\n(and possibly leave the Vec in an unexpected but otherwise consistent state).\nSince we've accepted that mem::forget is safe, this is definitely safe. We call\nleaks causing more leaks a *leak amplification*.\n\n\n\n\n## Rc\n\nRc is an interesting case because at first glance it doesn't appear to be a\nproxy value at all. After all, it manages the data it points to, and dropping\nall the Rcs for a value will drop that value. Leaking an Rc doesn't seem like it\nwould be particularly dangerous. It will leave the refcount permanently\nincremented and prevent the data from being freed or dropped, but that seems\njust like Box, right?\n\nNope.\n\nLet's consider a simplified implementation of Rc:\n\n```rust,ignore\nstruct Rc<T> {\n    ptr: *mut RcBox<T>,\n}\n\nstruct RcBox<T> {\n    data: T,\n    ref_count: usize,\n}\n\nimpl<T> Rc<T> {\n    fn new(data: T) -> Self {\n        unsafe {\n            // Wouldn't it be nice if heap::allocate worked like this?\n            let ptr = heap::allocate::<RcBox<T>>();\n            ptr::write(ptr, RcBox {\n                data: data,\n                ref_count: 1,\n            });\n            Rc { ptr: ptr }\n        }\n    }\n\n    fn clone(&self) -> Self {\n        unsafe {\n            (*self.ptr).ref_count += 1;\n        }\n        Rc { ptr: self.ptr }\n    }\n}\n\nimpl<T> Drop for Rc<T> {\n    fn drop(&mut self) {\n        unsafe {\n            (*self.ptr).ref_count -= 1;\n            if (*self.ptr).ref_count == 0 {\n                // drop the data and then free it\n                ptr::read(self.ptr);\n                heap::deallocate(self.ptr);\n            }\n        }\n    }\n}\n```\n\nThis code contains an implicit and subtle assumption: `ref_count` can fit in a\n`usize`, because there can't be more than `usize::MAX` Rcs in memory. However\nthis itself assumes that the `ref_count` accurately reflects the number of Rcs\nin memory, which we know is false with `mem::forget`. Using `mem::forget` we can\noverflow the `ref_count`, and then get it down to 0 with outstanding Rcs. Then\nwe can happily use-after-free the inner data. Bad Bad Not Good.\n\nThis can be solved by just checking the `ref_count` and doing *something*. The\nstandard library's stance is to just abort, because your program has become\nhorribly degenerate. Also *oh my gosh* it's such a ridiculous corner case.\n\n\n\n\n## thread::scoped::JoinGuard\n\nThe thread::scoped API intends to allow threads to be spawned that reference\ndata on their parent's stack without any synchronization over that data by\nensuring the parent joins the thread before any of the shared data goes out\nof scope.\n\n```rust,ignore\npub fn scoped<'a, F>(f: F) -> JoinGuard<'a>\n    where F: FnOnce() + Send + 'a\n```\n\nHere `f` is some closure for the other thread to execute. Saying that\n`F: Send +'a` is saying that it closes over data that lives for `'a`, and it\neither owns that data or the data was Sync (implying `&data` is Send).\n\nBecause JoinGuard has a lifetime, it keeps all the data it closes over\nborrowed in the parent thread. This means the JoinGuard can't outlive\nthe data that the other thread is working on. When the JoinGuard *does* get\ndropped it blocks the parent thread, ensuring the child terminates before any\nof the closed-over data goes out of scope in the parent.\n\nUsage looked like:\n\n```rust,ignore\nlet mut data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n{\n    let guards = vec![];\n    for x in &mut data {\n        // Move the mutable reference into the closure, and execute\n        // it on a different thread. The closure has a lifetime bound\n        // by the lifetime of the mutable reference `x` we store in it.\n        // The guard that is returned is in turn assigned the lifetime\n        // of the closure, so it also mutably borrows `data` as `x` did.\n        // This means we cannot access `data` until the guard goes away.\n        let guard = thread::scoped(move || {\n            *x *= 2;\n        });\n        // store the thread's guard for later\n        guards.push(guard);\n    }\n    // All guards are dropped here, forcing the threads to join\n    // (this thread blocks here until the others terminate).\n    // Once the threads join, the borrow expires and the data becomes\n    // accessible again in this thread.\n}\n// data is definitely mutated here.\n```\n\nIn principle, this totally works! Rust's ownership system perfectly ensures it!\n...except it relies on a destructor being called to be safe.\n\n```rust,ignore\nlet mut data = Box::new(0);\n{\n    let guard = thread::scoped(|| {\n        // This is at best a data race. At worst, it's also a use-after-free.\n        *data += 1;\n    });\n    // Because the guard is forgotten, expiring the loan without blocking this\n    // thread.\n    mem::forget(guard);\n}\n// So the Box is dropped here while the scoped thread may or may not be trying\n// to access it.\n```\n\nDang. Here the destructor running was pretty fundamental to the API, and it had\nto be scrapped in favor of a completely different design.\n"
  },
  {
    "path": "nomicon/lifetime-elision.md",
    "content": "% Lifetime Elision\n\nIn order to make common patterns more ergonomic, Rust allows lifetimes to be\n*elided* in function signatures.\n\nA *lifetime position* is anywhere you can write a lifetime in a type:\n\n```rust,ignore\n&'a T\n&'a mut T\nT<'a>\n```\n\nLifetime positions can appear as either \"input\" or \"output\":\n\n* For `fn` definitions, input refers to the types of the formal arguments\n  in the `fn` definition, while output refers to\n  result types. So `fn foo(s: &str) -> (&str, &str)` has elided one lifetime in\n  input position and two lifetimes in output position.\n  Note that the input positions of a `fn` method definition do not\n  include the lifetimes that occur in the method's `impl` header\n  (nor lifetimes that occur in the trait header, for a default method).\n\n* In the future, it should be possible to elide `impl` headers in the same manner.\n\nElision rules are as follows:\n\n* Each elided lifetime in input position becomes a distinct lifetime\n  parameter.\n\n* If there is exactly one input lifetime position (elided or not), that lifetime\n  is assigned to *all* elided output lifetimes.\n\n* If there are multiple input lifetime positions, but one of them is `&self` or\n  `&mut self`, the lifetime of `self` is assigned to *all* elided output lifetimes.\n\n* Otherwise, it is an error to elide an output lifetime.\n\nExamples:\n\n```rust,ignore\nfn print(s: &str);                                      // elided\nfn print<'a>(s: &'a str);                               // expanded\n\nfn debug(lvl: uint, s: &str);                           // elided\nfn debug<'a>(lvl: uint, s: &'a str);                    // expanded\n\nfn substr(s: &str, until: uint) -> &str;                // elided\nfn substr<'a>(s: &'a str, until: uint) -> &'a str;      // expanded\n\nfn get_str() -> &str;                                   // ILLEGAL\n\nfn frob(s: &str, t: &str) -> &str;                      // ILLEGAL\n\nfn get_mut(&mut self) -> &mut T;                        // elided\nfn get_mut<'a>(&'a mut self) -> &'a mut T;              // expanded\n\nfn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command                  // elided\nfn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded\n\nfn new(buf: &mut [u8]) -> BufWriter;                    // elided\nfn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>          // expanded\n\n```\n"
  },
  {
    "path": "nomicon/lifetime-mismatch.md",
    "content": "% Limits of Lifetimes\n\nGiven the following code:\n\n```rust,ignore\nstruct Foo;\n\nimpl Foo {\n    fn mutate_and_share(&mut self) -> &Self { &*self }\n    fn share(&self) {}\n}\n\nfn main() {\n    let mut foo = Foo;\n    let loan = foo.mutate_and_share();\n    foo.share();\n}\n```\n\nOne might expect it to compile. We call `mutate_and_share`, which mutably borrows\n`foo` temporarily, but then returns only a shared reference. Therefore we\nwould expect `foo.share()` to succeed as `foo` shouldn't be mutably borrowed.\n\nHowever when we try to compile it:\n\n```text\n<anon>:11:5: 11:8 error: cannot borrow `foo` as immutable because it is also borrowed as mutable\n<anon>:11     foo.share();\n              ^~~\n<anon>:10:16: 10:19 note: previous borrow of `foo` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `foo` until the borrow ends\n<anon>:10     let loan = foo.mutate_and_share();\n                         ^~~\n<anon>:12:2: 12:2 note: previous borrow ends here\n<anon>:8 fn main() {\n<anon>:9     let mut foo = Foo;\n<anon>:10     let loan = foo.mutate_and_share();\n<anon>:11     foo.share();\n<anon>:12 }\n          ^\n```\n\nWhat happened? Well, we got the exact same reasoning as we did for\n[Example 2 in the previous section][ex2]. We desugar the program and we get\nthe following:\n\n```rust,ignore\nstruct Foo;\n\nimpl Foo {\n    fn mutate_and_share<'a>(&'a mut self) -> &'a Self { &'a *self }\n    fn share<'a>(&'a self) {}\n}\n\nfn main() {\n\t'b: {\n    \tlet mut foo: Foo = Foo;\n    \t'c: {\n    \t\tlet loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo);\n    \t\t'd: {\n    \t\t\tFoo::share::<'d>(&'d foo);\n    \t\t}\n    \t}\n    }\n}\n```\n\nThe lifetime system is forced to extend the `&mut foo` to have lifetime `'c`,\ndue to the lifetime of `loan` and mutate_and_share's signature. Then when we\ntry to call `share`, and it sees we're trying to alias that `&'c mut foo` and\nblows up in our face!\n\nThis program is clearly correct according to the reference semantics we actually\ncare about, but the lifetime system is too coarse-grained to handle that.\n\n\nTODO: other common problems? SEME regions stuff, mostly?\n\n\n\n\n[ex2]: lifetimes.html#example-aliasing-a-mutable-reference\n"
  },
  {
    "path": "nomicon/lifetimes.md",
    "content": "% Lifetimes\n\nRust enforces these rules through *lifetimes*. Lifetimes are effectively\njust names for scopes somewhere in the program. Each reference,\nand anything that contains a reference, is tagged with a lifetime specifying\nthe scope it's valid for.\n\nWithin a function body, Rust generally doesn't let you explicitly name the\nlifetimes involved. This is because it's generally not really necessary\nto talk about lifetimes in a local context; Rust has all the information and\ncan work out everything as optimally as possible. Many anonymous scopes and\ntemporaries that you would otherwise have to write are often introduced to\nmake your code Just Work.\n\nHowever once you cross the function boundary, you need to start talking about\nlifetimes. Lifetimes are denoted with an apostrophe: `'a`, `'static`. To dip\nour toes with lifetimes, we're going to pretend that we're actually allowed\nto label scopes with lifetimes, and desugar the examples from the start of\nthis chapter.\n\nOriginally, our examples made use of *aggressive* sugar -- high fructose corn\nsyrup even -- around scopes and lifetimes, because writing everything out\nexplicitly is *extremely noisy*. All Rust code relies on aggressive inference\nand elision of \"obvious\" things.\n\nOne particularly interesting piece of sugar is that each `let` statement implicitly\nintroduces a scope. For the most part, this doesn't really matter. However it\ndoes matter for variables that refer to each other. As a simple example, let's\ncompletely desugar this simple piece of Rust code:\n\n```rust\nlet x = 0;\nlet y = &x;\nlet z = &y;\n```\n\nThe borrow checker always tries to minimize the extent of a lifetime, so it will\nlikely desugar to the following:\n\n```rust,ignore\n// NOTE: `'a: {` and `&'b x` is not valid syntax!\n'a: {\n    let x: i32 = 0;\n    'b: {\n        // lifetime used is 'b because that's good enough.\n        let y: &'b i32 = &'b x;\n        'c: {\n            // ditto on 'c\n            let z: &'c &'b i32 = &'c y;\n        }\n    }\n}\n```\n\nWow. That's... awful. Let's all take a moment to thank Rust for making this easier.\n\nActually passing references to outer scopes will cause Rust to infer\na larger lifetime:\n\n```rust\nlet x = 0;\nlet z;\nlet y = &x;\nz = y;\n```\n\n```rust,ignore\n'a: {\n    let x: i32 = 0;\n    'b: {\n        let z: &'b i32;\n        'c: {\n            // Must use 'b here because this reference is\n            // being passed to that scope.\n            let y: &'b i32 = &'b x;\n            z = y;\n        }\n    }\n}\n```\n\n\n\n# Example: references that outlive referents\n\nAlright, let's look at some of those examples from before:\n\n```rust,ignore\nfn as_str(data: &u32) -> &str {\n    let s = format!(\"{}\", data);\n    &s\n}\n```\n\ndesugars to:\n\n```rust,ignore\nfn as_str<'a>(data: &'a u32) -> &'a str {\n    'b: {\n        let s = format!(\"{}\", data);\n        return &'a s;\n    }\n}\n```\n\nThis signature of `as_str` takes a reference to a u32 with *some* lifetime, and\npromises that it can produce a reference to a str that can live *just as long*.\nAlready we can see why this signature might be trouble. That basically implies\nthat we're going to find a str somewhere in the scope the reference\nto the u32 originated in, or somewhere *even earlier*. That's a bit of a tall\norder.\n\nWe then proceed to compute the string `s`, and return a reference to it. Since\nthe contract of our function says the reference must outlive `'a`, that's the\nlifetime we infer for the reference. Unfortunately, `s` was defined in the\nscope `'b`, so the only way this is sound is if `'b` contains `'a` -- which is\nclearly false since `'a` must contain the function call itself. We have therefore\ncreated a reference whose lifetime outlives its referent, which is *literally*\nthe first thing we said that references can't do. The compiler rightfully blows\nup in our face.\n\nTo make this more clear, we can expand the example:\n\n```rust,ignore\nfn as_str<'a>(data: &'a u32) -> &'a str {\n    'b: {\n        let s = format!(\"{}\", data);\n        return &'a s\n    }\n}\n\nfn main() {\n    'c: {\n        let x: u32 = 0;\n        'd: {\n            // An anonymous scope is introduced because the borrow does not\n            // need to last for the whole scope x is valid for. The return\n            // of as_str must find a str somewhere before this function\n            // call. Obviously not happening.\n            println!(\"{}\", as_str::<'d>(&'d x));\n        }\n    }\n}\n```\n\nShoot!\n\nOf course, the right way to write this function is as follows:\n\n```rust\nfn to_string(data: &u32) -> String {\n    format!(\"{}\", data)\n}\n```\n\nWe must produce an owned value inside the function to return it! The only way\nwe could have returned an `&'a str` would have been if it was in a field of the\n`&'a u32`, which is obviously not the case.\n\n(Actually we could have also just returned a string literal, which as a global\ncan be considered to reside at the bottom of the stack; though this limits\nour implementation *just a bit*.)\n\n\n\n\n\n# Example: aliasing a mutable reference\n\nHow about the other example:\n\n```rust,ignore\nlet mut data = vec![1, 2, 3];\nlet x = &data[0];\ndata.push(4);\nprintln!(\"{}\", x);\n```\n\n```rust,ignore\n'a: {\n    let mut data: Vec<i32> = vec![1, 2, 3];\n    'b: {\n        // 'b is as big as we need this borrow to be\n        // (just need to get to `println!`)\n        let x: &'b i32 = Index::index::<'b>(&'b data, 0);\n        'c: {\n            // Temporary scope because we don't need the\n            // &mut to last any longer.\n            Vec::push(&'c mut data, 4);\n        }\n        println!(\"{}\", x);\n    }\n}\n```\n\nThe problem here is a bit more subtle and interesting. We want Rust to\nreject this program for the following reason: We have a live shared reference `x`\nto a descendant of `data` when we try to take a mutable reference to `data`\nto `push`. This would create an aliased mutable reference, which would\nviolate the *second* rule of references.\n\nHowever this is *not at all* how Rust reasons that this program is bad. Rust\ndoesn't understand that `x` is a reference to a subpath of `data`. It doesn't\nunderstand Vec at all. What it *does* see is that `x` has to live for `'b` to\nbe printed. The signature of `Index::index` subsequently demands that the\nreference we take to `data` has to survive for `'b`. When we try to call `push`,\nit then sees us try to make an `&'c mut data`. Rust knows that `'c` is contained\nwithin `'b`, and rejects our program because the `&'b data` must still be live!\n\nHere we see that the lifetime system is much more coarse than the reference\nsemantics we're actually interested in preserving. For the most part, *that's\ntotally ok*, because it keeps us from spending all day explaining our program\nto the compiler. However it does mean that several programs that are totally\ncorrect with respect to Rust's *true* semantics are rejected because lifetimes\nare too dumb.\n"
  },
  {
    "path": "nomicon/meet-safe-and-unsafe.md",
    "content": "% Meet Safe and Unsafe\n\nProgrammers in safe \"high-level\" languages face a fundamental dilemma. On one\nhand, it would be *really* great to just say what you want and not worry about\nhow it's done. On the other hand, that can lead to unacceptably poor\nperformance. It may be necessary to drop down to less clear or idiomatic\npractices to get the performance characteristics you want. Or maybe you just\nthrow up your hands in disgust and decide to shell out to an implementation in\na less sugary-wonderful *unsafe* language.\n\nWorse, when you want to talk directly to the operating system, you *have* to\ntalk to an unsafe language: *C*. C is ever-present and unavoidable. It's the\nlingua-franca of the programming world.\nEven other safe languages generally expose C interfaces for the world at large!\nRegardless of why you're doing it, as soon as your program starts talking to\nC it stops being safe.\n\nWith that said, Rust is *totally* a safe programming language.\n\nWell, Rust *has* a safe programming language. Let's step back a bit.\n\nRust can be thought of as being composed of two programming languages: *Safe\nRust* and *Unsafe Rust*. Safe Rust is For Reals  Totally Safe. Unsafe Rust,\nunsurprisingly, is *not* For Reals Totally Safe.  In fact, Unsafe Rust lets you\ndo some really crazy unsafe things.\n\nSafe Rust is the *true* Rust programming language. If all you do is write Safe\nRust, you will never have to worry about type-safety or memory-safety. You will\nnever endure a null or dangling pointer, or any of that Undefined Behavior\nnonsense.\n\n*That's totally awesome.*\n\nThe standard library also gives you enough utilities out-of-the-box that you'll\nbe able to write awesome high-performance applications and libraries in pure\nidiomatic Safe Rust.\n\nBut maybe you want to talk to another language. Maybe you're writing a\nlow-level abstraction not exposed by the standard library. Maybe you're\n*writing* the standard library (which is written entirely in Rust). Maybe you\nneed to do something the type-system doesn't understand and just *frob some dang\nbits*. Maybe you need Unsafe Rust.\n\nUnsafe Rust is exactly like Safe Rust with all the same rules and semantics.\nHowever Unsafe Rust lets you do some *extra* things that are Definitely Not Safe.\n\nThe only things that are different in Unsafe Rust are that you can:\n\n* Dereference raw pointers\n* Call `unsafe` functions (including C functions, intrinsics, and the raw allocator)\n* Implement `unsafe` traits\n* Mutate statics\n\nThat's it. The reason these operations are relegated to Unsafe is that misusing\nany of these things will cause the ever dreaded Undefined Behavior. Invoking\nUndefined Behavior gives the compiler full rights to do arbitrarily bad things\nto your program. You definitely *should not* invoke Undefined Behavior.\n\nUnlike C, Undefined Behavior is pretty limited in scope in Rust. All the core\nlanguage cares about is preventing the following things:\n\n* Dereferencing null or dangling pointers\n* Reading [uninitialized memory]\n* Breaking the [pointer aliasing rules]\n* Producing invalid primitive values:\n    * dangling/null references\n    * a `bool` that isn't 0 or 1\n    * an undefined `enum` discriminant\n    * a `char` outside the ranges [0x0, 0xD7FF] and [0xE000, 0x10FFFF]\n    * A non-utf8 `str`\n* Unwinding into another language\n* Causing a [data race][race]\n\nThat's it. That's all the causes of Undefined Behavior baked into Rust. Of\ncourse, unsafe functions and traits are free to declare arbitrary other\nconstraints that a program must maintain to avoid Undefined Behavior. However,\ngenerally violations of these constraints will just transitively lead to one of\nthe above problems. Some additional constraints may also derive from compiler\nintrinsics that make special assumptions about how code can be optimized.\n\nRust is otherwise quite permissive with respect to other dubious operations.\nRust considers it \"safe\" to:\n\n* Deadlock\n* Have a [race condition][race]\n* Leak memory\n* Fail to call destructors\n* Overflow integers\n* Abort the program\n* Delete the production database\n\nHowever any program that actually manages to do such a thing is *probably*\nincorrect. Rust provides lots of tools to make these things rare, but\nthese problems are considered impractical to categorically prevent.\n\n[pointer aliasing rules]: references.html\n[uninitialized memory]: uninitialized.html\n[race]: races.html\n"
  },
  {
    "path": "nomicon/obrm.md",
    "content": "% The Perils Of Ownership Based Resource Management (OBRM)\n\nOBRM (AKA RAII: Resource Acquisition Is Initialization) is something you'll\ninteract with a lot in Rust. Especially if you use the standard library.\n\nRoughly speaking the pattern is as follows: to acquire a resource, you create an\nobject that manages it. To release the resource, you simply destroy the object,\nand it cleans up the resource for you. The most common \"resource\" this pattern\nmanages is simply *memory*. `Box`, `Rc`, and basically everything in\n`std::collections` is a convenience to enable correctly managing memory. This is\nparticularly important in Rust because we have no pervasive GC to rely on for\nmemory management. Which is the point, really: Rust is about control. However we\nare not limited to just memory. Pretty much every other system resource like a\nthread, file, or socket is exposed through this kind of API.\n"
  },
  {
    "path": "nomicon/other-reprs.md",
    "content": "% Alternative representations\n\nRust allows you to specify alternative data layout strategies from the default.\n\n\n\n\n# repr(C)\n\nThis is the most important `repr`. It has fairly simple intent: do what C does.\nThe order, size, and alignment of fields is exactly what you would expect from C\nor C++. Any type you expect to pass through an FFI boundary should have\n`repr(C)`, as C is the lingua-franca of the programming world. This is also\nnecessary to soundly do more elaborate tricks with data layout such as\nreinterpreting values as a different type.\n\nHowever, the interaction with Rust's more exotic data layout features must be\nkept in mind. Due to its dual purpose as \"for FFI\" and \"for layout control\",\n`repr(C)` can be applied to types that will be nonsensical or problematic if\npassed through the FFI boundary.\n\n* ZSTs are still zero-sized, even though this is not a standard behavior in\nC, and is explicitly contrary to the behavior of an empty type in C++, which\nstill consumes a byte of space.\n\n* DSTs, tuples, and tagged unions are not a concept in C and as such are never\nFFI safe.\n\n* Tuple structs are like structs with regards to `repr(C)`, as the only\n  difference from a struct is that the fields aren’t named.\n\n* **If the type would have any [drop flags], they will still be added**\n\n* This is equivalent to one of `repr(u*)` (see the next section) for enums. The\nchosen size is the default enum size for the target platform's C ABI. Note that\nenum representation in C is implementation defined, so this is really a \"best\nguess\". In particular, this may be incorrect when the C code of interest is\ncompiled with certain flags.\n\n\n\n# repr(u8), repr(u16), repr(u32), repr(u64)\n\nThese specify the size to make a C-like enum. If the discriminant overflows the\ninteger it has to fit in, it will produce a compile-time error. You can manually\nask Rust to allow this by setting the overflowing element to explicitly be 0.\nHowever Rust will not allow you to create an enum where two variants have the\nsame discriminant.\n\nOn non-C-like enums, this will inhibit certain optimizations like the null-\npointer optimization.\n\nThese reprs have no effect on a struct.\n\n\n\n\n# repr(packed)\n\n`repr(packed)` forces Rust to strip any padding, and only align the type to a\nbyte. This may improve the memory footprint, but will likely have other negative\nside-effects.\n\nIn particular, most architectures *strongly* prefer values to be aligned. This\nmay mean the unaligned loads are penalized (x86), or even fault (some ARM\nchips). For simple cases like directly loading or storing a packed field, the\ncompiler might be able to paper over alignment issues with shifts and masks.\nHowever if you take a reference to a packed field, it's unlikely that the\ncompiler will be able to emit code to avoid an unaligned load.\n\n**[As of Rust 1.0 this can cause undefined behavior.][ub loads]**\n\n`repr(packed)` is not to be used lightly. Unless you have extreme requirements,\nthis should not be used.\n\nThis repr is a modifier on `repr(C)` and `repr(rust)`.\n\n[drop flags]: drop-flags.html\n[ub loads]: https://github.com/rust-lang/rust/issues/27060\n"
  },
  {
    "path": "nomicon/ownership.md",
    "content": "% Ownership and Lifetimes\n\nOwnership is the breakout feature of Rust. It allows Rust to be completely\nmemory-safe and efficient, while avoiding garbage collection. Before getting\ninto the ownership system in detail, we will consider the motivation of this\ndesign.\n\nWe will assume that you accept that garbage collection (GC) is not always an\noptimal solution, and that it is desirable to manually manage memory in some\ncontexts. If you do not accept this, might I interest you in a different\nlanguage?\n\nRegardless of your feelings on GC, it is pretty clearly a *massive* boon to\nmaking code safe. You never have to worry about things going away *too soon*\n(although whether you still wanted to be pointing at that thing is a different\nissue...). This is a pervasive problem that C and C++ programs need to deal\nwith. Consider this simple mistake that all of us who have used a non-GC'd\nlanguage have made at one point:\n\n```rust,ignore\nfn as_str(data: &u32) -> &str {\n    // compute the string\n    let s = format!(\"{}\", data);\n\n    // OH NO! We returned a reference to something that\n    // exists only in this function!\n    // Dangling pointer! Use after free! Alas!\n    // (this does not compile in Rust)\n    &s\n}\n```\n\nThis is exactly what Rust's ownership system was built to solve.\nRust knows the scope in which the `&s` lives, and as such can prevent it from\nescaping. However this is a simple case that even a C compiler could plausibly\ncatch. Things get more complicated as code gets bigger and pointers get fed through\nvarious functions. Eventually, a C compiler will fall down and won't be able to\nperform sufficient escape analysis to prove your code unsound. It will consequently\nbe forced to accept your program on the assumption that it is correct.\n\nThis will never happen to Rust. It's up to the programmer to prove to the\ncompiler that everything is sound.\n\nOf course, Rust's story around ownership is much more complicated than just\nverifying that references don't escape the scope of their referent. That's\nbecause ensuring pointers are always valid is much more complicated than this.\nFor instance in this code,\n\n```rust,ignore\nlet mut data = vec![1, 2, 3];\n// get an internal reference\nlet x = &data[0];\n\n// OH NO! `push` causes the backing storage of `data` to be reallocated.\n// Dangling pointer! User after free! Alas!\n// (this does not compile in Rust)\ndata.push(4);\n\nprintln!(\"{}\", x);\n```\n\nnaive scope analysis would be insufficient to prevent this bug, because `data`\ndoes in fact live as long as we needed. However it was *changed* while we had\na reference into it. This is why Rust requires any references to freeze the\nreferent and its owners.\n\n"
  },
  {
    "path": "nomicon/phantom-data.md",
    "content": "% PhantomData\n\nWhen working with unsafe code, we can often end up in a situation where\ntypes or lifetimes are logically associated with a struct, but not actually\npart of a field. This most commonly occurs with lifetimes. For instance, the\n`Iter` for `&'a [T]` is (approximately) defined as follows:\n\n```rust,ignore\nstruct Iter<'a, T: 'a> {\n    ptr: *const T,\n    end: *const T,\n}\n```\n\nHowever because `'a` is unused within the struct's body, it's *unbounded*.\nBecause of the troubles this has historically caused, unbounded lifetimes and\ntypes are *forbidden* in struct definitions. Therefore we must somehow refer\nto these types in the body. Correctly doing this is necessary to have\ncorrect variance and drop checking.\n\nWe do this using `PhantomData`, which is a special marker type. `PhantomData`\nconsumes no space, but simulates a field of the given type for the purpose of\nstatic analysis. This was deemed to be less error-prone than explicitly telling\nthe type-system the kind of variance that you want, while also providing other\nuseful such as the information needed by drop check.\n\nIter logically contains a bunch of `&'a T`s, so this is exactly what we tell\nthe PhantomData to simulate:\n\n```\nuse std::marker;\n\nstruct Iter<'a, T: 'a> {\n    ptr: *const T,\n    end: *const T,\n    _marker: marker::PhantomData<&'a T>,\n}\n```\n\nand that's it. The lifetime will be bounded, and your iterator will be variant\nover `'a` and `T`. Everything Just Works.\n\nAnother important example is Vec, which is (approximately) defined as follows:\n\n```\nstruct Vec<T> {\n    data: *const T, // *const for variance!\n    len: usize,\n    cap: usize,\n}\n```\n\nUnlike the previous example it *appears* that everything is exactly as we\nwant. Every generic argument to Vec shows up in the at least one field.\nGood to go!\n\nNope.\n\nThe drop checker will generously determine that Vec<T> does not own any values\nof type T. This will in turn make it conclude that it doesn't need to worry\nabout Vec dropping any T's in its destructor for determining drop check\nsoundness. This will in turn allow people to create unsoundness using\nVec's destructor.\n\nIn order to tell dropck that we *do* own values of type T, and therefore may\ndrop some T's when *we* drop, we must add an extra PhantomData saying exactly\nthat:\n\n```\nuse std::marker;\n\nstruct Vec<T> {\n    data: *const T, // *const for covariance!\n    len: usize,\n    cap: usize,\n    _marker: marker::PhantomData<T>,\n}\n```\n\nRaw pointers that own an allocation is such a pervasive pattern that the\nstandard library made a utility for itself called `Unique<T>` which:\n\n* wraps a `*const T` for variance\n* includes a `PhantomData<T>`,\n* auto-derives Send/Sync as if T was contained\n* marks the pointer as NonZero for the null-pointer optimization\n\n"
  },
  {
    "path": "nomicon/poisoning.md",
    "content": "% Poisoning\n\nAlthough all unsafe code *must* ensure it has minimal exception safety, not all\ntypes ensure *maximal* exception safety. Even if the type does, your code may\nascribe additional meaning to it. For instance, an integer is certainly\nexception-safe, but has no semantics on its own. It's possible that code that\npanics could fail to correctly update the integer, producing an inconsistent\nprogram state.\n\nThis is *usually* fine, because anything that witnesses an exception is about\nto get destroyed. For instance, if you send a Vec to another thread and that\nthread panics, it doesn't matter if the Vec is in a weird state. It will be\ndropped and go away forever. However some types are especially good at smuggling\nvalues across the panic boundary.\n\nThese types may choose to explicitly *poison* themselves if they witness a panic.\nPoisoning doesn't entail anything in particular. Generally it just means\npreventing normal usage from proceeding. The most notable example of this is the\nstandard library's Mutex type. A Mutex will poison itself if one of its\nMutexGuards (the thing it returns when a lock is obtained) is dropped during a\npanic. Any future attempts to lock the Mutex will return an `Err` or panic.\n\nMutex poisons not for true safety in the sense that Rust normally cares about. It\npoisons as a safety-guard against blindly using the data that comes out of a Mutex\nthat has witnessed a panic while locked. The data in such a Mutex was likely in the\nmiddle of being modified, and as such may be in an inconsistent or incomplete state.\nIt is important to note that one cannot violate memory safety with such a type\nif it is correctly written. After all, it must be minimally exception-safe!\n\nHowever if the Mutex contained, say, a BinaryHeap that does not actually have the\nheap property, it's unlikely that any code that uses it will do\nwhat the author intended. As such, the program should not proceed normally.\nStill, if you're double-plus-sure that you can do *something* with the value,\nthe Mutex exposes a method to get the lock anyway. It *is* safe, after all.\nJust maybe nonsense.\n"
  },
  {
    "path": "nomicon/races.md",
    "content": "% Data Races and Race Conditions\n\nSafe Rust guarantees an absence of data races, which are defined as:\n\n* two or more threads concurrently accessing a location of memory\n* one of them is a write\n* one of them is unsynchronized\n\nA data race has Undefined Behavior, and is therefore impossible to perform\nin Safe Rust. Data races are *mostly* prevented through rust's ownership system:\nit's impossible to alias a mutable reference, so it's impossible to perform a\ndata race. Interior mutability makes this more complicated, which is largely why\nwe have the Send and Sync traits (see below).\n\n**However Rust does not prevent general race conditions.**\n\nThis is pretty fundamentally impossible, and probably honestly undesirable. Your\nhardware is racy, your OS is racy, the other programs on your computer are racy,\nand the world this all runs in is racy. Any system that could genuinely claim to\nprevent *all* race conditions would be pretty awful to use, if not just\nincorrect.\n\nSo it's perfectly \"fine\" for a Safe Rust program to get deadlocked or do\nsomething incredibly stupid with incorrect synchronization. Obviously such a\nprogram isn't very good, but Rust can only hold your hand so far. Still, a\nrace condition can't violate memory safety in a Rust program on\nits own. Only in conjunction with some other unsafe code can a race condition\nactually violate memory safety. For instance:\n\n```rust,no_run\nuse std::thread;\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nlet data = vec![1, 2, 3, 4];\n// Arc so that the memory the AtomicUsize is stored in still exists for\n// the other thread to increment, even if we completely finish executing\n// before it. Rust won't compile the program without it, because of the\n// lifetime requirements of thread::spawn!\nlet idx = Arc::new(AtomicUsize::new(0));\nlet other_idx = idx.clone();\n\n// `move` captures other_idx by-value, moving it into this thread\nthread::spawn(move || {\n    // It's ok to mutate idx because this value\n    // is an atomic, so it can't cause a Data Race.\n    other_idx.fetch_add(10, Ordering::SeqCst);\n});\n\n// Index with the value loaded from the atomic. This is safe because we\n// read the atomic memory only once, and then pass a copy of that value\n// to the Vec's indexing implementation. This indexing will be correctly\n// bounds checked, and there's no chance of the value getting changed\n// in the middle. However our program may panic if the thread we spawned\n// managed to increment before this ran. A race condition because correct\n// program execution (panicking is rarely correct) depends on order of\n// thread execution.\nprintln!(\"{}\", data[idx.load(Ordering::SeqCst)]);\n```\n\n```rust,no_run\nuse std::thread;\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nlet data = vec![1, 2, 3, 4];\n\nlet idx = Arc::new(AtomicUsize::new(0));\nlet other_idx = idx.clone();\n\n// `move` captures other_idx by-value, moving it into this thread\nthread::spawn(move || {\n    // It's ok to mutate idx because this value\n    // is an atomic, so it can't cause a Data Race.\n    other_idx.fetch_add(10, Ordering::SeqCst);\n});\n\nif idx.load(Ordering::SeqCst) < data.len() {\n    unsafe {\n        // Incorrectly loading the idx after we did the bounds check.\n        // It could have changed. This is a race condition, *and dangerous*\n        // because we decided to do `get_unchecked`, which is `unsafe`.\n        println!(\"{}\", data.get_unchecked(idx.load(Ordering::SeqCst)));\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/references.md",
    "content": "% References\n\nThis section gives a high-level view of the memory model that *all* Rust\nprograms must satisfy to be correct. Safe code is statically verified\nto obey this model by the borrow checker. Unsafe code may go above\nand beyond the borrow checker while still satisfying this model. The borrow\nchecker may also be extended to allow more programs to compile, as long as\nthis more fundamental model is satisfied.\n\nThere are two kinds of reference:\n\n* Shared reference: `&`\n* Mutable reference: `&mut`\n\nWhich obey the following rules:\n\n* A reference cannot outlive its referent\n* A mutable reference cannot be aliased\n\nThat's it. That's the whole model. Of course, we should probably define\nwhat *aliased* means. To define aliasing, we must define the notion of\n*paths* and *liveness*.\n\n\n**NOTE: The model that follows is generally agreed to be dubious and have\nissues. It's ok-ish as an intuitive model, but fails to capture the desired\nsemantics. We leave this here to be able to use notions introduced here in later\nsections. This will be significantly changed in the future. TODO: do that.**\n\n\n# Paths\n\nIf all Rust had were values (no pointers), then every value would be uniquely\nowned by a variable or composite structure. From this we naturally derive a\n*tree* of ownership. The stack itself is the root of the tree, with every\nvariable as its direct children. Each variable's direct children would be their\nfields (if any), and so on.\n\nFrom this view, every value in Rust has a unique *path* in the tree of\nownership. Of particular interest are *ancestors* and *descendants*: if `x` owns\n`y`, then `x` is an ancestor of `y`, and `y` is a descendant of `x`. Note\nthat this is an inclusive relationship: `x` is a descendant and ancestor of\nitself.\n\nWe can then define references as simply *names* for paths. When you create a\nreference, you're declaring that an ownership path exists to this address\nof memory.\n\nTragically, plenty of data doesn't reside on the stack, and we must also\naccommodate this. Globals and thread-locals are simple enough to model as\nresiding at the bottom of the stack (though we must be careful with mutable\nglobals). Data on the heap poses a different problem.\n\nIf all Rust had on the heap was data uniquely owned by a pointer on the stack,\nthen we could just treat such a pointer as a struct that owns the value on the\nheap. Box, Vec, String, and HashMap, are examples of types which uniquely\nown data on the heap.\n\nUnfortunately, data on the heap is not *always* uniquely owned. Rc for instance\nintroduces a notion of *shared* ownership. Shared ownership of a value means\nthere is no unique path to it. A value with no unique path limits what we can do\nwith it.\n\nIn general, only shared references can be created to non-unique paths. However\nmechanisms which ensure mutual exclusion may establish One True Owner\ntemporarily, establishing a unique path to that value (and therefore all\nits children). If this is done, the value may be mutated. In particular, a\nmutable reference can be taken.\n\nThe most common way to establish such a path is through *interior mutability*,\nin contrast to the *inherited mutability* that everything in Rust normally uses.\nCell, RefCell, Mutex, and RWLock are all examples of interior mutability types.\nThese types provide exclusive access through runtime restrictions.\n\nAn interesting case of this effect is Rc itself: if an Rc has refcount 1,\nthen it is safe to mutate or even move its internals. Note however that the\nrefcount itself uses interior mutability.\n\nIn order to correctly communicate to the type system that a variable or field of\na struct can have interior mutability, it must be wrapped in an UnsafeCell. This\ndoes not in itself make it safe to perform interior mutability operations on\nthat value. You still must yourself ensure that mutual exclusion is upheld.\n\n\n\n\n# Liveness\n\nNote: Liveness is not the same thing as a *lifetime*, which will be explained\nin detail in the next section of this chapter.\n\nRoughly, a reference is *live* at some point in a program if it can be\ndereferenced. Shared references are always live unless they are literally\nunreachable (for instance, they reside in freed or leaked memory). Mutable\nreferences can be reachable but *not* live through the process of *reborrowing*.\n\nA mutable reference can be reborrowed to either a shared or mutable reference to\none of its descendants. A reborrowed reference will only be live again once all\nreborrows derived from it expire. For instance, a mutable reference can be\nreborrowed to point to a field of its referent:\n\n```rust\nlet x = &mut (1, 2);\n{\n    // reborrow x to a subfield\n    let y = &mut x.0;\n    // y is now live, but x isn't\n    *y = 3;\n}\n// y goes out of scope, so x is live again\n*x = (5, 7);\n```\n\nIt is also possible to reborrow into *multiple* mutable references, as long as\nthey are *disjoint*: no reference is an ancestor of another. Rust\nexplicitly enables this to be done with disjoint struct fields, because\ndisjointness can be statically proven:\n\n```rust\nlet x = &mut (1, 2);\n{\n    // reborrow x to two disjoint subfields\n    let y = &mut x.0;\n    let z = &mut x.1;\n\n    // y and z are now live, but x isn't\n    *y = 3;\n    *z = 4;\n}\n// y and z go out of scope, so x is live again\n*x = (5, 7);\n```\n\nHowever it's often the case that Rust isn't sufficiently smart to prove that\nmultiple borrows are disjoint. *This does not mean it is fundamentally illegal\nto make such a borrow*, just that Rust isn't as smart as you want.\n\nTo simplify things, we can model variables as a fake type of reference: *owned*\nreferences. Owned references have much the same semantics as mutable references:\nthey can be re-borrowed in a mutable or shared manner, which makes them no\nlonger live. Live owned references have the unique property that they can be\nmoved out of (though mutable references *can* be swapped out of). This power is\nonly given to *live* owned references because moving its referent would of\ncourse invalidate all outstanding references prematurely.\n\nAs a local lint against inappropriate mutation, only variables that are marked\nas `mut` can be borrowed mutably.\n\nIt is interesting to note that Box behaves exactly like an owned reference. It\ncan be moved out of, and Rust understands it sufficiently to reason about its\npaths like a normal variable.\n\n\n\n\n# Aliasing\n\nWith liveness and paths defined, we can now properly define *aliasing*:\n\n**A mutable reference is aliased if there exists another live reference to one\nof its ancestors or descendants.**\n\n(If you prefer, you may also say the two live references alias *each other*.\nThis has no semantic consequences, but is probably a more useful notion when\nverifying the soundness of a construct.)\n\nThat's it. Super simple right? Except for the fact that it took us two pages to\ndefine all of the terms in that definition. You know: Super. Simple.\n\nActually it's a bit more complicated than that. In addition to references, Rust\nhas *raw pointers*: `*const T` and `*mut T`. Raw pointers have no inherent\nownership or aliasing semantics. As a result, Rust makes absolutely no effort to\ntrack that they are used correctly, and they are wildly unsafe.\n\n**It is an open question to what degree raw pointers have alias semantics.\nHowever it is important for these definitions to be sound that the existence of\na raw pointer does not imply some kind of live path.**\n"
  },
  {
    "path": "nomicon/repr-rust.md",
    "content": "% repr(Rust)\n\nFirst and foremost, all types have an alignment specified in bytes. The\nalignment of a type specifies what addresses are valid to store the value at. A\nvalue of alignment `n` must only be stored at an address that is a multiple of\n`n`. So alignment 2 means you must be stored at an even address, and 1 means\nthat you can be stored anywhere. Alignment is at least 1, and always a power of\n2. Most primitives are generally aligned to their size, although this is\nplatform-specific behavior. In particular, on x86 `u64` and `f64` may be only\naligned to 32 bits.\n\nA type's size must always be a multiple of its alignment. This ensures that an\narray of that type may always be indexed by offsetting by a multiple of its\nsize. Note that the size and alignment of a type may not be known\nstatically in the case of [dynamically sized types][dst].\n\nRust gives you the following ways to lay out composite data:\n\n* structs (named product types)\n* tuples (anonymous product types)\n* arrays (homogeneous product types)\n* enums (named sum types -- tagged unions)\n\nAn enum is said to be *C-like* if none of its variants have associated data.\n\nComposite structures will have an alignment equal to the maximum\nof their fields' alignment. Rust will consequently insert padding where\nnecessary to ensure that all fields are properly aligned and that the overall\ntype's size is a multiple of its alignment. For instance:\n\n```rust\nstruct A {\n    a: u8,\n    b: u32,\n    c: u16,\n}\n```\n\nwill be 32-bit aligned on an architecture that aligns these primitives to their\nrespective sizes. The whole struct will therefore have a size that is a multiple\nof 32-bits. It will potentially become:\n\n```rust\nstruct A {\n    a: u8,\n    _pad1: [u8; 3], // to align `b`\n    b: u32,\n    c: u16,\n    _pad2: [u8; 2], // to make overall size multiple of 4\n}\n```\n\nThere is *no indirection* for these types; all data is stored within the struct,\nas you would expect in C. However with the exception of arrays (which are\ndensely packed and in-order), the layout of data is not by default specified in\nRust. Given the two following struct definitions:\n\n```rust\nstruct A {\n    a: i32,\n    b: u64,\n}\n\nstruct B {\n    a: i32,\n    b: u64,\n}\n```\n\nRust *does* guarantee that two instances of A have their data laid out in\nexactly the same way. However Rust *does not* currently guarantee that an\ninstance of A has the same field ordering or padding as an instance of B, though\nin practice there's no reason why they wouldn't.\n\nWith A and B as written, this point would seem to be pedantic, but several other\nfeatures of Rust make it desirable for the language to play with data layout in\ncomplex ways.\n\nFor instance, consider this struct:\n\n```rust\nstruct Foo<T, U> {\n    count: u16,\n    data1: T,\n    data2: U,\n}\n```\n\nNow consider the monomorphizations of `Foo<u32, u16>` and `Foo<u16, u32>`. If\nRust lays out the fields in the order specified, we expect it to pad the\nvalues in the struct to satisfy their alignment requirements. So if Rust\ndidn't reorder fields, we would expect it to produce the following:\n\n```rust,ignore\nstruct Foo<u16, u32> {\n    count: u16,\n    data1: u16,\n    data2: u32,\n}\n\nstruct Foo<u32, u16> {\n    count: u16,\n    _pad1: u16,\n    data1: u32,\n    data2: u16,\n    _pad2: u16,\n}\n```\n\nThe latter case quite simply wastes space. An optimal use of space therefore\nrequires different monomorphizations to have *different field orderings*.\n\n**Note: this is a hypothetical optimization that is not yet implemented in Rust\n1.0**\n\nEnums make this consideration even more complicated. Naively, an enum such as:\n\n```rust\nenum Foo {\n    A(u32),\n    B(u64),\n    C(u8),\n}\n```\n\nwould be laid out as:\n\n```rust\nstruct FooRepr {\n    data: u64, // this is either a u64, u32, or u8 based on `tag`\n    tag: u8,   // 0 = A, 1 = B, 2 = C\n}\n```\n\nAnd indeed this is approximately how it would be laid out in general (modulo the\nsize and position of `tag`).\n\nHowever there are several cases where such a representation is inefficient. The\nclassic case of this is Rust's \"null pointer optimization\": an enum consisting\nof a single outer unit variant (e.g. `None`) and a (potentially nested) non-\nnullable pointer variant (e.g. `&T`) makes the tag unnecessary, because a null\npointer value can safely be interpreted to mean that the unit variant is chosen\ninstead. The net result is that, for example, `size_of::<Option<&T>>() ==\nsize_of::<&T>()`.\n\nThere are many types in Rust that are, or contain, non-nullable pointers such as\n`Box<T>`, `Vec<T>`, `String`, `&T`, and `&mut T`. Similarly, one can imagine\nnested enums pooling their tags into a single discriminant, as they are by\ndefinition known to have a limited range of valid values. In principle enums could\nuse fairly elaborate algorithms to cache bits throughout nested types with\nspecial constrained representations. As such it is *especially* desirable that\nwe leave enum layout unspecified today.\n\n[dst]: exotic-sizes.html#dynamically-sized-types-dsts\n"
  },
  {
    "path": "nomicon/safe-unsafe-meaning.md",
    "content": "% How Safe and Unsafe Interact\n\nSo what's the relationship between Safe and Unsafe Rust? How do they interact?\n\nRust models the separation between Safe and Unsafe Rust with the `unsafe`\nkeyword, which can be thought as a sort of *foreign function interface* (FFI)\nbetween Safe and Unsafe Rust. This is the magic behind why we can say Safe Rust\nis a safe language: all the scary unsafe bits are relegated exclusively to FFI\n*just like every other safe language*.\n\nHowever because one language is a subset of the other, the two can be cleanly\nintermixed as long as the boundary between Safe and Unsafe Rust is denoted with\nthe `unsafe` keyword. No need to write headers, initialize runtimes, or any of\nthat other FFI boiler-plate.\n\nThere are several places `unsafe` can appear in Rust today, which can largely be\ngrouped into two categories:\n\n* There are unchecked contracts here. To declare you understand this, I require\nyou to write `unsafe` elsewhere:\n    * On functions, `unsafe` is declaring the function to be unsafe to call.\n      Users of the function must check the documentation to determine what this\n      means, and then have to write `unsafe` somewhere to identify that they're\n      aware of the danger.\n    * On trait declarations, `unsafe` is declaring that *implementing* the trait\n      is an unsafe operation, as it has contracts that other unsafe code is free\n      to trust blindly. (More on this below.)\n\n* I am declaring that I have, to the best of my knowledge, adhered to the\nunchecked contracts:\n    * On trait implementations, `unsafe` is declaring that the contract of the\n      `unsafe` trait has been upheld.\n    * On blocks, `unsafe` is declaring any unsafety from an unsafe\n      operation within to be handled, and therefore the parent function is safe.\n\nThere is also `#[unsafe_no_drop_flag]`, which is a special case that exists for\nhistorical reasons and is in the process of being phased out. See the section on\n[drop flags] for details.\n\nSome examples of unsafe functions:\n\n* `slice::get_unchecked` will perform unchecked indexing, allowing memory\n  safety to be freely violated.\n* every raw pointer to sized type has intrinsic `offset` method that invokes\n  Undefined Behavior if it is not \"in bounds\" as defined by LLVM.\n* `mem::transmute` reinterprets some value as having the given type,\n  bypassing type safety in arbitrary ways. (see [conversions] for details)\n* All FFI functions are `unsafe` because they can do arbitrary things.\n  C being an obvious culprit, but generally any language can do something\n  that Rust isn't happy about.\n\nAs of Rust 1.0 there are exactly two unsafe traits:\n\n* `Send` is a marker trait (it has no actual API) that promises implementors\n  are safe to send (move) to another thread.\n* `Sync` is a marker trait that promises that threads can safely share\n  implementors through a shared reference.\n\nThe need for unsafe traits boils down to the fundamental property of safe code:\n\n**No matter how completely awful Safe code is, it can't cause Undefined\nBehavior.**\n\nThis means that Unsafe Rust, **the royal vanguard of Undefined Behavior**, has to be\n*super paranoid* about generic safe code. To be clear, Unsafe Rust is totally free to trust\nspecific safe code. Anything else would degenerate into infinite spirals of\nparanoid despair. In particular it's generally regarded as ok to trust the standard library\nto be correct. `std` is effectively an extension of the language, and you\nreally just have to trust the language. If `std` fails to uphold the\nguarantees it declares, then it's basically a language bug.\n\nThat said, it would be best to minimize *needlessly* relying on properties of\nconcrete safe code. Bugs happen! Of course, I must reinforce that this is only\na concern for Unsafe code. Safe code can blindly trust anyone and everyone\nas far as basic memory-safety is concerned.\n\nOn the other hand, safe traits are free to declare arbitrary contracts, but because\nimplementing them is safe, unsafe code can't trust those contracts to actually\nbe upheld. This is different from the concrete case because *anyone* can\nrandomly implement the interface. There is something fundamentally different\nabout trusting a particular piece of code to be correct, and trusting *all the\ncode that will ever be written* to be correct.\n\nFor instance Rust has `PartialOrd` and `Ord` traits to try to differentiate\nbetween types which can \"just\" be compared, and those that actually implement a\ntotal ordering. Pretty much every API that wants to work with data that can be\ncompared wants Ord data. For instance, a sorted map like BTreeMap\n*doesn't even make sense* for partially ordered types. If you claim to implement\nOrd for a type, but don't actually provide a proper total ordering, BTreeMap will\nget *really confused* and start making a total mess of itself. Data that is\ninserted may be impossible to find!\n\nBut that's okay. BTreeMap is safe, so it guarantees that even if you give it a\ncompletely garbage Ord implementation, it will still do something *safe*. You\nwon't start reading uninitialized or unallocated memory. In fact, BTreeMap\nmanages to not actually lose any of your data. When the map is dropped, all the\ndestructors will be successfully called! Hooray!\n\nHowever BTreeMap is implemented using a modest spoonful of Unsafe Rust (most collections\nare). That means that it's not necessarily *trivially true* that a bad Ord\nimplementation will make BTreeMap behave safely. BTreeMap must be sure not to rely\non Ord *where safety is at stake*. Ord is provided by safe code, and safety is not\nsafe code's responsibility to uphold.\n\nBut wouldn't it be grand if there was some way for Unsafe to trust some trait\ncontracts *somewhere*? This is the problem that unsafe traits tackle: by marking\n*the trait itself* as unsafe to implement, unsafe code can trust the implementation\nto uphold the trait's contract. Although the trait implementation may be\nincorrect in arbitrary other ways.\n\nFor instance, given a hypothetical UnsafeOrd trait, this is technically a valid\nimplementation:\n\n```rust\n# use std::cmp::Ordering;\n# struct MyType;\n# unsafe trait UnsafeOrd { fn cmp(&self, other: &Self) -> Ordering; }\nunsafe impl UnsafeOrd for MyType {\n    fn cmp(&self, other: &Self) -> Ordering {\n        Ordering::Equal\n    }\n}\n```\n\nBut it's probably not the implementation you want.\n\nRust has traditionally avoided making traits unsafe because it makes Unsafe\npervasive, which is not desirable. The reason Send and Sync are unsafe is because thread\nsafety is a *fundamental property* that unsafe code cannot possibly hope to defend\nagainst in the same way it would defend against a bad Ord implementation. The\nonly way to possibly defend against thread-unsafety would be to *not use\nthreading at all*. Making every load and store atomic isn't even sufficient,\nbecause it's possible for complex invariants to exist between disjoint locations\nin memory. For instance, the pointer and capacity of a Vec must be in sync.\n\nEven concurrent paradigms that are traditionally regarded as Totally Safe like\nmessage passing implicitly rely on some notion of thread safety -- are you\nreally message-passing if you pass a pointer? Send and Sync therefore require\nsome fundamental level of trust that Safe code can't provide, so they must be\nunsafe to implement. To help obviate the pervasive unsafety that this would\nintroduce, Send (resp. Sync) is automatically derived for all types composed only\nof Send (resp. Sync) values. 99% of types are Send and Sync, and 99% of those\nnever actually say it (the remaining 1% is overwhelmingly synchronization\nprimitives).\n\n\n\n\n[drop flags]: drop-flags.html\n[conversions]: conversions.html\n"
  },
  {
    "path": "nomicon/send-and-sync.md",
    "content": "% Send and Sync\n\nNot everything obeys inherited mutability, though. Some types allow you to\nmultiply alias a location in memory while mutating it. Unless these types use\nsynchronization to manage this access, they are absolutely not thread safe. Rust\ncaptures this through the `Send` and `Sync` traits.\n\n* A type is Send if it is safe to send it to another thread.\n* A type is Sync if it is safe to share between threads (`&T` is Send).\n\nSend and Sync are fundamental to Rust's concurrency story. As such, a\nsubstantial amount of special tooling exists to make them work right. First and\nforemost, they're [unsafe traits]. This means that they are unsafe to\nimplement, and other unsafe code can assume that they are correctly\nimplemented. Since they're *marker traits* (they have no associated items like\nmethods), correctly implemented simply means that they have the intrinsic\nproperties an implementor should have. Incorrectly implementing Send or Sync can\ncause Undefined Behavior.\n\nSend and Sync are also automatically derived traits. This means that, unlike\nevery other trait, if a type is composed entirely of Send or Sync types, then it\nis Send or Sync. Almost all primitives are Send and Sync, and as a consequence\npretty much all types you'll ever interact with are Send and Sync.\n\nMajor exceptions include:\n\n* raw pointers are neither Send nor Sync (because they have no safety guards).\n* `UnsafeCell` isn't Sync (and therefore `Cell` and `RefCell` aren't).\n* `Rc` isn't Send or Sync (because the refcount is shared and unsynchronized).\n\n`Rc` and `UnsafeCell` are very fundamentally not thread-safe: they enable\nunsynchronized shared mutable state. However raw pointers are, strictly\nspeaking, marked as thread-unsafe as more of a *lint*. Doing anything useful\nwith a raw pointer requires dereferencing it, which is already unsafe. In that\nsense, one could argue that it would be \"fine\" for them to be marked as thread\nsafe.\n\nHowever it's important that they aren't thread safe to prevent types that\ncontain them from being automatically marked as thread safe. These types have\nnon-trivial untracked ownership, and it's unlikely that their author was\nnecessarily thinking hard about thread safety. In the case of Rc, we have a nice\nexample of a type that contains a `*mut` that is definitely not thread safe.\n\nTypes that aren't automatically derived can simply implement them if desired:\n\n```rust\nstruct MyBox(*mut u8);\n\nunsafe impl Send for MyBox {}\nunsafe impl Sync for MyBox {}\n```\n\nIn the *incredibly rare* case that a type is inappropriately automatically\nderived to be Send or Sync, then one can also unimplement Send and Sync:\n\n```rust\n#![feature(optin_builtin_traits)]\n\n// I have some magic semantics for some synchronization primitive!\nstruct SpecialThreadToken(u8);\n\nimpl !Send for SpecialThreadToken {}\nimpl !Sync for SpecialThreadToken {}\n```\n\nNote that *in and of itself* it is impossible to incorrectly derive Send and\nSync. Only types that are ascribed special meaning by other unsafe code can\npossible cause trouble by being incorrectly Send or Sync.\n\nMost uses of raw pointers should be encapsulated behind a sufficient abstraction\nthat Send and Sync can be derived. For instance all of Rust's standard\ncollections are Send and Sync (when they contain Send and Sync types) in spite\nof their pervasive use of raw pointers to manage allocations and complex ownership.\nSimilarly, most iterators into these collections are Send and Sync because they\nlargely behave like an `&` or `&mut` into the collection.\n\nTODO: better explain what can or can't be Send or Sync. Sufficient to appeal\nonly to data races?\n\n[unsafe traits]: safe-unsafe-meaning.html\n"
  },
  {
    "path": "nomicon/subtyping.md",
    "content": "% Subtyping and Variance\n\nAlthough Rust doesn't have any notion of structural inheritance, it *does*\ninclude subtyping. In Rust, subtyping derives entirely from lifetimes. Since\nlifetimes are scopes, we can partially order them based on the *contains*\n(outlives) relationship. We can even express this as a generic bound.\n\nSubtyping on lifetimes is in terms of that relationship: if `'a: 'b` (\"a contains\nb\" or \"a outlives b\"), then `'a` is a subtype of `'b`. This is a large source of\nconfusion, because it seems intuitively backwards to many: the bigger scope is a\n*subtype* of the smaller scope.\n\nThis does in fact make sense, though. The intuitive reason for this is that if\nyou expect an `&'a u8`, then it's totally fine for me to hand you an `&'static\nu8`, in the same way that if you expect an Animal in Java, it's totally fine for\nme to hand you a Cat. Cats are just Animals *and more*, just as `'static` is\njust `'a` *and more*.\n\n(Note, the subtyping relationship and typed-ness of lifetimes is a fairly\narbitrary construct that some disagree with. However it simplifies our analysis\nto treat lifetimes and types uniformly.)\n\nHigher-ranked lifetimes are also subtypes of every concrete lifetime. This is\nbecause taking an arbitrary lifetime is strictly more general than taking a\nspecific one.\n\n\n\n# Variance\n\nVariance is where things get a bit complicated.\n\nVariance is a property that *type constructors* have with respect to their\narguments. A type constructor in Rust is a generic type with unbound arguments.\nFor instance `Vec` is a type constructor that takes a `T` and returns a\n`Vec<T>`. `&` and `&mut` are type constructors that take two inputs: a\nlifetime, and a type to point to.\n\nA type constructor's *variance* is how the subtyping of its inputs affects the\nsubtyping of its outputs. There are two kinds of variance in Rust:\n\n* F is *variant* over `T` if `T` being a subtype of `U` implies\n  `F<T>` is a subtype of `F<U>` (subtyping \"passes through\")\n* F is *invariant* over `T` otherwise (no subtyping relation can be derived)\n\n(For those of you who are familiar with variance from other languages, what we\nrefer to as \"just\" variance is in fact *covariance*. Rust has *contravariance*\nfor functions. The future of contravariance is uncertain and it may be\nscrapped. For now, `fn(T)` is contravariant in `T`, which is used in matching\nmethods in trait implementations to the trait definition. Traits don't have\ninferred variance, so `Fn(T)` is invariant in `T`).\n\nSome important variances:\n\n* `&'a T` is variant over `'a` and `T` (as is `*const T` by metaphor)\n* `&'a mut T` is variant over `'a` but invariant over `T`\n* `Fn(T) -> U` is invariant over `T`, but variant over `U`\n* `Box`, `Vec`, and all other collections are variant over the types of\n  their contents\n* `UnsafeCell<T>`, `Cell<T>`, `RefCell<T>`, `Mutex<T>` and all other\n  interior mutability types are invariant over T (as is `*mut T` by metaphor)\n\nTo understand why these variances are correct and desirable, we will consider\nseveral examples.\n\n\nWe have already covered why `&'a T` should be variant over `'a` when\nintroducing subtyping: it's desirable to be able to pass longer-lived things\nwhere shorter-lived things are needed.\n\nSimilar reasoning applies to why it should be variant over T. It is reasonable\nto be able to pass `&&'static str` where an `&&'a str` is expected. The\nadditional level of indirection does not change the desire to be able to pass\nlonger lived things where shorted lived things are expected.\n\nHowever this logic doesn't apply to `&mut`. To see why `&mut` should\nbe invariant over T, consider the following code:\n\n```rust,ignore\nfn overwrite<T: Copy>(input: &mut T, new: &mut T) {\n    *input = *new;\n}\n\nfn main() {\n    let mut forever_str: &'static str = \"hello\";\n    {\n        let string = String::from(\"world\");\n        overwrite(&mut forever_str, &mut &*string);\n    }\n    // Oops, printing free'd memory\n    println!(\"{}\", forever_str);\n}\n```\n\nThe signature of `overwrite` is clearly valid: it takes mutable references to\ntwo values of the same type, and overwrites one with the other. If `&mut T` was\nvariant over T, then `&mut &'static str` would be a subtype of `&mut &'a str`,\nsince `&'static str` is a subtype of `&'a str`. Therefore the lifetime of\n`forever_str` would successfully be \"shrunk\" down to the shorter lifetime of\n`string`, and `overwrite` would be called successfully. `string` would\nsubsequently be dropped, and `forever_str` would point to freed memory when we\nprint it! Therefore `&mut` should be invariant.\n\nThis is the general theme of variance vs invariance: if variance would allow you\nto store a short-lived value into a longer-lived slot, then you must be\ninvariant.\n\nHowever it *is* sound for `&'a mut T` to be variant over `'a`. The key difference\nbetween `'a` and T is that `'a` is a property of the reference itself,\nwhile T is something the reference is borrowing. If you change T's type, then\nthe source still remembers the original type. However if you change the\nlifetime's type, no one but the reference knows this information, so it's fine.\nPut another way: `&'a mut T` owns `'a`, but only *borrows* T.\n\n`Box` and `Vec` are interesting cases because they're variant, but you can\ndefinitely store values in them! This is where Rust gets really clever: it's\nfine for them to be variant because you can only store values\nin them *via a mutable reference*! The mutable reference makes the whole type\ninvariant, and therefore prevents you from smuggling a short-lived type into\nthem.\n\nBeing variant allows `Box` and `Vec` to be weakened when shared\nimmutably. So you can pass a `&Box<&'static str>` where a `&Box<&'a str>` is\nexpected.\n\nHowever what should happen when passing *by-value* is less obvious. It turns out\nthat, yes, you can use subtyping when passing by-value. That is, this works:\n\n```rust\nfn get_box<'a>(str: &'a str) -> Box<&'a str> {\n    // string literals are `&'static str`s\n    Box::new(\"hello\")\n}\n```\n\nWeakening when you pass by-value is fine because there's no one else who\n\"remembers\" the old lifetime in the Box. The reason a variant `&mut` was\ntrouble was because there's always someone else who remembers the original\nsubtype: the actual owner.\n\nThe invariance of the cell types can be seen as follows: `&` is like an `&mut`\nfor a cell, because you can still store values in them through an `&`. Therefore\ncells must be invariant to avoid lifetime smuggling.\n\n`Fn` is the most subtle case because it has mixed variance. To see why\n`Fn(T) -> U` should be invariant over T, consider the following function\nsignature:\n\n```rust,ignore\n// 'a is derived from some parent scope\nfn foo(&'a str) -> usize;\n```\n\nThis signature claims that it can handle any `&str` that lives at least as\nlong as `'a`. Now if this signature was variant over `&'a str`, that\nwould mean\n\n```rust,ignore\nfn foo(&'static str) -> usize;\n```\n\ncould be provided in its place, as it would be a subtype. However this function\nhas a stronger requirement: it says that it can only handle `&'static str`s,\nand nothing else. Giving `&'a str`s to it would be unsound, as it's free to\nassume that what it's given lives forever. Therefore functions are not variant\nover their arguments.\n\nTo see why `Fn(T) -> U` should be variant over U, consider the following\nfunction signature:\n\n```rust,ignore\n// 'a is derived from some parent scope\nfn foo(usize) -> &'a str;\n```\n\nThis signature claims that it will return something that outlives `'a`. It is\ntherefore completely reasonable to provide\n\n```rust,ignore\nfn foo(usize) -> &'static str;\n```\n\nin its place. Therefore functions are variant over their return type.\n\n`*const` has the exact same semantics as `&`, so variance follows. `*mut` on the\nother hand can dereference to an `&mut` whether shared or not, so it is marked\nas invariant just like cells.\n\nThis is all well and good for the types the standard library provides, but\nhow is variance determined for type that *you* define? A struct, informally\nspeaking, inherits the variance of its fields. If a struct `Foo`\nhas a generic argument `A` that is used in a field `a`, then Foo's variance\nover `A` is exactly `a`'s variance. However this is complicated if `A` is used\nin multiple fields.\n\n* If all uses of A are variant, then Foo is variant over A\n* Otherwise, Foo is invariant over A\n\n```rust\nuse std::cell::Cell;\n\nstruct Foo<'a, 'b, A: 'a, B: 'b, C, D, E, F, G, H> {\n    a: &'a A,     // variant over 'a and A\n    b: &'b mut B, // variant over 'b and invariant over B\n    c: *const C,  // variant over C\n    d: *mut D,    // invariant over D\n    e: Vec<E>,    // variant over E\n    f: Cell<F>,   // invariant over F\n    g: G,         // variant over G\n    h1: H,        // would also be variant over H except...\n    h2: Cell<H>,  // invariant over H, because invariance wins\n}\n```\n"
  },
  {
    "path": "nomicon/transmutes.md",
    "content": "% Transmutes\n\nGet out of our way type system! We're going to reinterpret these bits or die\ntrying! Even though this book is all about doing things that are unsafe, I\nreally can't emphasize that you should deeply think about finding Another Way\nthan the operations covered in this section. This is really, truly, the most\nhorribly unsafe thing you can do in Rust. The railguards here are dental floss.\n\n`mem::transmute<T, U>` takes a value of type `T` and reinterprets it to have\ntype `U`. The only restriction is that the `T` and `U` are verified to have the\nsame size. The ways to cause Undefined Behavior with this are mind boggling.\n\n* First and foremost, creating an instance of *any* type with an invalid state\n  is going to cause arbitrary chaos that can't really be predicted.\n* Transmute has an overloaded return type. If you do not specify the return type\n  it may produce a surprising type to satisfy inference.\n* Making a primitive with an invalid value is UB\n* Transmuting between non-repr(C) types is UB\n* Transmuting an & to &mut is UB\n    * Transmuting an & to &mut is *always* UB\n    * No you can't do it\n    * No you're not special\n* Transmuting to a reference without an explicitly provided lifetime\n  produces an [unbounded lifetime]\n\n`mem::transmute_copy<T, U>` somehow manages to be *even more* wildly unsafe than\nthis. It copies `size_of<U>` bytes out of an `&T` and interprets them as a `U`.\nThe size check that `mem::transmute` has is gone (as it may be valid to copy\nout a prefix), though it is Undefined Behavior for `U` to be larger than `T`.\n\nAlso of course you can get most of the functionality of these functions using\npointer casts.\n\n\n[unbounded lifetime]: unbounded-lifetimes.html\n"
  },
  {
    "path": "nomicon/unbounded-lifetimes.md",
    "content": "% Unbounded Lifetimes\n\nUnsafe code can often end up producing references or lifetimes out of thin air.\nSuch lifetimes come into the world as *unbounded*. The most common source of this\nis dereferencing a raw pointer, which produces a reference with an unbounded lifetime.\nSuch a lifetime becomes as big as context demands. This is in fact more powerful\nthan simply becoming `'static`, because for instance `&'static &'a T`\nwill fail to typecheck, but the unbound lifetime will perfectly mold into\n`&'a &'a T` as needed. However for most intents and purposes, such an unbounded\nlifetime can be regarded as `'static`.\n\nAlmost no reference is `'static`, so this is probably wrong. `transmute` and\n`transmute_copy` are the two other primary offenders. One should endeavor to\nbound an unbounded lifetime as quick as possible, especially across function\nboundaries.\n\nGiven a function, any output lifetimes that don't derive from inputs are\nunbounded. For instance:\n\n```rust,ignore\nfn get_str<'a>() -> &'a str;\n```\n\nwill produce an `&str` with an unbounded lifetime. The easiest way to avoid\nunbounded lifetimes is to use lifetime elision at the function boundary.\nIf an output lifetime is elided, then it *must* be bounded by an input lifetime.\nOf course it might be bounded by the *wrong* lifetime, but this will usually\njust cause a compiler error, rather than allow memory safety to be trivially\nviolated.\n\nWithin a function, bounding lifetimes is more error-prone. The safest and easiest\nway to bound a lifetime is to return it from a function with a bound lifetime.\nHowever if this is unacceptable, the reference can be placed in a location with\na specific lifetime. Unfortunately it's impossible to name all lifetimes involved\nin a function.\n\n"
  },
  {
    "path": "nomicon/unchecked-uninit.md",
    "content": "% Unchecked Uninitialized Memory\n\nOne interesting exception to this rule is working with arrays. Safe Rust doesn't\npermit you to partially initialize an array. When you initialize an array, you\ncan either set every value to the same thing with `let x = [val; N]`, or you can\nspecify each member individually with `let x = [val1, val2, val3]`.\nUnfortunately this is pretty rigid, especially if you need to initialize your\narray in a more incremental or dynamic way.\n\nUnsafe Rust gives us a powerful tool to handle this problem:\n`mem::uninitialized`. This function pretends to return a value when really\nit does nothing at all. Using it, we can convince Rust that we have initialized\na variable, allowing us to do trickier things with conditional and incremental\ninitialization.\n\nUnfortunately, this opens us up to all kinds of problems. Assignment has a\ndifferent meaning to Rust based on whether it believes that a variable is\ninitialized or not. If it's believed uninitialized, then Rust will semantically\njust memcopy the bits over the uninitialized ones, and do nothing else. However\nif Rust believes a value to be initialized, it will try to `Drop` the old value!\nSince we've tricked Rust into believing that the value is initialized, we can no\nlonger safely use normal assignment.\n\nThis is also a problem if you're working with a raw system allocator, which\nreturns a pointer to uninitialized memory.\n\nTo handle this, we must use the `ptr` module. In particular, it provides\nthree functions that allow us to assign bytes to a location in memory without\ndropping the old value: `write`, `copy`, and `copy_nonoverlapping`.\n\n* `ptr::write(ptr, val)` takes a `val` and moves it into the address pointed\n  to by `ptr`.\n* `ptr::copy(src, dest, count)` copies the bits that `count` T's would occupy\n  from src to dest. (this is equivalent to memmove -- note that the argument\n  order is reversed!)\n* `ptr::copy_nonoverlapping(src, dest, count)` does what `copy` does, but a\n  little faster on the assumption that the two ranges of memory don't overlap.\n  (this is equivalent to memcpy -- note that the argument order is reversed!)\n\nIt should go without saying that these functions, if misused, will cause serious\nhavoc or just straight up Undefined Behavior. The only things that these\nfunctions *themselves* require is that the locations you want to read and write\nare allocated. However the ways writing arbitrary bits to arbitrary\nlocations of memory can break things are basically uncountable!\n\nPutting this all together, we get the following:\n\n```rust\nuse std::mem;\nuse std::ptr;\n\n// size of the array is hard-coded but easy to change. This means we can't\n// use [a, b, c] syntax to initialize the array, though!\nconst SIZE: usize = 10;\n\nlet mut x: [Box<u32>; SIZE];\n\nunsafe {\n\t// convince Rust that x is Totally Initialized\n\tx = mem::uninitialized();\n\tfor i in 0..SIZE {\n\t\t// very carefully overwrite each index without reading it\n\t\t// NOTE: exception safety is not a concern; Box can't panic\n\t\tptr::write(&mut x[i], Box::new(i as u32));\n\t}\n}\n\nprintln!(\"{:?}\", x);\n```\n\nIt's worth noting that you don't need to worry about `ptr::write`-style\nshenanigans with types which don't implement `Drop` or contain `Drop` types,\nbecause Rust knows not to try to drop them. Similarly you should be able to\nassign to fields of partially initialized structs directly if those fields don't\ncontain any `Drop` types.\n\nHowever when working with uninitialized memory you need to be ever-vigilant for\nRust trying to drop values you make like this before they're fully initialized.\nEvery control path through that variable's scope must initialize the value\nbefore it ends, if it has a destructor.\n*[This includes code panicking](unwinding.html)*.\n\nAnd that's about it for working with uninitialized memory! Basically nothing\nanywhere expects to be handed uninitialized memory, so if you're going to pass\nit around at all, be sure to be *really* careful.\n"
  },
  {
    "path": "nomicon/uninitialized.md",
    "content": "% Working With Uninitialized Memory\n\nAll runtime-allocated memory in a Rust program begins its life as\n*uninitialized*. In this state the value of the memory is an indeterminate pile\nof bits that may or may not even reflect a valid state for the type that is\nsupposed to inhabit that location of memory. Attempting to interpret this memory\nas a value of *any* type will cause Undefined Behavior. Do Not Do This.\n\nRust provides mechanisms to work with uninitialized memory in checked (safe) and\nunchecked (unsafe) ways.\n"
  },
  {
    "path": "nomicon/unwinding.md",
    "content": "% Unwinding\n\nRust has a *tiered* error-handling scheme:\n\n* If something might reasonably be absent, Option is used.\n* If something goes wrong and can reasonably be handled, Result is used.\n* If something goes wrong and cannot reasonably be handled, the thread panics.\n* If something catastrophic happens, the program aborts.\n\nOption and Result are overwhelmingly preferred in most situations, especially\nsince they can be promoted into a panic or abort at the API user's discretion.\nPanics cause the thread to halt normal execution and unwind its stack, calling\ndestructors as if every function instantly returned.\n\nAs of 1.0, Rust is of two minds when it comes to panics. In the long-long-ago,\nRust was much more like Erlang. Like Erlang, Rust had lightweight tasks,\nand tasks were intended to kill themselves with a panic when they reached an\nuntenable state. Unlike an exception in Java or C++, a panic could not be\ncaught at any time. Panics could only be caught by the owner of the task, at which\npoint they had to be handled or *that* task would itself panic.\n\nUnwinding was important to this story because if a task's\ndestructors weren't called, it would cause memory and other system resources to\nleak. Since tasks were expected to die during normal execution, this would make\nRust very poor for long-running systems!\n\nAs the Rust we know today came to be, this style of programming grew out of\nfashion in the push for less-and-less abstraction. Light-weight tasks were\nkilled in the name of heavy-weight OS threads. Still, on stable Rust as of 1.0\npanics can only be caught by the parent thread. This means catching a panic\nrequires spinning up an entire OS thread! This unfortunately stands in conflict\nto Rust's philosophy of zero-cost abstractions.\n\nThere is an unstable API called `catch_panic` that enables catching a panic\nwithout spawning a thread. Still, we would encourage you to only do this\nsparingly. In particular, Rust's current unwinding implementation is heavily\noptimized for the \"doesn't unwind\" case. If a program doesn't unwind, there\nshould be no runtime cost for the program being *ready* to unwind. As a\nconsequence, actually unwinding will be more expensive than in e.g. Java.\nDon't build your programs to unwind under normal circumstances. Ideally, you\nshould only panic for programming errors or *extreme* problems.\n\nRust's unwinding strategy is not specified to be fundamentally compatible\nwith any other language's unwinding. As such, unwinding into Rust from another\nlanguage, or unwinding into another language from Rust is Undefined Behavior.\nYou must *absolutely* catch any panics at the FFI boundary! What you do at that\npoint is up to you, but *something* must be done. If you fail to do this,\nat best, your application will crash and burn. At worst, your application *won't*\ncrash and burn, and will proceed with completely clobbered state.\n"
  },
  {
    "path": "nomicon/vec-alloc.md",
    "content": "% Allocating Memory\n\nUsing Unique throws a wrench in an important feature of Vec (and indeed all of\nthe std collections): an empty Vec doesn't actually allocate at all. So if we\ncan't allocate, but also can't put a null pointer in `ptr`, what do we do in\n`Vec::new`? Well, we just put some other garbage in there!\n\nThis is perfectly fine because we already have `cap == 0` as our sentinel for no\nallocation. We don't even need to handle it specially in almost any code because\nwe usually need to check if `cap > len` or `len > 0` anyway. The traditional\nRust value to put here is `0x01`. The standard library actually exposes this\nas `alloc::heap::EMPTY`. There are quite a few places where we'll\nwant to use `heap::EMPTY` because there's no real allocation to talk about but\n`null` would make the compiler do bad things.\n\nAll of the `heap` API is totally unstable under the `heap_api` feature, though.\nWe could trivially define `heap::EMPTY` ourselves, but we'll want the rest of\nthe `heap` API anyway, so let's just get that dependency over with.\n\nSo:\n\n```rust,ignore\n#![feature(alloc, heap_api)]\n\nuse std::mem;\n\nuse alloc::heap::EMPTY;\n\nimpl<T> Vec<T> {\n    fn new() -> Self {\n        assert!(mem::size_of::<T>() != 0, \"We're not ready to handle ZSTs\");\n        unsafe {\n            // need to cast EMPTY to the actual ptr type we want, let\n            // inference handle it.\n            Vec { ptr: Unique::new(heap::EMPTY as *mut _), len: 0, cap: 0 }\n        }\n    }\n}\n```\n\nI slipped in that assert there because zero-sized types will require some\nspecial handling throughout our code, and I want to defer the issue for now.\nWithout this assert, some of our early drafts will do some Very Bad Things.\n\nNext we need to figure out what to actually do when we *do* want space. For\nthat, we'll need to use the rest of the heap APIs. These basically allow us to\ntalk directly to Rust's allocator (jemalloc by default).\n\nWe'll also need a way to handle out-of-memory (OOM) conditions. The standard\nlibrary calls the `abort` intrinsic, which just calls an illegal instruction to\ncrash the whole program. The reason we abort and don't panic is because\nunwinding can cause allocations to happen, and that seems like a bad thing to do\nwhen your allocator just came back with \"hey I don't have any more memory\".\n\nOf course, this is a bit silly since most platforms don't actually run out of\nmemory in a conventional way. Your operating system will probably kill the\napplication by another means if you legitimately start using up all the memory.\nThe most likely way we'll trigger OOM is by just asking for ludicrous quantities\nof memory at once (e.g. half the theoretical address space). As such it's\n*probably* fine to panic and nothing bad will happen. Still, we're trying to be\nlike the standard library as much as possible, so we'll just kill the whole\nprogram.\n\nWe said we don't want to use intrinsics, so doing exactly what `std` does is\nout. Instead, we'll call `std::process::exit` with some random number.\n\n```rust\nfn oom() {\n    ::std::process::exit(-9999);\n}\n```\n\nOkay, now we can write growing. Roughly, we want to have this logic:\n\n```text\nif cap == 0:\n    allocate()\n    cap = 1\nelse:\n    reallocate()\n    cap *= 2\n```\n\nBut Rust's only supported allocator API is so low level that we'll need to do a\nfair bit of extra work. We also need to guard against some special\nconditions that can occur with really large allocations or empty allocations.\n\nIn particular, `ptr::offset` will cause us a lot of trouble, because it has\nthe semantics of LLVM's GEP inbounds instruction. If you're fortunate enough to\nnot have dealt with this instruction, here's the basic story with GEP: alias\nanalysis, alias analysis, alias analysis. It's super important to an optimizing\ncompiler to be able to reason about data dependencies and aliasing.\n\nAs a simple example, consider the following fragment of code:\n\n```rust\n# let x = &mut 0;\n# let y = &mut 0;\n*x *= 7;\n*y *= 3;\n```\n\nIf the compiler can prove that `x` and `y` point to different locations in\nmemory, the two operations can in theory be executed in parallel (by e.g.\nloading them into different registers and working on them independently).\nHowever the compiler can't do this in general because if x and y point to\nthe same location in memory, the operations need to be done to the same value,\nand they can't just be merged afterwards.\n\nWhen you use GEP inbounds, you are specifically telling LLVM that the offsets\nyou're about to do are within the bounds of a single \"allocated\" entity. The\nultimate payoff being that LLVM can assume that if two pointers are known to\npoint to two disjoint objects, all the offsets of those pointers are *also*\nknown to not alias (because you won't just end up in some random place in\nmemory). LLVM is heavily optimized to work with GEP offsets, and inbounds\noffsets are the best of all, so it's important that we use them as much as\npossible.\n\nSo that's what GEP's about, how can it cause us trouble?\n\nThe first problem is that we index into arrays with unsigned integers, but\nGEP (and as a consequence `ptr::offset`) takes a signed integer. This means\nthat half of the seemingly valid indices into an array will overflow GEP and\nactually go in the wrong direction! As such we must limit all allocations to\n`isize::MAX` elements. This actually means we only need to worry about\nbyte-sized objects, because e.g. `> isize::MAX` `u16`s will truly exhaust all of\nthe system's memory. However in order to avoid subtle corner cases where someone\nreinterprets some array of `< isize::MAX` objects as bytes, std limits all\nallocations to `isize::MAX` bytes.\n\nOn all 64-bit targets that Rust currently supports we're artificially limited\nto significantly less than all 64 bits of the address space (modern x64\nplatforms only expose 48-bit addressing), so we can rely on just running out of\nmemory first. However on 32-bit targets, particularly those with extensions to\nuse more of the address space (PAE x86 or x32), it's theoretically possible to\nsuccessfully allocate more than `isize::MAX` bytes of memory.\n\nHowever since this is a tutorial, we're not going to be particularly optimal\nhere, and just unconditionally check, rather than use clever platform-specific\n`cfg`s.\n\nThe other corner-case we need to worry about is empty allocations. There will\nbe two kinds of empty allocations we need to worry about: `cap = 0` for all T,\nand `cap > 0` for zero-sized types.\n\nThese cases are tricky because they come\ndown to what LLVM means by \"allocated\". LLVM's notion of an\nallocation is significantly more abstract than how we usually use it. Because\nLLVM needs to work with different languages' semantics and custom allocators,\nit can't really intimately understand allocation. Instead, the main idea behind\nallocation is \"doesn't overlap with other stuff\". That is, heap allocations,\nstack allocations, and globals don't randomly overlap. Yep, it's about alias\nanalysis. As such, Rust can technically play a bit fast and loose with the notion of\nan allocation as long as it's *consistent*.\n\nGetting back to the empty allocation case, there are a couple of places where\nwe want to offset by 0 as a consequence of generic code. The question is then:\nis it consistent to do so? For zero-sized types, we have concluded that it is\nindeed consistent to do a GEP inbounds offset by an arbitrary number of\nelements. This is a runtime no-op because every element takes up no space,\nand it's fine to pretend that there's infinite zero-sized types allocated\nat `0x01`. No allocator will ever allocate that address, because they won't\nallocate `0x00` and they generally allocate to some minimal alignment higher\nthan a byte. Also generally the whole first page of memory is\nprotected from being allocated anyway (a whole 4k, on many platforms).\n\nHowever what about for positive-sized types? That one's a bit trickier. In\nprinciple, you can argue that offsetting by 0 gives LLVM no information: either\nthere's an element before the address or after it, but it can't know which.\nHowever we've chosen to conservatively assume that it may do bad things. As\nsuch we will guard against this case explicitly.\n\n*Phew*\n\nOk with all the nonsense out of the way, let's actually allocate some memory:\n\n```rust,ignore\nfn grow(&mut self) {\n    // this is all pretty delicate, so let's say it's all unsafe\n    unsafe {\n        // current API requires us to specify size and alignment manually.\n        let align = mem::align_of::<T>();\n        let elem_size = mem::size_of::<T>();\n\n        let (new_cap, ptr) = if self.cap == 0 {\n            let ptr = heap::allocate(elem_size, align);\n            (1, ptr)\n        } else {\n            // as an invariant, we can assume that `self.cap < isize::MAX`,\n            // so this doesn't need to be checked.\n            let new_cap = self.cap * 2;\n            // Similarly this can't overflow due to previously allocating this\n            let old_num_bytes = self.cap * elem_size;\n\n            // check that the new allocation doesn't exceed `isize::MAX` at all\n            // regardless of the actual size of the capacity. This combines the\n            // `new_cap <= isize::MAX` and `new_num_bytes <= usize::MAX` checks\n            // we need to make. We lose the ability to allocate e.g. 2/3rds of\n            // the address space with a single Vec of i16's on 32-bit though.\n            // Alas, poor Yorick -- I knew him, Horatio.\n            assert!(old_num_bytes <= (::std::isize::MAX as usize) / 2,\n                    \"capacity overflow\");\n\n            let new_num_bytes = old_num_bytes * 2;\n            let ptr = heap::reallocate(*self.ptr as *mut _,\n                                        old_num_bytes,\n                                        new_num_bytes,\n                                        align);\n            (new_cap, ptr)\n        };\n\n        // If allocate or reallocate fail, we'll get `null` back\n        if ptr.is_null() { oom(); }\n\n        self.ptr = Unique::new(ptr as *mut _);\n        self.cap = new_cap;\n    }\n}\n```\n\nNothing particularly tricky here. Just computing sizes and alignments and doing\nsome careful multiplication checks.\n\n"
  },
  {
    "path": "nomicon/vec-dealloc.md",
    "content": "% Deallocating\n\nNext we should implement Drop so that we don't massively leak tons of resources.\nThe easiest way is to just call `pop` until it yields None, and then deallocate\nour buffer. Note that calling `pop` is unneeded if `T: !Drop`. In theory we can\nask Rust if `T` `needs_drop` and omit the calls to `pop`. However in practice\nLLVM is *really* good at removing simple side-effect free code like this, so I\nwouldn't bother unless you notice it's not being stripped (in this case it is).\n\nWe must not call `heap::deallocate` when `self.cap == 0`, as in this case we\nhaven't actually allocated any memory.\n\n\n```rust,ignore\nimpl<T> Drop for Vec<T> {\n    fn drop(&mut self) {\n        if self.cap != 0 {\n            while let Some(_) = self.pop() { }\n\n            let align = mem::align_of::<T>();\n            let elem_size = mem::size_of::<T>();\n            let num_bytes = elem_size * self.cap;\n            unsafe {\n                heap::deallocate(*self.ptr as *mut _, num_bytes, align);\n            }\n        }\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/vec-deref.md",
    "content": "% Deref\n\nAlright! We've got a decent minimal stack implemented. We can push, we can\npop, and we can clean up after ourselves. However there's a whole mess of\nfunctionality we'd reasonably want. In particular, we have a proper array, but\nnone of the slice functionality. That's actually pretty easy to solve: we can\nimplement `Deref<Target=[T]>`. This will magically make our Vec coerce to, and\nbehave like, a slice in all sorts of conditions.\n\nAll we need is `slice::from_raw_parts`. It will correctly handle empty slices\nfor us. Later once we set up zero-sized type support it will also Just Work\nfor those too.\n\n```rust,ignore\nuse std::ops::Deref;\n\nimpl<T> Deref for Vec<T> {\n    type Target = [T];\n    fn deref(&self) -> &[T] {\n        unsafe {\n            ::std::slice::from_raw_parts(*self.ptr, self.len)\n        }\n    }\n}\n```\n\nAnd let's do DerefMut too:\n\n```rust,ignore\nuse std::ops::DerefMut;\n\nimpl<T> DerefMut for Vec<T> {\n    fn deref_mut(&mut self) -> &mut [T] {\n        unsafe {\n            ::std::slice::from_raw_parts_mut(*self.ptr, self.len)\n        }\n    }\n}\n```\n\nNow we have `len`, `first`, `last`, indexing, slicing, sorting, `iter`,\n`iter_mut`, and all other sorts of bells and whistles provided by slice. Sweet!\n"
  },
  {
    "path": "nomicon/vec-drain.md",
    "content": "% Drain\n\nLet's move on to Drain. Drain is largely the same as IntoIter, except that\ninstead of consuming the Vec, it borrows the Vec and leaves its allocation\nuntouched. For now we'll only implement the \"basic\" full-range version.\n\n```rust,ignore\nuse std::marker::PhantomData;\n\nstruct Drain<'a, T: 'a> {\n    // Need to bound the lifetime here, so we do it with `&'a mut Vec<T>`\n    // because that's semantically what we contain. We're \"just\" calling\n    // `pop()` and `remove(0)`.\n    vec: PhantomData<&'a mut Vec<T>>\n    start: *const T,\n    end: *const T,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n```\n\n-- wait, this is seeming familiar. Let's do some more compression. Both\nIntoIter and Drain have the exact same structure, let's just factor it out.\n\n```rust\nstruct RawValIter<T> {\n    start: *const T,\n    end: *const T,\n}\n\nimpl<T> RawValIter<T> {\n    // unsafe to construct because it has no associated lifetimes.\n    // This is necessary to store a RawValIter in the same struct as\n    // its actual allocation. OK since it's a private implementation\n    // detail.\n    unsafe fn new(slice: &[T]) -> Self {\n        RawValIter {\n            start: slice.as_ptr(),\n            end: if slice.len() == 0 {\n                // if `len = 0`, then this is not actually allocated memory.\n                // Need to avoid offsetting because that will give wrong\n                // information to LLVM via GEP.\n                slice.as_ptr()\n            } else {\n                slice.as_ptr().offset(slice.len() as isize)\n            }\n        }\n    }\n}\n\n// Iterator and DoubleEndedIterator impls identical to IntoIter.\n```\n\nAnd IntoIter becomes the following:\n\n```rust,ignore\npub struct IntoIter<T> {\n    _buf: RawVec<T>, // we don't actually care about this. Just need it to live.\n    iter: RawValIter<T>,\n}\n\nimpl<T> Iterator for IntoIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> { self.iter.next() }\n    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }\n}\n\nimpl<T> DoubleEndedIterator for IntoIter<T> {\n    fn next_back(&mut self) -> Option<T> { self.iter.next_back() }\n}\n\nimpl<T> Drop for IntoIter<T> {\n    fn drop(&mut self) {\n        for _ in &mut self.iter {}\n    }\n}\n\nimpl<T> Vec<T> {\n    pub fn into_iter(self) -> IntoIter<T> {\n        unsafe {\n            let iter = RawValIter::new(&self);\n\n            let buf = ptr::read(&self.buf);\n            mem::forget(self);\n\n            IntoIter {\n                iter: iter,\n                _buf: buf,\n            }\n        }\n    }\n}\n```\n\nNote that I've left a few quirks in this design to make upgrading Drain to work\nwith arbitrary subranges a bit easier. In particular we *could* have RawValIter\ndrain itself on drop, but that won't work right for a more complex Drain.\nWe also take a slice to simplify Drain initialization.\n\nAlright, now Drain is really easy:\n\n```rust,ignore\nuse std::marker::PhantomData;\n\npub struct Drain<'a, T: 'a> {\n    vec: PhantomData<&'a mut Vec<T>>,\n    iter: RawValIter<T>,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> { self.iter.next() }\n    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }\n}\n\nimpl<'a, T> DoubleEndedIterator for Drain<'a, T> {\n    fn next_back(&mut self) -> Option<T> { self.iter.next_back() }\n}\n\nimpl<'a, T> Drop for Drain<'a, T> {\n    fn drop(&mut self) {\n        for _ in &mut self.iter {}\n    }\n}\n\nimpl<T> Vec<T> {\n    pub fn drain(&mut self) -> Drain<T> {\n        unsafe {\n            let iter = RawValIter::new(&self);\n\n            // this is a mem::forget safety thing. If Drain is forgotten, we just\n            // leak the whole Vec's contents. Also we need to do this *eventually*\n            // anyway, so why not do it now?\n            self.len = 0;\n\n            Drain {\n                iter: iter,\n                vec: PhantomData,\n            }\n        }\n    }\n}\n```\n\nFor more details on the `mem::forget` problem, see the\n[section on leaks][leaks].\n\n[leaks]: leaking.html\n"
  },
  {
    "path": "nomicon/vec-final.md",
    "content": "% The Final Code\n\n```rust\n#![feature(unique)]\n#![feature(alloc, heap_api)]\n\nextern crate alloc;\n\nuse std::ptr::{Unique, self};\nuse std::mem;\nuse std::ops::{Deref, DerefMut};\nuse std::marker::PhantomData;\n\nuse alloc::heap;\n\nstruct RawVec<T> {\n    ptr: Unique<T>,\n    cap: usize,\n}\n\nimpl<T> RawVec<T> {\n    fn new() -> Self {\n        unsafe {\n            // !0 is usize::MAX. This branch should be stripped at compile time.\n            let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };\n\n            // heap::EMPTY doubles as \"unallocated\" and \"zero-sized allocation\"\n            RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: cap }\n        }\n    }\n\n    fn grow(&mut self) {\n        unsafe {\n            let elem_size = mem::size_of::<T>();\n\n            // since we set the capacity to usize::MAX when elem_size is\n            // 0, getting to here necessarily means the Vec is overfull.\n            assert!(elem_size != 0, \"capacity overflow\");\n\n            let align = mem::align_of::<T>();\n\n            let (new_cap, ptr) = if self.cap == 0 {\n                let ptr = heap::allocate(elem_size, align);\n                (1, ptr)\n            } else {\n                let new_cap = 2 * self.cap;\n                let ptr = heap::reallocate(*self.ptr as *mut _,\n                                            self.cap * elem_size,\n                                            new_cap * elem_size,\n                                            align);\n                (new_cap, ptr)\n            };\n\n            // If allocate or reallocate fail, we'll get `null` back\n            if ptr.is_null() { oom() }\n\n            self.ptr = Unique::new(ptr as *mut _);\n            self.cap = new_cap;\n        }\n    }\n}\n\nimpl<T> Drop for RawVec<T> {\n    fn drop(&mut self) {\n        let elem_size = mem::size_of::<T>();\n        if self.cap != 0 && elem_size != 0 {\n            let align = mem::align_of::<T>();\n\n            let num_bytes = elem_size * self.cap;\n            unsafe {\n                heap::deallocate(*self.ptr as *mut _, num_bytes, align);\n            }\n        }\n    }\n}\n\n\n\n\n\npub struct Vec<T> {\n    buf: RawVec<T>,\n    len: usize,\n}\n\nimpl<T> Vec<T> {\n    fn ptr(&self) -> *mut T { *self.buf.ptr }\n\n    fn cap(&self) -> usize { self.buf.cap }\n\n    pub fn new() -> Self {\n        Vec { buf: RawVec::new(), len: 0 }\n    }\n    pub fn push(&mut self, elem: T) {\n        if self.len == self.cap() { self.buf.grow(); }\n\n        unsafe {\n            ptr::write(self.ptr().offset(self.len as isize), elem);\n        }\n\n        // Can't fail, we'll OOM first.\n        self.len += 1;\n    }\n\n    pub fn pop(&mut self) -> Option<T> {\n        if self.len == 0 {\n            None\n        } else {\n            self.len -= 1;\n            unsafe {\n                Some(ptr::read(self.ptr().offset(self.len as isize)))\n            }\n        }\n    }\n\n    pub fn insert(&mut self, index: usize, elem: T) {\n        assert!(index <= self.len, \"index out of bounds\");\n        if self.cap() == self.len { self.buf.grow(); }\n\n        unsafe {\n            if index < self.len {\n                ptr::copy(self.ptr().offset(index as isize),\n                          self.ptr().offset(index as isize + 1),\n                          self.len - index);\n            }\n            ptr::write(self.ptr().offset(index as isize), elem);\n            self.len += 1;\n        }\n    }\n\n    pub fn remove(&mut self, index: usize) -> T {\n        assert!(index < self.len, \"index out of bounds\");\n        unsafe {\n            self.len -= 1;\n            let result = ptr::read(self.ptr().offset(index as isize));\n            ptr::copy(self.ptr().offset(index as isize + 1),\n                      self.ptr().offset(index as isize),\n                      self.len - index);\n            result\n        }\n    }\n\n    pub fn into_iter(self) -> IntoIter<T> {\n        unsafe {\n            let iter = RawValIter::new(&self);\n            let buf = ptr::read(&self.buf);\n            mem::forget(self);\n\n            IntoIter {\n                iter: iter,\n                _buf: buf,\n            }\n        }\n    }\n\n    pub fn drain(&mut self) -> Drain<T> {\n        unsafe {\n            let iter = RawValIter::new(&self);\n\n            // this is a mem::forget safety thing. If Drain is forgotten, we just\n            // leak the whole Vec's contents. Also we need to do this *eventually*\n            // anyway, so why not do it now?\n            self.len = 0;\n\n            Drain {\n                iter: iter,\n                vec: PhantomData,\n            }\n        }\n    }\n}\n\nimpl<T> Drop for Vec<T> {\n    fn drop(&mut self) {\n        while let Some(_) = self.pop() {}\n        // allocation is handled by RawVec\n    }\n}\n\nimpl<T> Deref for Vec<T> {\n    type Target = [T];\n    fn deref(&self) -> &[T] {\n        unsafe {\n            ::std::slice::from_raw_parts(self.ptr(), self.len)\n        }\n    }\n}\n\nimpl<T> DerefMut for Vec<T> {\n    fn deref_mut(&mut self) -> &mut [T] {\n        unsafe {\n            ::std::slice::from_raw_parts_mut(self.ptr(), self.len)\n        }\n    }\n}\n\n\n\n\n\nstruct RawValIter<T> {\n    start: *const T,\n    end: *const T,\n}\n\nimpl<T> RawValIter<T> {\n    unsafe fn new(slice: &[T]) -> Self {\n        RawValIter {\n            start: slice.as_ptr(),\n            end: if mem::size_of::<T>() == 0 {\n                ((slice.as_ptr() as usize) + slice.len()) as *const _\n            } else if slice.len() == 0 {\n                slice.as_ptr()\n            } else {\n                slice.as_ptr().offset(slice.len() as isize)\n            }\n        }\n    }\n}\n\nimpl<T> Iterator for RawValIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                let result = ptr::read(self.start);\n                self.start = if mem::size_of::<T>() == 0 {\n                    (self.start as usize + 1) as *const _\n                } else {\n                    self.start.offset(1)\n                };\n                Some(result)\n            }\n        }\n    }\n\n    fn size_hint(&self) -> (usize, Option<usize>) {\n        let elem_size = mem::size_of::<T>();\n        let len = (self.end as usize - self.start as usize)\n                  / if elem_size == 0 { 1 } else { elem_size };\n        (len, Some(len))\n    }\n}\n\nimpl<T> DoubleEndedIterator for RawValIter<T> {\n    fn next_back(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                self.end = if mem::size_of::<T>() == 0 {\n                    (self.end as usize - 1) as *const _\n                } else {\n                    self.end.offset(-1)\n                };\n                Some(ptr::read(self.end))\n            }\n        }\n    }\n}\n\n\n\n\npub struct IntoIter<T> {\n    _buf: RawVec<T>, // we don't actually care about this. Just need it to live.\n    iter: RawValIter<T>,\n}\n\nimpl<T> Iterator for IntoIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> { self.iter.next() }\n    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }\n}\n\nimpl<T> DoubleEndedIterator for IntoIter<T> {\n    fn next_back(&mut self) -> Option<T> { self.iter.next_back() }\n}\n\nimpl<T> Drop for IntoIter<T> {\n    fn drop(&mut self) {\n        for _ in &mut *self {}\n    }\n}\n\n\n\n\npub struct Drain<'a, T: 'a> {\n    vec: PhantomData<&'a mut Vec<T>>,\n    iter: RawValIter<T>,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> { self.iter.next_back() }\n    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }\n}\n\nimpl<'a, T> DoubleEndedIterator for Drain<'a, T> {\n    fn next_back(&mut self) -> Option<T> { self.iter.next_back() }\n}\n\nimpl<'a, T> Drop for Drain<'a, T> {\n    fn drop(&mut self) {\n        // pre-drain the iter\n        for _ in &mut self.iter {}\n    }\n}\n\n/// Abort the process, we're out of memory!\n///\n/// In practice this is probably dead code on most OSes\nfn oom() {\n    ::std::process::exit(-9999);\n}\n\n# fn main() {}\n```\n"
  },
  {
    "path": "nomicon/vec-insert-remove.md",
    "content": "% Insert and Remove\n\nSomething *not* provided by slice is `insert` and `remove`, so let's do those\nnext.\n\nInsert needs to shift all the elements at the target index to the right by one.\nTo do this we need to use `ptr::copy`, which is our version of C's `memmove`.\nThis copies some chunk of memory from one location to another, correctly\nhandling the case where the source and destination overlap (which will\ndefinitely happen here).\n\nIf we insert at index `i`, we want to shift the `[i .. len]` to `[i+1 .. len+1]`\nusing the old len.\n\n```rust,ignore\npub fn insert(&mut self, index: usize, elem: T) {\n    // Note: `<=` because it's valid to insert after everything\n    // which would be equivalent to push.\n    assert!(index <= self.len, \"index out of bounds\");\n    if self.cap == self.len { self.grow(); }\n\n    unsafe {\n        if index < self.len {\n            // ptr::copy(src, dest, len): \"copy from source to dest len elems\"\n            ptr::copy(self.ptr.offset(index as isize),\n                      self.ptr.offset(index as isize + 1),\n                      self.len - index);\n        }\n        ptr::write(self.ptr.offset(index as isize), elem);\n        self.len += 1;\n    }\n}\n```\n\nRemove behaves in the opposite manner. We need to shift all the elements from\n`[i+1 .. len + 1]` to `[i .. len]` using the *new* len.\n\n```rust,ignore\npub fn remove(&mut self, index: usize) -> T {\n    // Note: `<` because it's *not* valid to remove after everything\n    assert!(index < self.len, \"index out of bounds\");\n    unsafe {\n        self.len -= 1;\n        let result = ptr::read(self.ptr.offset(index as isize));\n        ptr::copy(self.ptr.offset(index as isize + 1),\n                  self.ptr.offset(index as isize),\n                  self.len - index);\n        result\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/vec-into-iter.md",
    "content": "% IntoIter\n\nLet's move on to writing iterators. `iter` and `iter_mut` have already been\nwritten for us thanks to The Magic of Deref. However there's two interesting\niterators that Vec provides that slices can't: `into_iter` and `drain`.\n\nIntoIter consumes the Vec by-value, and can consequently yield its elements\nby-value. In order to enable this, IntoIter needs to take control of Vec's\nallocation.\n\nIntoIter needs to be DoubleEnded as well, to enable reading from both ends.\nReading from the back could just be implemented as calling `pop`, but reading\nfrom the front is harder. We could call `remove(0)` but that would be insanely\nexpensive. Instead we're going to just use ptr::read to copy values out of\neither end of the Vec without mutating the buffer at all.\n\nTo do this we're going to use a very common C idiom for array iteration. We'll\nmake two pointers; one that points to the start of the array, and one that\npoints to one-element past the end. When we want an element from one end, we'll\nread out the value pointed to at that end and move the pointer over by one. When\nthe two pointers are equal, we know we're done.\n\nNote that the order of read and offset are reversed for `next` and `next_back`\nFor `next_back` the pointer is always after the element it wants to read next,\nwhile for `next` the pointer is always at the element it wants to read next.\nTo see why this is, consider the case where every element but one has been\nyielded.\n\nThe array looks like this:\n\n```text\n          S  E\n[X, X, X, O, X, X, X]\n```\n\nIf E pointed directly at the element it wanted to yield next, it would be\nindistinguishable from the case where there are no more elements to yield.\n\nAlthough we don't actually care about it during iteration, we also need to hold\nonto the Vec's allocation information in order to free it once IntoIter is\ndropped.\n\nSo we're going to use the following struct:\n\n```rust,ignore\nstruct IntoIter<T> {\n    buf: Unique<T>,\n    cap: usize,\n    start: *const T,\n    end: *const T,\n}\n```\n\nAnd this is what we end up with for initialization:\n\n```rust,ignore\nimpl<T> Vec<T> {\n    fn into_iter(self) -> IntoIter<T> {\n        // Can't destructure Vec since it's Drop\n        let ptr = self.ptr;\n        let cap = self.cap;\n        let len = self.len;\n\n        // Make sure not to drop Vec since that will free the buffer\n        mem::forget(self);\n\n        unsafe {\n            IntoIter {\n                buf: ptr,\n                cap: cap,\n                start: *ptr,\n                end: if cap == 0 {\n                    // can't offset off this pointer, it's not allocated!\n                    *ptr\n                } else {\n                    ptr.offset(len as isize)\n                }\n            }\n        }\n    }\n}\n```\n\nHere's iterating forward:\n\n```rust,ignore\nimpl<T> Iterator for IntoIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                let result = ptr::read(self.start);\n                self.start = self.start.offset(1);\n                Some(result)\n            }\n        }\n    }\n\n    fn size_hint(&self) -> (usize, Option<usize>) {\n        let len = (self.end as usize - self.start as usize)\n                  / mem::size_of::<T>();\n        (len, Some(len))\n    }\n}\n```\n\nAnd here's iterating backwards.\n\n```rust,ignore\nimpl<T> DoubleEndedIterator for IntoIter<T> {\n    fn next_back(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                self.end = self.end.offset(-1);\n                Some(ptr::read(self.end))\n            }\n        }\n    }\n}\n```\n\nBecause IntoIter takes ownership of its allocation, it needs to implement Drop\nto free it. However it also wants to implement Drop to drop any elements it\ncontains that weren't yielded.\n\n\n```rust,ignore\nimpl<T> Drop for IntoIter<T> {\n    fn drop(&mut self) {\n        if self.cap != 0 {\n            // drop any remaining elements\n            for _ in &mut *self {}\n\n            let align = mem::align_of::<T>();\n            let elem_size = mem::size_of::<T>();\n            let num_bytes = elem_size * self.cap;\n            unsafe {\n                heap::deallocate(*self.buf as *mut _, num_bytes, align);\n            }\n        }\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/vec-layout.md",
    "content": "% Layout\n\nFirst off, we need to come up with the struct layout. A Vec has three parts:\na pointer to the allocation, the size of the allocation, and the number of\nelements that have been initialized.\n\nNaively, this means we just want this design:\n\n```rust\npub struct Vec<T> {\n    ptr: *mut T,\n    cap: usize,\n    len: usize,\n}\n# fn main() {}\n```\n\nAnd indeed this would compile. Unfortunately, it would be incorrect. First, the\ncompiler will give us too strict variance. So a `&Vec<&'static str>`\ncouldn't be used where an `&Vec<&'a str>` was expected. More importantly, it\nwill give incorrect ownership information to the drop checker, as it will\nconservatively assume we don't own any values of type `T`. See [the chapter\non ownership and lifetimes][ownership] for all the details on variance and\ndrop check.\n\nAs we saw in the ownership chapter, we should use `Unique<T>` in place of\n`*mut T` when we have a raw pointer to an allocation we own. Unique is unstable,\nso we'd like to not use it if possible, though.\n\nAs a recap, Unique is a wrapper around a raw pointer that declares that:\n\n* We are variant over `T`\n* We may own a value of type `T` (for drop check)\n* We are Send/Sync if `T` is Send/Sync\n* We deref to `*mut T` (so it largely acts like a `*mut` in our code)\n* Our pointer is never null (so `Option<Vec<T>>` is null-pointer-optimized)\n\nWe can implement all of the above requirements except for the last\none in stable Rust:\n\n```rust\nuse std::marker::PhantomData;\nuse std::ops::Deref;\nuse std::mem;\n\nstruct Unique<T> {\n    ptr: *const T,              // *const for variance\n    _marker: PhantomData<T>,    // For the drop checker\n}\n\n// Deriving Send and Sync is safe because we are the Unique owners\n// of this data. It's like Unique<T> is \"just\" T.\nunsafe impl<T: Send> Send for Unique<T> {}\nunsafe impl<T: Sync> Sync for Unique<T> {}\n\nimpl<T> Unique<T> {\n    pub fn new(ptr: *mut T) -> Self {\n        Unique { ptr: ptr, _marker: PhantomData }\n    }\n}\n\nimpl<T> Deref for Unique<T> {\n    type Target = *mut T;\n    fn deref(&self) -> &*mut T {\n        // There's no way to cast the *const to a *mut\n        // while also taking a reference. So we just\n        // transmute it since it's all \"just pointers\".\n        unsafe { mem::transmute(&self.ptr) }\n    }\n}\n# fn main() {}\n```\n\nUnfortunately the mechanism for stating that your value is non-zero is\nunstable and unlikely to be stabilized soon. As such we're just going to\ntake the hit and use std's Unique:\n\n\n```rust\n#![feature(unique)]\n\nuse std::ptr::{Unique, self};\n\npub struct Vec<T> {\n    ptr: Unique<T>,\n    cap: usize,\n    len: usize,\n}\n\n# fn main() {}\n```\n\nIf you don't care about the null-pointer optimization, then you can use the\nstable code. However we will be designing the rest of the code around enabling\nthe optimization. In particular, `Unique::new` is unsafe to call, because\nputting `null` inside of it is Undefined Behavior. Our stable Unique doesn't\nneed `new` to be unsafe because it doesn't make any interesting guarantees about\nits contents.\n\n[ownership]: ownership.html\n"
  },
  {
    "path": "nomicon/vec-push-pop.md",
    "content": "% Push and Pop\n\nAlright. We can initialize. We can allocate. Let's actually implement some\nfunctionality! Let's start with `push`. All it needs to do is check if we're\nfull to grow, unconditionally write to the next index, and then increment our\nlength.\n\nTo do the write we have to be careful not to evaluate the memory we want to write\nto. At worst, it's truly uninitialized memory from the allocator. At best it's the\nbits of some old value we popped off. Either way, we can't just index to the memory\nand dereference it, because that will evaluate the memory as a valid instance of\nT. Worse, `foo[idx] = x` will try to call `drop` on the old value of `foo[idx]`!\n\nThe correct way to do this is with `ptr::write`, which just blindly overwrites the\ntarget address with the bits of the value we provide. No evaluation involved.\n\nFor `push`, if the old len (before push was called) is 0, then we want to write\nto the 0th index. So we should offset by the old len.\n\n```rust,ignore\npub fn push(&mut self, elem: T) {\n    if self.len == self.cap { self.grow(); }\n\n    unsafe {\n        ptr::write(self.ptr.offset(self.len as isize), elem);\n    }\n\n    // Can't fail, we'll OOM first.\n    self.len += 1;\n}\n```\n\nEasy! How about `pop`? Although this time the index we want to access is\ninitialized, Rust won't just let us dereference the location of memory to move\nthe value out, because that would leave the memory uninitialized! For this we\nneed `ptr::read`, which just copies out the bits from the target address and\ninterprets it as a value of type T. This will leave the memory at this address\nlogically uninitialized, even though there is in fact a perfectly good instance\nof T there.\n\nFor `pop`, if the old len is 1, we want to read out of the 0th index. So we\nshould offset by the new len.\n\n```rust,ignore\npub fn pop(&mut self) -> Option<T> {\n    if self.len == 0 {\n        None\n    } else {\n        self.len -= 1;\n        unsafe {\n            Some(ptr::read(self.ptr.offset(self.len as isize)))\n        }\n    }\n}\n```\n"
  },
  {
    "path": "nomicon/vec-raw.md",
    "content": "% RawVec\n\nWe've actually reached an interesting situation here: we've duplicated the logic\nfor specifying a buffer and freeing its memory in Vec and IntoIter. Now that\nwe've implemented it and identified *actual* logic duplication, this is a good\ntime to perform some logic compression.\n\nWe're going to abstract out the `(ptr, cap)` pair and give them the logic for\nallocating, growing, and freeing:\n\n```rust,ignore\nstruct RawVec<T> {\n    ptr: Unique<T>,\n    cap: usize,\n}\n\nimpl<T> RawVec<T> {\n    fn new() -> Self {\n        assert!(mem::size_of::<T>() != 0, \"TODO: implement ZST support\");\n        unsafe {\n            RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: 0 }\n        }\n    }\n\n    // unchanged from Vec\n    fn grow(&mut self) {\n        unsafe {\n            let align = mem::align_of::<T>();\n            let elem_size = mem::size_of::<T>();\n\n            let (new_cap, ptr) = if self.cap == 0 {\n                let ptr = heap::allocate(elem_size, align);\n                (1, ptr)\n            } else {\n                let new_cap = 2 * self.cap;\n                let ptr = heap::reallocate(*self.ptr as *mut _,\n                                            self.cap * elem_size,\n                                            new_cap * elem_size,\n                                            align);\n                (new_cap, ptr)\n            };\n\n            // If allocate or reallocate fail, we'll get `null` back\n            if ptr.is_null() { oom() }\n\n            self.ptr = Unique::new(ptr as *mut _);\n            self.cap = new_cap;\n        }\n    }\n}\n\n\nimpl<T> Drop for RawVec<T> {\n    fn drop(&mut self) {\n        if self.cap != 0 {\n            let align = mem::align_of::<T>();\n            let elem_size = mem::size_of::<T>();\n            let num_bytes = elem_size * self.cap;\n            unsafe {\n                heap::deallocate(*self.ptr as *mut _, num_bytes, align);\n            }\n        }\n    }\n}\n```\n\nAnd change Vec as follows:\n\n```rust,ignore\npub struct Vec<T> {\n    buf: RawVec<T>,\n    len: usize,\n}\n\nimpl<T> Vec<T> {\n    fn ptr(&self) -> *mut T { *self.buf.ptr }\n\n    fn cap(&self) -> usize { self.buf.cap }\n\n    pub fn new() -> Self {\n        Vec { buf: RawVec::new(), len: 0 }\n    }\n\n    // push/pop/insert/remove largely unchanged:\n    // * `self.ptr -> self.ptr()`\n    // * `self.cap -> self.cap()`\n    // * `self.grow -> self.buf.grow()`\n}\n\nimpl<T> Drop for Vec<T> {\n    fn drop(&mut self) {\n        while let Some(_) = self.pop() {}\n        // deallocation is handled by RawVec\n    }\n}\n```\n\nAnd finally we can really simplify IntoIter:\n\n```rust,ignore\nstruct IntoIter<T> {\n    _buf: RawVec<T>, // we don't actually care about this. Just need it to live.\n    start: *const T,\n    end: *const T,\n}\n\n// next and next_back literally unchanged since they never referred to the buf\n\nimpl<T> Drop for IntoIter<T> {\n    fn drop(&mut self) {\n        // only need to ensure all our elements are read;\n        // buffer will clean itself up afterwards.\n        for _ in &mut *self {}\n    }\n}\n\nimpl<T> Vec<T> {\n    pub fn into_iter(self) -> IntoIter<T> {\n        unsafe {\n            // need to use ptr::read to unsafely move the buf out since it's\n            // not Copy, and Vec implements Drop (so we can't destructure it).\n            let buf = ptr::read(&self.buf);\n            let len = self.len;\n            mem::forget(self);\n\n            IntoIter {\n                start: *buf.ptr,\n                end: buf.ptr.offset(len as isize),\n                _buf: buf,\n            }\n        }\n    }\n}\n```\n\nMuch better.\n"
  },
  {
    "path": "nomicon/vec-zsts.md",
    "content": "% Handling Zero-Sized Types\n\nIt's time. We're going to fight the specter that is zero-sized types. Safe Rust\n*never* needs to care about this, but Vec is very intensive on raw pointers and\nraw allocations, which are exactly the two things that care about\nzero-sized types. We need to be careful of two things:\n\n* The raw allocator API has undefined behavior if you pass in 0 for an\n  allocation size.\n* raw pointer offsets are no-ops for zero-sized types, which will break our\n  C-style pointer iterator.\n\nThankfully we abstracted out pointer-iterators and allocating handling into\nRawValIter and RawVec respectively. How mysteriously convenient.\n\n\n\n\n## Allocating Zero-Sized Types\n\nSo if the allocator API doesn't support zero-sized allocations, what on earth\ndo we store as our allocation? Why, `heap::EMPTY` of course! Almost every operation\nwith a ZST is a no-op since ZSTs have exactly one value, and therefore no state needs\nto be considered to store or load them. This actually extends to `ptr::read` and\n`ptr::write`: they won't actually look at the pointer at all. As such we never need\nto change the pointer.\n\nNote however that our previous reliance on running out of memory before overflow is\nno longer valid with zero-sized types. We must explicitly guard against capacity\noverflow for zero-sized types.\n\nDue to our current architecture, all this means is writing 3 guards, one in each\nmethod of RawVec.\n\n```rust,ignore\nimpl<T> RawVec<T> {\n    fn new() -> Self {\n        unsafe {\n            // !0 is usize::MAX. This branch should be stripped at compile time.\n            let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };\n\n            // heap::EMPTY doubles as \"unallocated\" and \"zero-sized allocation\"\n            RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: cap }\n        }\n    }\n\n    fn grow(&mut self) {\n        unsafe {\n            let elem_size = mem::size_of::<T>();\n\n            // since we set the capacity to usize::MAX when elem_size is\n            // 0, getting to here necessarily means the Vec is overfull.\n            assert!(elem_size != 0, \"capacity overflow\");\n\n            let align = mem::align_of::<T>();\n\n            let (new_cap, ptr) = if self.cap == 0 {\n                let ptr = heap::allocate(elem_size, align);\n                (1, ptr)\n            } else {\n                let new_cap = 2 * self.cap;\n                let ptr = heap::reallocate(*self.ptr as *mut _,\n                                            self.cap * elem_size,\n                                            new_cap * elem_size,\n                                            align);\n                (new_cap, ptr)\n            };\n\n            // If allocate or reallocate fail, we'll get `null` back\n            if ptr.is_null() { oom() }\n\n            self.ptr = Unique::new(ptr as *mut _);\n            self.cap = new_cap;\n        }\n    }\n}\n\nimpl<T> Drop for RawVec<T> {\n    fn drop(&mut self) {\n        let elem_size = mem::size_of::<T>();\n\n        // don't free zero-sized allocations, as they were never allocated.\n        if self.cap != 0 && elem_size != 0 {\n            let align = mem::align_of::<T>();\n\n            let num_bytes = elem_size * self.cap;\n            unsafe {\n                heap::deallocate(*self.ptr as *mut _, num_bytes, align);\n            }\n        }\n    }\n}\n```\n\nThat's it. We support pushing and popping zero-sized types now. Our iterators\n(that aren't provided by slice Deref) are still busted, though.\n\n\n\n\n## Iterating Zero-Sized Types\n\nZero-sized offsets are no-ops. This means that our current design will always\ninitialize `start` and `end` as the same value, and our iterators will yield\nnothing. The current solution to this is to cast the pointers to integers,\nincrement, and then cast them back:\n\n```rust,ignore\nimpl<T> RawValIter<T> {\n    unsafe fn new(slice: &[T]) -> Self {\n        RawValIter {\n            start: slice.as_ptr(),\n            end: if mem::size_of::<T>() == 0 {\n                ((slice.as_ptr() as usize) + slice.len()) as *const _\n            } else if slice.len() == 0 {\n                slice.as_ptr()\n            } else {\n                slice.as_ptr().offset(slice.len() as isize)\n            }\n        }\n    }\n}\n```\n\nNow we have a different bug. Instead of our iterators not running at all, our\niterators now run *forever*. We need to do the same trick in our iterator impls.\nAlso, our size_hint computation code will divide by 0 for ZSTs. Since we'll\nbasically be treating the two pointers as if they point to bytes, we'll just\nmap size 0 to divide by 1.\n\n```rust,ignore\nimpl<T> Iterator for RawValIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                let result = ptr::read(self.start);\n                self.start = if mem::size_of::<T>() == 0 {\n                    (self.start as usize + 1) as *const _\n                } else {\n                    self.start.offset(1)\n                };\n                Some(result)\n            }\n        }\n    }\n\n    fn size_hint(&self) -> (usize, Option<usize>) {\n        let elem_size = mem::size_of::<T>();\n        let len = (self.end as usize - self.start as usize)\n                  / if elem_size == 0 { 1 } else { elem_size };\n        (len, Some(len))\n    }\n}\n\nimpl<T> DoubleEndedIterator for RawValIter<T> {\n    fn next_back(&mut self) -> Option<T> {\n        if self.start == self.end {\n            None\n        } else {\n            unsafe {\n                self.end = if mem::size_of::<T>() == 0 {\n                    (self.end as usize - 1) as *const _\n                } else {\n                    self.end.offset(-1)\n                };\n                Some(ptr::read(self.end))\n            }\n        }\n    }\n}\n```\n\nAnd that's it. Iteration works!\n"
  },
  {
    "path": "nomicon/vec.md",
    "content": "% Example: Implementing Vec\n\nTo bring everything together, we're going to write `std::Vec` from scratch.\nBecause all the best tools for writing unsafe code are unstable, this\nproject will only work on nightly (as of Rust 1.9.0). With the exception of the\nallocator API, much of the unstable code we'll use is expected to be stabilized\nin a similar form as it is today.\n\nHowever we will generally try to avoid unstable code where possible. In\nparticular we won't use any intrinsics that could make a code a little\nbit nicer or efficient because intrinsics are permanently unstable. Although\nmany intrinsics *do* become stabilized elsewhere (`std::ptr` and `str::mem`\nconsist of many intrinsics).\n\nUltimately this means our implementation may not take advantage of all\npossible optimizations, though it will be by no means *naive*. We will\ndefinitely get into the weeds over nitty-gritty details, even\nwhen the problem doesn't *really* merit it.\n\nYou wanted advanced. We're gonna go advanced.\n"
  },
  {
    "path": "nomicon/working-with-unsafe.md",
    "content": "% Working with Unsafe\n\nRust generally only gives us the tools to talk about Unsafe Rust in a scoped and\nbinary manner. Unfortunately, reality is significantly more complicated than\nthat. For instance, consider the following toy function:\n\n```rust\nfn index(idx: usize, arr: &[u8]) -> Option<u8> {\n    if idx < arr.len() {\n        unsafe {\n            Some(*arr.get_unchecked(idx))\n        }\n    } else {\n        None\n    }\n}\n```\n\nClearly, this function is safe. We check that the index is in bounds, and if it\nis, index into the array in an unchecked manner. But even in such a trivial\nfunction, the scope of the unsafe block is questionable. Consider changing the\n`<` to a `<=`:\n\n```rust\nfn index(idx: usize, arr: &[u8]) -> Option<u8> {\n    if idx <= arr.len() {\n        unsafe {\n            Some(*arr.get_unchecked(idx))\n        }\n    } else {\n        None\n    }\n}\n```\n\nThis program is now unsound, and yet *we only modified safe code*. This is the\nfundamental problem of safety: it's non-local. The soundness of our unsafe\noperations necessarily depends on the state established by otherwise\n\"safe\" operations.\n\nSafety is modular in the sense that opting into unsafety doesn't require you\nto consider arbitrary other kinds of badness. For instance, doing an unchecked\nindex into a slice doesn't mean you suddenly need to worry about the slice being\nnull or containing uninitialized memory. Nothing fundamentally changes. However\nsafety *isn't* modular in the sense that programs are inherently stateful and\nyour unsafe operations may depend on arbitrary other state.\n\nTrickier than that is when we get into actual statefulness. Consider a simple\nimplementation of `Vec`:\n\n```rust\nuse std::ptr;\n\n// Note this definition is insufficient. See the section on implementing Vec.\npub struct Vec<T> {\n    ptr: *mut T,\n    len: usize,\n    cap: usize,\n}\n\n// Note this implementation does not correctly handle zero-sized types.\n// We currently live in a nice imaginary world of only positive fixed-size\n// types.\nimpl<T> Vec<T> {\n    pub fn push(&mut self, elem: T) {\n        if self.len == self.cap {\n            // not important for this example\n            self.reallocate();\n        }\n        unsafe {\n            ptr::write(self.ptr.offset(self.len as isize), elem);\n            self.len += 1;\n        }\n    }\n\n    # fn reallocate(&mut self) { }\n}\n\n# fn main() {}\n```\n\nThis code is simple enough to reasonably audit and verify. Now consider\nadding the following method:\n\n```rust,ignore\nfn make_room(&mut self) {\n    // grow the capacity\n    self.cap += 1;\n}\n```\n\nThis code is 100% Safe Rust but it is also completely unsound. Changing the\ncapacity violates the invariants of Vec (that `cap` reflects the allocated space\nin the Vec). This is not something the rest of Vec can guard against. It *has*\nto trust the capacity field because there's no way to verify it.\n\n`unsafe` does more than pollute a whole function: it pollutes a whole *module*.\nGenerally, the only bullet-proof way to limit the scope of unsafe code is at the\nmodule boundary with privacy.\n\nHowever this works *perfectly*. The existence of `make_room` is *not* a\nproblem for the soundness of Vec because we didn't mark it as public. Only the\nmodule that defines this function can call it. Also, `make_room` directly\naccesses the private fields of Vec, so it can only be written in the same module\nas Vec.\n\nIt is therefore possible for us to write a completely safe abstraction that\nrelies on complex invariants. This is *critical* to the relationship between\nSafe Rust and Unsafe Rust. We have already seen that Unsafe code must trust\n*some* Safe code, but can't trust *generic* Safe code. It can't trust an\narbitrary implementor of a trait or any function that was passed to it to be\nwell-behaved in a way that safe code doesn't care about.\n\nHowever if unsafe code couldn't prevent client safe code from messing with its\nstate in arbitrary ways, safety would be a lost cause. Thankfully, it *can*\nprevent arbitrary code from messing with critical state due to privacy.\n\nSafety lives!\n\n"
  },
  {
    "path": "nomicon_meta.yml",
    "content": "---\ntitle: \"The Rustonomicon\"\nauthor: \"The Rust Team\"\ndate: {release_date}\ndescription: \"This book digs into all the awful details that are necessary to understand in order to write correct Unsafe Rust programs. Due to the nature of this problem, it may lead to unleashing untold horrors that shatter your psyche into a billion infinitesimal fragments of despair.\"\nlanguage: en\ndocumentclass: book\nlinks-as-notes: true\nverbatim-in-note: true\ntoc-depth: 2\nmonofont: \"DejaVu Sans Mono\"\n...\n"
  },
  {
    "path": "src/convert_book/index.rs",
    "content": "use std::error::Error;\nuse std::path::Path;\nuse std::fs;\nuse std::collections::BTreeMap;\nuse std::ascii::AsciiExt;\n\nuse regex::Regex;\n\nconst FILENAME_PATTRN: &'static str =\n    r\"^(?P<prefix>\\w+)-(?P<date>\\d{4}-\\d{2}-\\d{2})\\.(?P<ext>.+)$\";\n\ntype FileListing = Vec<(String, String)>;\n\nfn list_file_groups(path: &str) -> Result<FileListing, Box<Error>> {\n    let filename_pattern = Regex::new(FILENAME_PATTRN).unwrap();\n\n    let files = try!(fs::read_dir(&Path::new(path)))\n    .filter(Result::is_ok)\n    .map(|x| x.unwrap().path())\n    .filter_map(|x| {\n        x.file_name()\n         .and_then(|a| { a.to_str() })\n         .and_then(|b| -> Option<String> { Some(b.into()) })\n    })\n    .flat_map(|name| -> Option<(String, String)> {\n        // Extract the date from names like 'trpl-2015-05-13.a4.pdf'.\n        // This also excludes the `index.html` file as it contains no date.\n        if let Some(caps) = filename_pattern.captures(&name) {\n            if let Some(version) = caps.name(\"date\") {\n                return Some((version.to_owned(), name.to_owned()));\n            }\n        }\n        return None;\n    })\n    .collect();\n\n    Ok(files)\n}\n\npub fn render_index(path: &str) -> Result<String, Box<Error>> {\n    let filename_pattern = Regex::new(FILENAME_PATTRN).unwrap();\n\n    let files = try!(list_file_groups(path));\n    let mut versions: BTreeMap<String, Vec<String>> = BTreeMap::new();\n\n    for &(ref version, ref filename) in &files {\n        let file = versions.entry(version.clone()).or_insert(vec![]);\n        file.push(filename.clone());\n    }\n\n    let mut file_listing = String::new();\n\n    for (version, files) in versions.iter().rev() {\n        file_listing.push_str(\"<li>\\n<h2>\");\n        file_listing.push_str(&version);\n        file_listing.push_str(\"</h2>\\n<ul>\");\n\n        for file in files {\n            file_listing.push_str(&format!(\n                \"<li><a href='{file_name}'>{file_title}</a></li>\\n\",\n                file_name = file,\n                file_title = filename_pattern\n                    .replace_all(file, \"$prefix $ext\")\n                    .to_ascii_uppercase()\n            ));\n        }\n\n        file_listing.push_str(\"</ul>\\n</li>\");\n    }\n\n    let output = format!(include_str!(\"../../lib/index_template.html\"),\n                         css = include_str!(\"../../lib/index.css\"),\n                         file_listing = file_listing);\n\n    Ok(output)\n}\n"
  },
  {
    "path": "src/convert_book/markdown.rs",
    "content": "use std::path::Path;\nuse std::error::Error;\nuse regex::Regex;\n\nuse helpers::*;\n\n/// Poor man's progress indicator\nmacro_rules! put {\n    ($e:expr) => ({\n        {\n            use std::io;\n            use std::io::Write;\n            print!($e);\n            io::stdout().flush().unwrap();\n        }\n    })\n}\n\n#[derive(Debug, Hash, PartialEq, Eq)]\nstruct Chapter {\n    file: String,\n    headline: String,\n}\n\nfn get_chapters(toc: &str) -> Vec<Chapter> {\n    let toc_pattern = Regex::new(r\"(?x)\n        (?P<indent>\\s*?)\n        \\*\\s\n        \\[\n        (?P<title>.+?)\n        \\]\n        \\(\n        (?P<filename>.+?)\n        \\)\n    \").unwrap();\n\n    let filename_pattern = Regex::new(r\"(?x)\n        ^\n        (?P<path>(.*)/)?\n        (?P<name>(.*?))\n        (?P<ext>\\.(\\w*))?\n        $\n    \").unwrap();\n\n    toc.lines()\n    .filter_map(|l| toc_pattern.captures(l))\n    .map(|link| {\n        let level = if link.name(\"indent\").unwrap().chars().count() == 0 { \"#\" } else { \"##\" };\n        let id = filename_pattern.captures(\n            link.name(\"filename\").unwrap()\n        ).unwrap().name(\"name\").unwrap();\n\n        let headline = format!(\n            \"{level} {name} {{#sec--{link}}}\\n\",\n            level = level, name = link.name(\"title\").unwrap(), link = id\n        );\n\n        Chapter {\n            file: link.name(\"filename\").unwrap().into(),\n            headline: headline,\n        }\n    })\n    .collect::<Vec<Chapter>>()\n}\n\npub fn to_single_file(src_path: &Path, meta: &str) -> Result<String, Box<Error>> {\n    put!(\"Reading book\");\n\n    let toc = try!(file::get_file_content(&src_path.join(\"SUMMARY.md\")));\n    put!(\".\");\n\n    let mut book = String::new();\n\n    book.push_str(meta);\n    book.push_str(\"\\n\");\n\n    {\n        // Readme ~ \"Getting Started\"\n        let file = try!(file::get_file_content(&src_path.join(\"README.md\")));\n        let mut content = try!(adjust_header_level::adjust_header_level(&file, 1));\n        content = try!(remove_file_title::remove_file_title(&content));\n        content = try!(adjust_reference_names::adjust_reference_name(&content, \"readme\"));\n        content = try!(normalize::normalize(&content));\n\n        put!(\".\");\n\n        book.push_str(\"\\n\\n\");\n        book.push_str(\"# Introduction\");\n        book.push_str(\"\\n\\n\");\n        book.push_str(&content);\n    }\n\n    for chapter in &get_chapters(&toc) {\n        let file = try!(file::get_file_content(&src_path.join(&chapter.file)));\n\n        let mut content = try!(adjust_header_level::adjust_header_level(&file, 3));\n        content = try!(remove_file_title::remove_file_title(&content));\n        content = try!(adjust_reference_names::adjust_reference_name(&content, &chapter.file));\n        content = try!(normalize::normalize(&content));\n\n        put!(\".\");\n\n        book.push_str(\"\\n\\n\");\n        book.push_str(&chapter.headline);\n        book.push_str(\"\\n\");\n        book.push_str(&content);\n    }\n\n    put!(\" done.\\n\");\n\n    Ok(book)\n}\n"
  },
  {
    "path": "src/convert_book/mod.rs",
    "content": "//! Tools to compile the book\n\npub mod index;\npub mod markdown;\npub mod options;\npub mod pandoc;\n\nuse std::path::Path;\nuse std::error::Error;\nuse helpers;\nuse convert_book::pandoc::save_as;\n\n/// Render book in different formats\npub fn render_book(prefix: &str, src_path: &Path, meta_file: &str) -> Result<(), Box<Error>> {\n    let meta_data = try!(helpers::file::get_file_content(meta_file));\n\n    let book = try!(markdown::to_single_file(src_path,\n                                             &meta_data.replace(\"{release_date}\",\n                                                                options::RELEASE_DATE)));\n\n    try!(helpers::file::write_string_to_file(&book,\n                                             &format!(\"dist/{}-{}.md\",\n                                                      prefix,\n                                                      options::RELEASE_DATE)));\n    println!(\"[✓] {}\", \"MD\");\n\n    try!(save_as(&book, prefix, \"html\", options::HTML));\n    try!(save_as(&book, prefix, \"epub\", options::EPUB));\n\n    let cc_book = helpers::convert_checkmarks::convert_checkmarks(&book);    \n    try!(save_as(&cc_book, prefix, \"tex\", options::LATEX));\n\n    let plain_book = helpers::remove_emojis::remove_emojis(&cc_book);\n    try!(save_as(&plain_book,\n                 prefix,\n                 \"a4.pdf\",\n                 &format!(r\"{} --variable papersize=a4paper\", options::LATEX)));\n    try!(save_as(&plain_book,\n                 prefix,\n                 \"letter.pdf\",\n                 &format!(r\"{} --variable papersize=letterpaper\",\n                          options::LATEX)));\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/convert_book/options.rs",
    "content": "pub const RELEASE_DATE: &'static str = \"2016-10-01\";\n\npub const MARKDOWN: &'static str = \"markdown+grid_tables+pipe_tables-simple_tables+raw_html+implicit_figures+footnotes+intraword_underscores+auto_identifiers-inline_code_attributes\";\n\npub const HTML: &'static str = \"--smart --normalize --standalone --self-contained --highlight-style=tango --table-of-contents --section-divs --template=lib/template.html --css=lib/pandoc.css --to=html5\";\n\npub const EPUB: &'static str = \"--smart --normalize --standalone --self-contained --highlight-style=tango --epub-stylesheet=lib/epub.css --table-of-contents\";\n\npub const LATEX: &'static str = \"--smart --normalize --standalone --self-contained --highlight-style=tango --chapters --table-of-contents --template=lib/template.tex --latex-engine=xelatex --to=latex\";\n"
  },
  {
    "path": "src/convert_book/pandoc.rs",
    "content": "use std::error::Error;\nuse std::ascii::AsciiExt;\n\nuse helpers::shell_pipe;\nuse convert_book::options;\n\npub fn run(args: &str, input: &str) -> Result<String, Box<Error>> {\n    shell_pipe::run(\"pandoc\", args, input)\n}\n\npub fn save_as(book: &str, prefix: &str, format: &str, opts: &str) -> Result<(), Box<Error>> {\n    let opts = format!(\"--from={markdown_opts} {opts} \\\n                        --output=dist/{prefix}-{release_date}.{format}\",\n                       markdown_opts = options::MARKDOWN,\n                       opts = opts,\n                       prefix = prefix,\n                       release_date = options::RELEASE_DATE,\n                       format = format);\n\n    try!(run(&opts, &book));\n\n    println!(\"[✓] {}\", format.to_ascii_uppercase());\n\n    Ok(())\n}\n\n#[test]\n#[ignore]\nfn dry_run() {\n    let output = run(\"--from=markdown --base-header-level=2 --to=markdown --atx-headers\",\n                     \"# Hi there!\\n\")\n                     .unwrap();\n\n    assert_eq!(output, \"## Hi there!\\n\");\n}\n"
  },
  {
    "path": "src/helpers/adjust_header_level.rs",
    "content": "use std::error::Error;\nuse std::iter::repeat;\nuse regex::Regex;\n\nconst CODE_BLOCK_TOGGLE: &'static str = \"```\";\n\npub type HeaderLevel = i32;\n\npub fn adjust_header_level(input: &str, base_level: HeaderLevel) -> Result<String, Box<Error>> {\n    let headline_pattern = Regex::new(r\"(?x)\n        ^\n        (?P<level>[\\x23]+)  # A bunch of hash symbols\n        \\s\n        (?P<title>.+)       # Title, and maybe id\n        $\n    \").unwrap();\n\n    let mut in_code_block = false;\n\n    let output = input.lines()\n    .fold(String::new(), |initial, line| {\n        match (in_code_block, line.starts_with(CODE_BLOCK_TOGGLE)) {\n            (true,  false) => {\n                // Code? I don't care about that stuff.\n                return initial + line + \"\\n\";\n            }\n            (true,  true ) => { in_code_block = false; }\n            (false, true ) => { in_code_block = true; }\n            _ => {}\n        };\n\n        if let Some(headline) = headline_pattern.captures(line) {\n            // level := number of '#'s.\n            // '#' is always 1 byte, so .len() is save to use.\n            let level = headline.name(\"level\").unwrap().len() as i32;\n            let new_level = calc_header_level(base_level, level);\n            let new_headline = format!(\n                \"{level} {title}\\n\",\n                level = repeat(\"#\").take(new_level as usize).collect::<String>(),\n                title = headline.name(\"title\").unwrap()\n            );\n            return initial + &new_headline;\n        }\n\n        initial + line + \"\\n\"\n    });\n\n    Ok(output)\n}\n\nfn calc_header_level(base_level: HeaderLevel, current_level: HeaderLevel) -> HeaderLevel {\n    current_level + base_level - 1\n}\n\n#[test]\nfn header_level_calculation() {\n    //                           base level | current level | new level\n    assert_eq!(calc_header_level(1,           1),             1);\n    assert_eq!(calc_header_level(1,           2),             2);\n    assert_eq!(calc_header_level(2,           2),             3);\n    assert_eq!(calc_header_level(2,           1),             2);\n}\n"
  },
  {
    "path": "src/helpers/adjust_reference_names.rs",
    "content": "use std::error::Error;\nuse regex::{Regex, Captures};\n\nconst CODE_BLOCK_TOGGLE: &'static str = \"```\";\n\npub fn adjust_reference_name(input: &str, prefix: &str) -> Result<String, Box<Error>> {\n    let reference_link = Regex::new(r\"(?x)\n        \\]\\[                # This is a link to a reference\n        (?P<id>.+?)         # The reference name\n        \\]\n    \").unwrap();\n\n    let footnote = Regex::new(r\"(?x)\n        \\[                  # This is a link to a reference\n        \\^                  # Link to footnote begins with `^`\n        (?P<id>.+?)         # The reference name\n        \\]\n    \").unwrap();\n\n    let reference_def = Regex::new(r\"(?x)\n        ^\n        \\[\n        (?P<footnote>\\^)?   # Footnote definition begins with `^`\n        (?P<id>.+)          # The reference name\n        \\]\n        :\\s\n        (?P<link>.+)        # The link url (and maybe the title)\n        $\n    \").unwrap();\n\n    let mut in_code_block = false;\n\n    let output = input.lines()\n    .fold(String::new(), |initial, line| {\n        match (in_code_block, line.starts_with(CODE_BLOCK_TOGGLE)) {\n            (true,  false) => {\n                // Code? I don't care about that stuff.\n                return initial + line + \"\\n\";\n            }\n            (true,  true ) => { in_code_block = false; }\n            (false, true ) => { in_code_block = true; }\n            _ => {}\n        };\n\n        if reference_link.is_match(line) {\n            let new_line = reference_link.replace_all(line, |matches: &Captures| {\n                format!(\"][{prefix}--{id}]\",\n                    prefix = prefix,\n                    id = matches.name(\"id\").expect(\"no id in ref link\")\n                )\n            });\n            return initial + &new_line + \"\\n\";\n        }\n\n        if footnote.is_match(line) {\n            let new_line = footnote.replace_all(line, |matches: &Captures| {\n                format!(\"[^{prefix}--{id}]\",\n                    prefix = prefix,\n                    id = matches.name(\"id\").expect(\"no id in ref link\")\n                )\n            });\n            return initial + &new_line + \"\\n\";\n        }\n\n        if let Some(matches) = reference_def.captures(line) {\n            let new_line = format!(\"[{footnote}{prefix}--{id}]: {link}\",\n                footnote = matches.name(\"footnote\").unwrap_or(\"\"),\n                prefix = prefix,\n                id = matches.name(\"id\").expect(\"no id in ref def\"),\n                link = matches.name(\"link\").expect(\"no ink in ref def\")\n            );\n            return initial + &new_line + \"\\n\";\n        }\n\n        initial + line + \"\\n\"\n    });\n\n    Ok(output)\n}\n\n#[test]\nfn reference_renamer() {\n    assert_eq!(\n        adjust_reference_name(\n            \"Lorem ipsum [dolor sit][amet], [consectetur adipisicing][elit]. Odio provident repellendus temporibus possimus magnam odit [neque obcaecati][illo], ab tenetur deserunt quae quia? Asperiores a hic, maiores quaerat, autem ea!\",\n            \"PREFIX\"\n        ).unwrap(),\n        \"Lorem ipsum [dolor sit][PREFIX--amet], [consectetur adipisicing][PREFIX--elit]. Odio provident repellendus temporibus possimus magnam odit [neque obcaecati][PREFIX--illo], ab tenetur deserunt quae quia? Asperiores a hic, maiores quaerat, autem ea!\\n\"\n\n    );\n}\n"
  },
  {
    "path": "src/helpers/convert_checkmarks.rs",
    "content": "use regex::Regex;\n\npub fn convert_checkmarks(input: &str) -> String {\n    let checks = Regex::new(\"[\\u{2713}\\u{2714}]\").unwrap();\n    // rely on pandoc's raw latex support\n    checks.replace_all(input, \"\\\\checkmark\")\n}\n\n#[test]\nfn checkmark_conversion() {\n    assert_eq!(convert_checkmarks(\"checks: ✓ ✔\"), \"checks: \\\\checkmark \\\\checkmark\");\n}\n"
  },
  {
    "path": "src/helpers/file.rs",
    "content": "use std::io::prelude::*;\nuse std::error::Error;\nuse std::path::Path;\nuse std::fs::File;\n\npub fn get_file_content<P: AsRef<Path>>(path: P) -> Result<String, Box<Error>> {\n    let mut file = try!(File::open(path));\n    let mut buffer = String::new();\n    try!(file.read_to_string(&mut buffer));\n    Ok(buffer)\n}\n\npub fn write_string_to_file(input: &str, name: &str) -> Result<(), Box<Error>> {\n    let mut file = try!(File::create(&Path::new(name)));\n\n    try!(file.write_all(input.as_bytes()));\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/helpers/line_breaks.rs",
    "content": "use std::error::Error;\n\npub fn break_long_line(line: &str, max_len: usize, sep: &str) -> Result<String, Box<Error>> {\n    let sep_length = sep.chars().count() as usize;\n    let mut output = String::with_capacity(line.len());\n\n    // First time: `max_len`, after that `max_len - sep_length`\n    let mut line_end = max_len;\n\n    for (index, ch) in line.chars().enumerate() {\n        if index >= (line_end - 1) {\n            line_end += max_len - sep_length - 1;\n            output.push_str(\"\\n\");\n            output.push_str(sep);\n        }\n        output.push(ch);\n    }\n\n    Ok(output)\n}\n\n#[test]\nfn break_long_lines() {\n    let long_line = \"markdown+grid_tables+pipe_tables+raw_html+implicit_figures+footnotes+intraword_underscores+auto_identifiers-inline_code_attributesmarkdown+grid_tables+pipe_tables+raw_html+implicit_figures+footnotes+intraword_underscores+auto_identifiers-inline_code_attributes\";\n\n    let correct_split = \"markdown+grid_tables+pipe_tables+raw_html+implicit_figures+footnotes+intraword_\n↳ underscores+auto_identifiers-inline_code_attributesmarkdown+grid_tables+pipe_\n↳ tables+raw_html+implicit_figures+footnotes+intraword_underscores+auto_identif\n↳ iers-inline_code_attributes\";\n\n    let max_len = 80;\n\n    let broken = break_long_line(long_line, max_len, \"↳ \").unwrap();\n\n    assert_eq!(broken, correct_split);\n    assert!(broken.lines().all(|x| x.chars().count() <= max_len));\n    assert_eq!(broken.lines().count(), 4);\n}\n"
  },
  {
    "path": "src/helpers/mod.rs",
    "content": "//! Various Helper Functions\n\npub mod adjust_header_level;\npub mod adjust_reference_names;\npub mod convert_checkmarks;\npub mod file;\npub mod line_breaks;\npub mod normalize;\npub mod normalize_code_blocks;\npub mod remove_emojis;\npub mod remove_file_title;\npub mod shell_pipe;\n"
  },
  {
    "path": "src/helpers/normalize.rs",
    "content": "use std::error::Error;\nuse regex::Regex;\n\nuse helpers::normalize_code_blocks::*;\n\nfn normalize_links(input: &str) -> Result<String, Box<Error>> {\n    let mut output = input.replace(r\"../std\", r\"http://doc.rust-lang.org/std\")\n                          .replace(r\"../reference\",\n                                   r\"http://doc.rust-lang.org/reference\")\n                          .replace(r\"../rustc\", r\"http://doc.rust-lang.org/rustc\")\n                          .replace(r\"../syntax\", r\"http://doc.rust-lang.org/syntax\")\n                          .replace(r\"../book\", r\"http://doc.rust-lang.org/book\")\n                          .replace(r\"../adv-book\", r\"http://doc.rust-lang.org/adv-book\")\n                          .replace(r\"../core\", r\"http://doc.rust-lang.org/core\");\n\n    let cross_section_link = Regex::new(r\"]\\((?P<file>[\\w-_]+)\\.html\\)\").unwrap();\n    output = cross_section_link.replace_all(&output, r\"](#sec--$file)\");\n\n    let cross_section_ref = Regex::new(r\"(?m)^\\[(?P<id>.+)\\]:\\s(?P<file>[^:^/]+)\\.html$\").unwrap();\n    output = cross_section_ref.replace_all(&output, r\"[$id]: #sec--$file\");\n\n    let cross_subsection_link = Regex::new(r\"]\\((?P<file>[\\w-_]+)\\.html#(?P<subsection>[\\w-_]+)\\)\")\n                                    .unwrap();\n    output = cross_subsection_link.replace_all(&output, r\"](#$subsection)\");\n\n    let cross_subsection_ref =\n        Regex::new(r\"(?m)^\\[(?P<id>.+)\\]:\\s(?P<file>[^:^/]+)\\.html#(?P<subsection>[\\w-_]+)$\")\n            .unwrap();\n    output = cross_subsection_ref.replace_all(&output, r\"[$id]: #$subsection\");\n\n    Ok(output)\n}\n\nfn normalize_math(input: &str) -> Result<String, Box<Error>> {\n    let superscript = Regex::new(r\"(\\d+)<sup>(\\d+)</sup>\").unwrap();\n    Ok(superscript.replace_all(&input, r\"$1^$2^\"))\n}\n\n\npub fn normalize(input: &str) -> Result<String, Box<Error>> {\n    let mut output;\n\n    output = try!(break_code_blocks(&input, 87, \"↳ \"));\n    output = try!(normalize_code_start(&output));\n    output = try!(normalize_links(&output));\n    output = try!(normalize_math(&output));\n\n    Ok(output)\n}\n"
  },
  {
    "path": "src/helpers/normalize_code_blocks.rs",
    "content": "use std::error::Error;\nuse regex::Regex;\n\nuse helpers::line_breaks;\n\nconst CODE_BLOCK_TOGGLE: &'static str = \"```\";\n\npub fn break_code_blocks(input: &str, max_len: usize, sep: &str) -> Result<String, Box<Error>> {\n    let mut in_code_block = false;\n\n    let output = input.lines()\n    .fold(String::new(), |initial, line| {\n        match (in_code_block, line.starts_with(CODE_BLOCK_TOGGLE)) {\n            (true,  false) => {\n                let lines = line_breaks::break_long_line(line, max_len, sep).unwrap();\n                return initial + &lines + \"\\n\";\n            }\n            (true,  true ) => { in_code_block = false; }\n            (false, true ) => { in_code_block = true; }\n            (false, false) => {}\n        };\n        initial + line + \"\\n\"\n    });\n\n    Ok(output)\n}\n\n\npub fn normalize_code_start(input: &str) -> Result<String, Box<Error>> {\n    let rust_code_block_start = Regex::new(r\"^```(.*)rust(.*)\").unwrap();\n    let hidden_code = Regex::new(r\"^(#\\s.*|#$)\").unwrap();\n\n    let mut in_code_block = false;\n\n    let output = input.lines()\n    .fold(String::new(), |initial, line| {\n        if in_code_block && hidden_code.is_match(line) {\n            initial\n        } else if rust_code_block_start.is_match(line) {\n            in_code_block = true;\n            initial + \"```rust\\n\"\n        } else if line.starts_with(CODE_BLOCK_TOGGLE) {\n            in_code_block = false;\n            initial + line + \"\\n\"\n        } else {\n            initial + line + \"\\n\"\n        }\n    });\n\n    Ok(output)\n}\n\n#[test]\nfn code_block_breaking() {\n    let long_code_block = \"If we truly want a reference, we need the other option: ensure that our reference goes out of scope before we try to do the mutation. That looks like this:\n\n```text\nWhew! The Rust compiler gives quite detailed errors at times, and this is one of those times. As the error explains, while we made our binding mutable, we still cannot call `push`. This is because we already have a reference to an element of the vector, `y`. Mutating something while another reference exists is dangerous, because we may invalidate the reference. In this speciffic case, when we create the vector, we may have only allocated space for three elements. Adding a fourth would mean allocating a new chunk of memory for all thosee elements, copying the old values over, and updating the internal pointer to that memory. That all works just fine.\n```\n\nWe created an inner scope with an additional set of curly braces. `y` will go out of scope before we call `push()`, and so we’re all good.\";\n\n    let code_block_broken_down = \"If we truly want a reference, we need the other option: ensure that our reference goes out of scope before we try to do the mutation. That looks like this:\n\n```text\nWhew! The Rust compiler gives quite detailed errors at times, and this is one o\n↳ f those times. As the error explains, while we made our binding mutable, we s\n↳ till cannot call `push`. This is because we already have a reference to an el\n↳ ement of the vector, `y`. Mutating something while another reference exists i\n↳ s dangerous, because we may invalidate the reference. In this speciffic case,\n↳  when we create the vector, we may have only allocated space for three elemen\n↳ ts. Adding a fourth would mean allocating a new chunk of memory for all those\n↳ e elements, copying the old values over, and updating the internal pointer to\n↳  that memory. That all works just fine.\n```\n\nWe created an inner scope with an additional set of curly braces. `y` will go out of scope before we call `push()`, and so we’re all good.\n\";\n\n    let max_len = 80;\n\n    let broken = break_code_blocks(long_code_block, max_len, \"↳ \").unwrap();\n\n    assert_eq!(broken, code_block_broken_down);\n}\n\n#[test]\nfn code_block_starts() {\n    let code_blocks = \"Code:\n\n```sh\n$ lol\n```\n\n```{rust,ignore}\nlet x = true;\n```\n\n``` rust,no_extras\nlet x = true;\n```\n\n```rust\n# use magic::from_the_future::*;\n#\n# #[inline]\n# fn extension(file_name: &str) -> Option<&str> {\n#     find(file_name, '.').map(|i| &file_name[i+1..])\n# }\nlet x = true;\n```\n\";\n\n    let code_blocks_clean = \"Code:\n\n```sh\n$ lol\n```\n\n```rust\nlet x = true;\n```\n\n```rust\nlet x = true;\n```\n\n```rust\nlet x = true;\n```\n\";\n\n    let cleaned = normalize_code_start(code_blocks).unwrap();\n\n    assert_eq!(cleaned, code_blocks_clean);\n}\n"
  },
  {
    "path": "src/helpers/remove_emojis.rs",
    "content": "use regex::Regex;\n\npub fn remove_emojis(input: &str) -> String {\n    // cf. http://stackoverflow.com/a/29115826/1254484\n    let emojis = Regex::new(\"[\\u{203c}\\u{2049}\\u{20e3}\\u{2122}\\u{2139}\\u{2194}-\\u{2199}\\u{21a9}-\\u{21aa}\\u{231a}-\\u{231b}\\u{23e9}-\\u{23ec}\\u{23f0}\\u{23f3}\\u{24c2}\\u{25aa}-\\u{25ab}\\u{25b6}\\u{25c0}\\u{25fb}-\\u{25fe}\\u{2600}-\\u{2601}\\u{260e}\\u{2611}\\u{2614}-\\u{2615}\\u{261d}\\u{263a}\\u{2648}-\\u{2653}\\u{2660}\\u{2663}\\u{2665}-\\u{2666}\\u{2668}\\u{267b}\\u{267f}\\u{2693}\\u{26a0}-\\u{26a1}\\u{26aa}-\\u{26ab}\\u{26bd}-\\u{26be}\\u{26c4}-\\u{26c5}\\u{26ce}\\u{26d4}\\u{26ea}\\u{26f2}-\\u{26f3}\\u{26f5}\\u{26fa}\\u{26fd}\\u{2702}\\u{2705}\\u{2708}-\\u{270c}\\u{270f}\\u{2712}\\u{2714}\\u{2716}\\u{2728}\\u{2733}-\\u{2734}\\u{2744}\\u{2747}\\u{274c}\\u{274e}\\u{2753}-\\u{2755}\\u{2757}\\u{2764}\\u{2795}-\\u{2797}\\u{27a1}\\u{27b0}\\u{2934}-\\u{2935}\\u{2b05}-\\u{2b07}\\u{2b1b}-\\u{2b1c}\\u{2b50}\\u{2b55}\\u{3030}\\u{303d}\\u{3297}\\u{3299}\\u{1f004}\\u{1f0cf}\\u{1f170}-\\u{1f171}\\u{1f17e}-\\u{1f17f}\\u{1f18e}\\u{1f191}-\\u{1f19a}\\u{1f1e7}-\\u{1f1ec}\\u{1f1ee}-\\u{1f1f0}\\u{1f1f3}\\u{1f1f5}\\u{1f1f7}-\\u{1f1fa}\\u{1f201}-\\u{1f202}\\u{1f21a}\\u{1f22f}\\u{1f232}-\\u{1f23a}\\u{1f250}-\\u{1f251}\\u{1f300}-\\u{1f320}\\u{1f330}-\\u{1f335}\\u{1f337}-\\u{1f37c}\\u{1f380}-\\u{1f393}\\u{1f3a0}-\\u{1f3c4}\\u{1f3c6}-\\u{1f3ca}\\u{1f3e0}-\\u{1f3f0}\\u{1f400}-\\u{1f43e}\\u{1f440}\\u{1f442}-\\u{1f4f7}\\u{1f4f9}-\\u{1f4fc}\\u{1f500}-\\u{1f507}\\u{1f509}-\\u{1f53d}\\u{1f550}-\\u{1f567}\\u{1f5fb}-\\u{1f640}\\u{1f645}-\\u{1f64f}\\u{1f680}-\\u{1f68a}]\").unwrap();\n\n    emojis.replace_all(input, \"\")\n}\n\n#[test]\nfn emoji_removal() {\n    assert_eq!(remove_emojis(\"emojis? 😅\"), \"emojis? \");\n}\n"
  },
  {
    "path": "src/helpers/remove_file_title.rs",
    "content": "use std::error::Error;\nuse regex::Regex;\n\npub fn remove_file_title(input: &str) -> Result<String, Box<Error>> {\n    Ok(Regex::new(r\"^%\\s(.+)\\n\").unwrap().replace(input, \"\"))\n}\n"
  },
  {
    "path": "src/helpers/shell_pipe.rs",
    "content": "use std::error::Error;\nuse std::fmt;\n\nuse std::io::prelude::*;\nuse std::process::{self, Command, Stdio};\n\n#[derive(Debug, Hash, PartialEq, Eq)]\nenum CommandError {\n    StdIn,\n    StdOut,\n}\n\nimpl fmt::Display for CommandError {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            CommandError::StdIn => write!(f, \"Error getting stdin\"),\n            CommandError::StdOut => write!(f, \"Error getting stdout\"),\n        }\n    }\n}\n\nimpl Error for CommandError {\n    fn description(&self) -> &str {\n        match *self {\n            CommandError::StdIn => \"Error getting stdin\",\n            CommandError::StdOut => \"Error getting stdout\",\n        }\n    }\n}\n\npub fn run(command: &str, args: &str, input: &str) -> Result<String, Box<Error>> {\n    let args: Vec<&str> = if args.is_empty() {\n        vec![]\n    } else {\n        // Command arguments are space separated but may contain sub strings in quotation marks\n        let mut in_substr = false;\n        args.split(|c: char| {\n            if c == '\\'' { in_substr = !in_substr; }\n            !in_substr && (c == ' ')\n        }).collect()\n    };\n\n    let process = try!(\n        Command::new(command)\n                .args(&args)\n                .stdin(Stdio::piped())\n                .stdout(Stdio::piped())\n                .spawn()\n    );\n\n    {\n        let mut stdin: process::ChildStdin = try!(process.stdin.ok_or(CommandError::StdIn));\n        try!(stdin.write_all(input.as_bytes()));\n    }\n\n    let mut output = String::new();\n\n    let mut stdout: process::ChildStdout = try!(process.stdout.ok_or(CommandError::StdOut));\n    try!(stdout.read_to_string(&mut output));\n\n    Ok(output)\n}\n\n#[test]\nfn dry_run() {\n    let output = run(\"cat\", \"\", \"lol\").unwrap();\n\n    assert_eq!(output, \"lol\");\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "//! Compile EBooks for 'The Rust Programming Language'\n//!\n//! ['The Rust Programming Language'][trpl] is originally published as Markdown\n//! and rendered by _rustbook_. This set of scripts does some transformations\n//! and uses _Pandoc_ to render it as HTML, EPUB and PDF (usign LaTeX).\n//!\n//! [trpl]: http://doc.rust-lang.org/book/\n\n#![cfg_attr(feature = \"dev\", feature(plugin))]\n#![cfg_attr(feature = \"dev\", plugin(clippy))]\n\nextern crate regex;\nextern crate docopt;\nextern crate rustc_serialize;\n\nuse std::path::Path;\nuse docopt::Docopt;\n\npub mod helpers;\npub mod convert_book;\n\nstatic USAGE: &'static str = r#\"\nCompile Rustbook to EBook formats.\n\nUsage:\n  compile-trpl [--prefix=<prefix>] [--source=<directory>] [--meta=<meta_file>]\n\nOptions:\n  --prefix=<prefix>     Prefix/short name of your book, e.g. \"trpl\" or \"nomicon\".\n  --source=<directory>  Directory containing the git book files, especially SUMMARY.md and README.md.\n  --meta=<meta_file>    Meta data of your book, needs to contain `date: {release_date}`.\n\"#;\n\n#[derive(Debug, RustcDecodable)]\nstruct Args {\n    flag_prefix: Option<String>,\n    flag_source: Option<String>,\n    flag_meta: Option<String>,\n}\n\nfn main() {\n    let args: Args = Docopt::new(USAGE)\n        .and_then(|d| d.decode())\n        .unwrap_or_else(|e| e.exit());\n\n    let prefix = args.flag_prefix.unwrap_or(\"trpl\".to_owned());\n    let source = args.flag_source.unwrap_or(\"trpl\".to_owned());\n    let meta = args.flag_meta.unwrap_or(\"trpl_meta.yml\".to_owned());\n\n    convert_book::render_book(&prefix, &Path::new(&source), &meta).unwrap();\n\n    let index = convert_book::index::render_index(\"dist/\").unwrap();\n    helpers::file::write_string_to_file(&index, \"dist/index.html\").unwrap();\n    println!(\"[✓] {}\", \"Index\");\n}\n"
  },
  {
    "path": "trpl/README.md",
    "content": "% The Rust Programming Language\n\nWelcome! This book will teach you about the [Rust Programming Language][rust].\nRust is a systems programming language focused on three goals: safety, speed,\nand concurrency. It maintains these goals without having a garbage collector,\nmaking it a useful language for a number of use cases other languages aren’t\ngood at: embedding in other languages, programs with specific space and time\nrequirements, and writing low-level code, like device drivers and operating\nsystems. It improves on current languages targeting this space by having a\nnumber of compile-time safety checks that produce no runtime overhead, while\neliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’\neven though some of these abstractions feel like those of a high-level language.\nEven then, Rust still allows precise control like a low-level language would.\n\n[rust]: https://www.rust-lang.org\n\n“The Rust Programming Language” is split into chapters. This introduction\nis the first. After this:\n\n* [Getting started][gs] - Set up your computer for Rust development.\n* [Tutorial: Guessing Game][gg] - Learn some Rust with a small project.\n* [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks.\n* [Effective Rust][er] - Higher-level concepts for writing excellent Rust code.\n* [Nightly Rust][nr] - Cutting-edge features that aren’t in stable builds yet.\n* [Glossary][gl] - A reference of terms used in the book.\n* [Bibliography][bi] - Background on Rust's influences, papers about Rust.\n\n[gs]: getting-started.html\n[gg]: guessing-game.html\n[er]: effective-rust.html\n[ss]: syntax-and-semantics.html\n[nr]: nightly-rust.html\n[gl]: glossary.html\n[bi]: bibliography.html\n\n### Contributing\n\nThe source files from which this book is generated can be found on\n[GitHub][book].\n\n[book]: https://github.com/rust-lang/rust/tree/master/src/doc/book\n"
  },
  {
    "path": "trpl/SUMMARY.md",
    "content": "# Summary\n\n* [Getting Started](getting-started.md)\n* [Tutorial: Guessing Game](guessing-game.md)\n* [Syntax and Semantics](syntax-and-semantics.md)\n    * [Variable Bindings](variable-bindings.md)\n    * [Functions](functions.md)\n    * [Primitive Types](primitive-types.md)\n    * [Comments](comments.md)\n    * [if](if.md)\n    * [Loops](loops.md)\n    * [Vectors](vectors.md)\n    * [Ownership](ownership.md)\n    * [References and Borrowing](references-and-borrowing.md)\n    * [Lifetimes](lifetimes.md)\n    * [Mutability](mutability.md)\n    * [Structs](structs.md)\n    * [Enums](enums.md)\n    * [Match](match.md)\n    * [Patterns](patterns.md)\n    * [Method Syntax](method-syntax.md)\n    * [Strings](strings.md)\n    * [Generics](generics.md)\n    * [Traits](traits.md)\n    * [Drop](drop.md)\n    * [if let](if-let.md)\n    * [Trait Objects](trait-objects.md)\n    * [Closures](closures.md)\n    * [Universal Function Call Syntax](ufcs.md)\n    * [Crates and Modules](crates-and-modules.md)\n    * [`const` and `static`](const-and-static.md)\n    * [Attributes](attributes.md)\n    * [`type` aliases](type-aliases.md)\n    * [Casting between types](casting-between-types.md)\n    * [Associated Types](associated-types.md)\n    * [Unsized Types](unsized-types.md)\n    * [Operators and Overloading](operators-and-overloading.md)\n    * [Deref coercions](deref-coercions.md)\n    * [Macros](macros.md)\n    * [Raw Pointers](raw-pointers.md)\n    * [`unsafe`](unsafe.md)\n* [Effective Rust](effective-rust.md)\n    * [The Stack and the Heap](the-stack-and-the-heap.md)\n    * [Testing](testing.md)\n    * [Conditional Compilation](conditional-compilation.md)\n    * [Documentation](documentation.md)\n    * [Iterators](iterators.md)\n    * [Concurrency](concurrency.md)\n    * [Error Handling](error-handling.md)\n    * [Choosing your Guarantees](choosing-your-guarantees.md)\n    * [FFI](ffi.md)\n    * [Borrow and AsRef](borrow-and-asref.md)\n    * [Release Channels](release-channels.md)\n    * [Using Rust without the standard library](using-rust-without-the-standard-library.md)\n* [Nightly Rust](nightly-rust.md)\n    * [Compiler Plugins](compiler-plugins.md)\n    * [Inline Assembly](inline-assembly.md)\n    * [No stdlib](no-stdlib.md)\n    * [Intrinsics](intrinsics.md)\n    * [Lang items](lang-items.md)\n    * [Advanced linking](advanced-linking.md)\n    * [Benchmark Tests](benchmark-tests.md)\n    * [Box Syntax and Patterns](box-syntax-and-patterns.md)\n    * [Slice Patterns](slice-patterns.md)\n    * [Associated Constants](associated-constants.md)\n    * [Custom Allocators](custom-allocators.md)\n* [Glossary](glossary.md)\n* [Syntax Index](syntax-index.md)\n* [Bibliography](bibliography.md)\n"
  },
  {
    "path": "trpl/advanced-linking.md",
    "content": "% Advanced Linking\n\nThe common cases of linking with Rust have been covered earlier in this book,\nbut supporting the range of linking possibilities made available by other\nlanguages is important for Rust to achieve seamless interaction with native\nlibraries.\n\n# Link args\n\nThere is one other way to tell `rustc` how to customize linking, and that is via\nthe `link_args` attribute. This attribute is applied to `extern` blocks and\nspecifies raw flags which need to get passed to the linker when producing an\nartifact. An example usage would be:\n\n```rust,no_run\n#![feature(link_args)]\n\n#[link_args = \"-foo -bar -baz\"]\nextern {}\n# fn main() {}\n```\n\nNote that this feature is currently hidden behind the `feature(link_args)` gate\nbecause this is not a sanctioned way of performing linking. Right now `rustc`\nshells out to the system linker (`gcc` on most systems, `link.exe` on MSVC),\nso it makes sense to provide extra command line\narguments, but this will not always be the case. In the future `rustc` may use\nLLVM directly to link native libraries, in which case `link_args` will have no\nmeaning. You can achieve the same effect as the `link_args` attribute with the\n`-C link-args` argument to `rustc`.\n\nIt is highly recommended to *not* use this attribute, and rather use the more\nformal `#[link(...)]` attribute on `extern` blocks instead.\n\n# Static linking\n\nStatic linking refers to the process of creating output that contains all\nrequired libraries and so doesn't need libraries installed on every system where\nyou want to use your compiled project. Pure-Rust dependencies are statically\nlinked by default so you can use created binaries and libraries without\ninstalling Rust everywhere. By contrast, native libraries\n(e.g. `libc` and `libm`) are usually dynamically linked, but it is possible to\nchange this and statically link them as well.\n\nLinking is a very platform-dependent topic, and static linking may not even be\npossible on some platforms! This section assumes some basic familiarity with\nlinking on your platform of choice.\n\n## Linux\n\nBy default, all Rust programs on Linux will link to the system `libc` along with\na number of other libraries. Let's look at an example on a 64-bit Linux machine\nwith GCC and `glibc` (by far the most common `libc` on Linux):\n\n```text\n$ cat example.rs\nfn main() {}\n$ rustc example.rs\n$ ldd example\n        linux-vdso.so.1 =>  (0x00007ffd565fd000)\n        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fa81889c000)\n        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fa81867e000)\n        librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fa818475000)\n        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fa81825f000)\n        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fa817e9a000)\n        /lib64/ld-linux-x86-64.so.2 (0x00007fa818cf9000)\n        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fa817b93000)\n```\n\nDynamic linking on Linux can be undesirable if you wish to use new library\nfeatures on old systems or target systems which do not have the required\ndependencies for your program to run.\n\nStatic linking is supported via an alternative `libc`, [`musl`](http://www.musl-libc.org). You can compile\nyour own version of Rust with `musl` enabled and install it into a custom\ndirectory with the instructions below:\n\n```text\n$ mkdir musldist\n$ PREFIX=$(pwd)/musldist\n$\n$ # Build musl\n$ curl -O http://www.musl-libc.org/releases/musl-1.1.10.tar.gz\n$ tar xf musl-1.1.10.tar.gz\n$ cd musl-1.1.10/\nmusl-1.1.10 $ ./configure --disable-shared --prefix=$PREFIX\nmusl-1.1.10 $ make\nmusl-1.1.10 $ make install\nmusl-1.1.10 $ cd ..\n$ du -h musldist/lib/libc.a\n2.2M    musldist/lib/libc.a\n$\n$ # Build libunwind.a\n$ curl -O http://llvm.org/releases/3.7.0/llvm-3.7.0.src.tar.xz\n$ tar xf llvm-3.7.0.src.tar.xz\n$ cd llvm-3.7.0.src/projects/\nllvm-3.7.0.src/projects $ curl http://llvm.org/releases/3.7.0/libunwind-3.7.0.src.tar.xz | tar xJf -\nllvm-3.7.0.src/projects $ mv libunwind-3.7.0.src libunwind\nllvm-3.7.0.src/projects $ mkdir libunwind/build\nllvm-3.7.0.src/projects $ cd libunwind/build\nllvm-3.7.0.src/projects/libunwind/build $ cmake -DLLVM_PATH=../../.. -DLIBUNWIND_ENABLE_SHARED=0 ..\nllvm-3.7.0.src/projects/libunwind/build $ make\nllvm-3.7.0.src/projects/libunwind/build $ cp lib/libunwind.a $PREFIX/lib/\nllvm-3.7.0.src/projects/libunwind/build $ cd ../../../../\n$ du -h musldist/lib/libunwind.a\n164K    musldist/lib/libunwind.a\n$\n$ # Build musl-enabled rust\n$ git clone https://github.com/rust-lang/rust.git muslrust\n$ cd muslrust\nmuslrust $ ./configure --target=x86_64-unknown-linux-musl --musl-root=$PREFIX --prefix=$PREFIX\nmuslrust $ make\nmuslrust $ make install\nmuslrust $ cd ..\n$ du -h musldist/bin/rustc\n12K     musldist/bin/rustc\n```\n\nYou now have a build of a `musl`-enabled Rust! Because we've installed it to a\ncustom prefix we need to make sure our system can find the binaries and appropriate\nlibraries when we try and run it:\n\n```text\n$ export PATH=$PREFIX/bin:$PATH\n$ export LD_LIBRARY_PATH=$PREFIX/lib:$LD_LIBRARY_PATH\n```\n\nLet's try it out!\n\n```text\n$ echo 'fn main() { println!(\"hi!\"); panic!(\"failed\"); }' > example.rs\n$ rustc --target=x86_64-unknown-linux-musl example.rs\n$ ldd example\n        not a dynamic executable\n$ ./example\nhi!\nthread 'main' panicked at 'failed', example.rs:1\n```\n\nSuccess! This binary can be copied to almost any Linux machine with the same\nmachine architecture and run without issues.\n\n`cargo build` also permits the `--target` option so you should be able to build\nyour crates as normal. However, you may need to recompile your native libraries\nagainst `musl` before they can be linked against.\n"
  },
  {
    "path": "trpl/associated-constants.md",
    "content": "% Associated Constants\n\nWith the `associated_consts` feature, you can define constants like this:\n\n```rust\n#![feature(associated_consts)]\n\ntrait Foo {\n    const ID: i32;\n}\n\nimpl Foo for i32 {\n    const ID: i32 = 1;\n}\n\nfn main() {\n    assert_eq!(1, i32::ID);\n}\n```\n\nAny implementor of `Foo` will have to define `ID`. Without the definition:\n\n```rust,ignore\n#![feature(associated_consts)]\n\ntrait Foo {\n    const ID: i32;\n}\n\nimpl Foo for i32 {\n}\n```\n\ngives\n\n```text\nerror: not all trait items implemented, missing: `ID` [E0046]\n     impl Foo for i32 {\n     }\n```\n\nA default value can be implemented as well:\n\n```rust\n#![feature(associated_consts)]\n\ntrait Foo {\n    const ID: i32 = 1;\n}\n\nimpl Foo for i32 {\n}\n\nimpl Foo for i64 {\n    const ID: i32 = 5;\n}\n\nfn main() {\n    assert_eq!(1, i32::ID);\n    assert_eq!(5, i64::ID);\n}\n```\n\nAs you can see, when implementing `Foo`, you can leave it unimplemented, as\nwith `i32`. It will then use the default value. But, as in `i64`, we can also\nadd our own definition.\n\nAssociated constants don’t have to be associated with a trait. An `impl` block\nfor a `struct` or an `enum` works fine too:\n\n```rust\n#![feature(associated_consts)]\n\nstruct Foo;\n\nimpl Foo {\n    const FOO: u32 = 3;\n}\n```\n"
  },
  {
    "path": "trpl/associated-types.md",
    "content": "% Associated Types\n\nAssociated types are a powerful part of Rust’s type system. They’re related to\nthe idea of a ‘type family’, in other words, grouping multiple types together. That\ndescription is a bit abstract, so let’s dive right into an example. If you want\nto write a `Graph` trait, you have two types to be generic over: the node type\nand the edge type. So you might write a trait, `Graph<N, E>`, that looks like\nthis:\n\n```rust\ntrait Graph<N, E> {\n    fn has_edge(&self, &N, &N) -> bool;\n    fn edges(&self, &N) -> Vec<E>;\n    // etc\n}\n```\n\nWhile this sort of works, it ends up being awkward. For example, any function\nthat wants to take a `Graph` as a parameter now _also_ needs to be generic over\nthe `N`ode and `E`dge types too:\n\n```rust,ignore\nfn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 { ... }\n```\n\nOur distance calculation works regardless of our `Edge` type, so the `E` stuff in\nthis signature is a distraction.\n\nWhat we really want to say is that a certain `E`dge and `N`ode type come together\nto form each kind of `Graph`. We can do that with associated types:\n\n```rust\ntrait Graph {\n    type N;\n    type E;\n\n    fn has_edge(&self, &Self::N, &Self::N) -> bool;\n    fn edges(&self, &Self::N) -> Vec<Self::E>;\n    // etc\n}\n```\n\nNow, our clients can be abstract over a given `Graph`:\n\n```rust,ignore\nfn distance<G: Graph>(graph: &G, start: &G::N, end: &G::N) -> u32 { ... }\n```\n\nNo need to deal with the `E`dge type here!\n\nLet’s go over all this in more detail.\n\n## Defining associated types\n\nLet’s build that `Graph` trait. Here’s the definition:\n\n```rust\ntrait Graph {\n    type N;\n    type E;\n\n    fn has_edge(&self, &Self::N, &Self::N) -> bool;\n    fn edges(&self, &Self::N) -> Vec<Self::E>;\n}\n```\n\nSimple enough. Associated types use the `type` keyword, and go inside the body\nof the trait, with the functions.\n\nThese `type` declarations can have all the same thing as functions do. For example,\nif we wanted our `N` type to implement `Display`, so we can print the nodes out,\nwe could do this:\n\n```rust\nuse std::fmt;\n\ntrait Graph {\n    type N: fmt::Display;\n    type E;\n\n    fn has_edge(&self, &Self::N, &Self::N) -> bool;\n    fn edges(&self, &Self::N) -> Vec<Self::E>;\n}\n```\n\n## Implementing associated types\n\nJust like any trait, traits that use associated types use the `impl` keyword to\nprovide implementations. Here’s a simple implementation of Graph:\n\n```rust\n# trait Graph {\n#     type N;\n#     type E;\n#     fn has_edge(&self, &Self::N, &Self::N) -> bool;\n#     fn edges(&self, &Self::N) -> Vec<Self::E>;\n# }\nstruct Node;\n\nstruct Edge;\n\nstruct MyGraph;\n\nimpl Graph for MyGraph {\n    type N = Node;\n    type E = Edge;\n\n    fn has_edge(&self, n1: &Node, n2: &Node) -> bool {\n        true\n    }\n\n    fn edges(&self, n: &Node) -> Vec<Edge> {\n        Vec::new()\n    }\n}\n```\n\nThis silly implementation always returns `true` and an empty `Vec<Edge>`, but it\ngives you an idea of how to implement this kind of thing. We first need three\n`struct`s, one for the graph, one for the node, and one for the edge. If it made\nmore sense to use a different type, that would work as well, we’re going to\nuse `struct`s for all three here.\n\nNext is the `impl` line, which is an implementation like any other trait.\n\nFrom here, we use `=` to define our associated types. The name the trait uses\ngoes on the left of the `=`, and the concrete type we’re `impl`ementing this\nfor goes on the right. Finally, we use the concrete types in our function\ndeclarations.\n\n## Trait objects with associated types\n\nThere’s one more bit of syntax we should talk about: trait objects. If you\ntry to create a trait object from a trait with an associated type, like this:\n\n```rust,ignore\n# trait Graph {\n#     type N;\n#     type E;\n#     fn has_edge(&self, &Self::N, &Self::N) -> bool;\n#     fn edges(&self, &Self::N) -> Vec<Self::E>;\n# }\n# struct Node;\n# struct Edge;\n# struct MyGraph;\n# impl Graph for MyGraph {\n#     type N = Node;\n#     type E = Edge;\n#     fn has_edge(&self, n1: &Node, n2: &Node) -> bool {\n#         true\n#     }\n#     fn edges(&self, n: &Node) -> Vec<Edge> {\n#         Vec::new()\n#     }\n# }\nlet graph = MyGraph;\nlet obj = Box::new(graph) as Box<Graph>;\n```\n\nYou’ll get two errors:\n\n```text\nerror: the value of the associated type `E` (from the trait `main::Graph`) must\nbe specified [E0191]\nlet obj = Box::new(graph) as Box<Graph>;\n          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n24:44 error: the value of the associated type `N` (from the trait\n`main::Graph`) must be specified [E0191]\nlet obj = Box::new(graph) as Box<Graph>;\n          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\n\nWe can’t create a trait object like this, because we don’t know the associated\ntypes. Instead, we can write this:\n\n```rust\n# trait Graph {\n#     type N;\n#     type E;\n#     fn has_edge(&self, &Self::N, &Self::N) -> bool;\n#     fn edges(&self, &Self::N) -> Vec<Self::E>;\n# }\n# struct Node;\n# struct Edge;\n# struct MyGraph;\n# impl Graph for MyGraph {\n#     type N = Node;\n#     type E = Edge;\n#     fn has_edge(&self, n1: &Node, n2: &Node) -> bool {\n#         true\n#     }\n#     fn edges(&self, n: &Node) -> Vec<Edge> {\n#         Vec::new()\n#     }\n# }\nlet graph = MyGraph;\nlet obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;\n```\n\nThe `N=Node` syntax allows us to provide a concrete type, `Node`, for the `N`\ntype parameter. Same with `E=Edge`. If we didn’t provide this constraint, we\ncouldn’t be sure which `impl` to match this trait object to.\n"
  },
  {
    "path": "trpl/attributes.md",
    "content": "% Attributes\n\nDeclarations can be annotated with ‘attributes’ in Rust. They look like this:\n\n```rust\n#[test]\n# fn foo() {}\n```\n\nor like this:\n\n```rust\n# mod foo {\n#![test]\n# }\n```\n\nThe difference between the two is the `!`, which changes what the attribute\napplies to:\n\n```rust,ignore\n#[foo]\nstruct Foo;\n\nmod bar {\n    #![bar]\n}\n```\n\nThe `#[foo]` attribute applies to the next item, which is the `struct`\ndeclaration. The `#![bar]` attribute applies to the item enclosing it, which is\nthe `mod` declaration. Otherwise, they’re the same. Both change the meaning of\nthe item they’re attached to somehow.\n\nFor example, consider a function like this:\n\n```rust\n#[test]\nfn check() {\n    assert_eq!(2, 1 + 1);\n}\n```\n\nIt is marked with `#[test]`. This means it’s special: when you run\n[tests][tests], this function will execute. When you compile as usual, it won’t\neven be included. This function is now a test function.\n\n[tests]: testing.html\n\nAttributes may also have additional data:\n\n```rust\n#[inline(always)]\nfn super_fast_fn() {\n# }\n```\n\nOr even keys and values:\n\n```rust\n#[cfg(target_os = \"macos\")]\nmod macos_only {\n# }\n```\n\nRust attributes are used for a number of different things. There is a full list\nof attributes [in the reference][reference]. Currently, you are not allowed to\ncreate your own attributes, the Rust compiler defines them.\n\n[reference]: ../reference.html#attributes\n"
  },
  {
    "path": "trpl/benchmark-tests.md",
    "content": "% Benchmark tests\n\nRust supports benchmark tests, which can test the performance of your\ncode. Let's make our `src/lib.rs` look like this (comments elided):\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\n\npub fn add_two(a: i32) -> i32 {\n    a + 2\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use test::Bencher;\n\n    #[test]\n    fn it_works() {\n        assert_eq!(4, add_two(2));\n    }\n\n    #[bench]\n    fn bench_add_two(b: &mut Bencher) {\n        b.iter(|| add_two(2));\n    }\n}\n```\n\nNote the `test` feature gate, which enables this unstable feature.\n\nWe've imported the `test` crate, which contains our benchmarking support.\nWe have a new function as well, with the `bench` attribute. Unlike regular\ntests, which take no arguments, benchmark tests take a `&mut Bencher`. This\n`Bencher` provides an `iter` method, which takes a closure. This closure\ncontains the code we'd like to benchmark.\n\nWe can run benchmark tests with `cargo bench`:\n\n```bash\n$ cargo bench\n   Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n     Running target/release/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest tests::it_works ... ignored\ntest tests::bench_add_two ... bench:         1 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 1 measured\n```\n\nOur non-benchmark test was ignored. You may have noticed that `cargo bench`\ntakes a bit longer than `cargo test`. This is because Rust runs our benchmark\na number of times, and then takes the average. Because we're doing so little\nwork in this example, we have a `1 ns/iter (+/- 0)`, but this would show\nthe variance if there was one.\n\nAdvice on writing benchmarks:\n\n\n* Move setup code outside the `iter` loop; only put the part you want to measure inside\n* Make the code do \"the same thing\" on each iteration; do not accumulate or change state\n* Make the outer function idempotent too; the benchmark runner is likely to run\n  it many times\n*  Make the inner `iter` loop short and fast so benchmark runs are fast and the\n   calibrator can adjust the run-length at fine resolution\n* Make the code in the `iter` loop do something simple, to assist in pinpointing\n  performance improvements (or regressions)\n\n## Gotcha: optimizations\n\nThere's another tricky part to writing benchmarks: benchmarks compiled with\noptimizations activated can be dramatically changed by the optimizer so that\nthe benchmark is no longer benchmarking what one expects. For example, the\ncompiler might recognize that some calculation has no external effects and\nremove it entirely.\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[bench]\nfn bench_xor_1000_ints(b: &mut Bencher) {\n    b.iter(|| {\n        (0..1000).fold(0, |old, new| old ^ new);\n    });\n}\n```\n\ngives the following results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench:         0 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nThe benchmarking runner offers two ways to avoid this. Either, the closure that\nthe `iter` method receives can return an arbitrary value which forces the\noptimizer to consider the result used and ensures it cannot remove the\ncomputation entirely. This could be done for the example above by adjusting the\n`b.iter` call to\n\n```rust\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n    // note lack of `;` (could also use an explicit `return`).\n    (0..1000).fold(0, |old, new| old ^ new)\n});\n```\n\nOr, the other option is to call the generic `test::black_box` function, which\nis an opaque \"black box\" to the optimizer and so forces it to consider any\nargument as used.\n\n```rust\n#![feature(test)]\n\nextern crate test;\n\n# fn main() {\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n    let n = test::black_box(1000);\n\n    (0..n).fold(0, |a, b| a ^ b)\n})\n# }\n```\n\nNeither of these read or modify the value, and are very cheap for small values.\nLarger values can be passed indirectly to reduce overhead (e.g.\n`black_box(&huge_struct)`).\n\nPerforming either of the above changes gives the following benchmarking results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench:       131 ns/iter (+/- 3)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nHowever, the optimizer can still modify a testcase in an undesirable manner\neven when using either of the above.\n"
  },
  {
    "path": "trpl/bibliography.md",
    "content": "% Bibliography\n\nThis is a reading list of material relevant to Rust. It includes prior\nresearch that has - at one time or another - influenced the design of\nRust, as well as publications about Rust.\n\n### Type system\n\n* [Region based memory management in Cyclone](http://209.68.42.137/ucsd-pages/Courses/cse227.w03/handouts/cyclone-regions.pdf)\n* [Safe manual memory management in Cyclone](http://www.cs.umd.edu/projects/PL/cyclone/scp.pdf)\n* [Typeclasses: making ad-hoc polymorphism less ad hoc](http://www.ps.uni-sb.de/courses/typen-ws99/class.ps.gz)\n* [Macros that work together](https://www.cs.utah.edu/plt/publications/jfp12-draft-fcdf.pdf)\n* [Traits: composable units of behavior](http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf)\n* [Alias burying](http://www.cs.uwm.edu/faculty/boyland/papers/unique-preprint.ps) - We tried something similar and abandoned it.\n* [External uniqueness is unique enough](http://www.cs.uu.nl/research/techreps/UU-CS-2002-048.html)\n* [Uniqueness and Reference Immutability for Safe Parallelism](https://research.microsoft.com/pubs/170528/msr-tr-2012-79.pdf)\n* [Region Based Memory Management](http://www.cs.ucla.edu/~palsberg/tba/papers/tofte-talpin-iandc97.pdf)\n\n### Concurrency\n\n* [Singularity: rethinking the software stack](https://research.microsoft.com/pubs/69431/osr2007_rethinkingsoftwarestack.pdf)\n* [Language support for fast and reliable message passing in singularity OS](https://research.microsoft.com/pubs/67482/singsharp.pdf)\n* [Scheduling multithreaded computations by work stealing](http://supertech.csail.mit.edu/papers/steal.pdf)\n* [Thread scheduling for multiprogramming multiprocessors](http://www.eecis.udel.edu/%7Ecavazos/cisc879-spring2008/papers/arora98thread.pdf)\n* [The data locality of work stealing](http://www.aladdin.cs.cmu.edu/papers/pdfs/y2000/locality_spaa00.pdf)\n* [Dynamic circular work stealing deque](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.170.1097&rep=rep1&type=pdf) - The Chase/Lev deque\n* [Work-first and help-first scheduling policies for async-finish task parallelism](http://www.cs.rice.edu/%7Eyguo/pubs/PID824943.pdf) - More general than fully-strict work stealing\n* [A Java fork/join calamity](http://www.coopsoft.com/ar/CalamityArticle.html) - critique of Java's fork/join library, particularly its application of work stealing to non-strict computation\n* [Scheduling techniques for concurrent systems](http://www.stanford.edu/~ouster/cgi-bin/papers/coscheduling.pdf)\n* [Contention aware scheduling](http://www.blagodurov.net/files/a8-blagodurov.pdf)\n* [Balanced work stealing for time-sharing multicores](http://www.cse.ohio-state.edu/hpcs/WWW/HTML/publications/papers/TR-12-1.pdf)\n* [Three layer cake for shared-memory programming](http://dl.acm.org/citation.cfm?id=1953616&dl=ACM&coll=DL&CFID=524387192&CFTOKEN=44362705)\n* [Non-blocking steal-half work queues](http://www.cs.bgu.ac.il/%7Ehendlerd/papers/p280-hendler.pdf)\n* [Reagents: expressing and composing fine-grained concurrency](http://www.mpi-sws.org/~turon/reagents.pdf)\n* [Algorithms for scalable synchronization of shared-memory multiprocessors](https://www.cs.rochester.edu/u/scott/papers/1991_TOCS_synch.pdf)\n* [Epoch-based reclamation](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf).\n\n### Others\n\n* [Crash-only software](https://www.usenix.org/legacy/events/hotos03/tech/full_papers/candea/candea.pdf)\n* [Composing High-Performance Memory Allocators](http://people.cs.umass.edu/~emery/pubs/berger-pldi2001.pdf)\n* [Reconsidering Custom Memory Allocation](http://people.cs.umass.edu/~emery/pubs/berger-oopsla2002.pdf)\n\n### Papers *about* Rust\n\n* [GPU Programming in Rust: Implementing High Level Abstractions in a\nSystems Level\nLanguage](http://www.cs.indiana.edu/~eholk/papers/hips2013.pdf). Early GPU work by Eric Holk.\n* [Parallel closures: a new twist on an old\n  idea](https://www.usenix.org/conference/hotpar12/parallel-closures-new-twist-old-idea)\n  - not exactly about Rust, but by nmatsakis\n* [Patina: A Formalization of the Rust Programming\n  Language](ftp://ftp.cs.washington.edu/tr/2015/03/UW-CSE-15-03-02.pdf). Early\n  formalization of a subset of the type system, by Eric Reed.\n* [Experience Report: Developing the Servo Web Browser Engine using\n  Rust](http://arxiv.org/abs/1505.07383). By Lars Bergstrom.\n* [Implementing a Generic Radix Trie in\n  Rust](https://michaelsproul.github.io/rust_radix_paper/rust-radix-sproul.pdf). Undergrad\n  paper by Michael Sproul.\n* [Reenix: Implementing a Unix-Like Operating System in\n  Rust](http://scialex.github.io/reenix.pdf). Undergrad paper by Alex\n  Light.\n* [Evaluation of performance and productivity metrics of potential\n  programming languages in the HPC environment]\n  (http://octarineparrot.com/assets/mrfloya-thesis-ba.pdf).\n  Bachelor's thesis by Florian Wilkens. Compares C, Go and Rust.\n* [Nom, a byte oriented, streaming, zero copy, parser combinators library\n  in Rust](http://spw15.langsec.org/papers/couprie-nom.pdf). By\n  Geoffroy Couprie, research for VLC.\n* [Graph-Based Higher-Order Intermediate\n  Representation](http://compilers.cs.uni-saarland.de/papers/lkh15_cgo.pdf). An\n  experimental IR implemented in Impala, a Rust-like language.\n* [Code Refinement of Stencil\n  Codes](http://compilers.cs.uni-saarland.de/papers/ppl14_web.pdf). Another\n  paper using Impala.\n* [Parallelization in Rust with fork-join and\n  friends](http://publications.lib.chalmers.se/records/fulltext/219016/219016.pdf). Linus\n  Farnstrand's master's thesis.\n* [Session Types for\n  Rust](http://munksgaard.me/papers/laumann-munksgaard-larsen.pdf). Philip\n  Munksgaard's master's thesis. Research for Servo.\n* [Ownership is Theft: Experiences Building an Embedded OS in Rust - Amit Levy, et. al.](http://amitlevy.com/papers/tock-plos2015.pdf)\n* [You can't spell trust without Rust](https://raw.githubusercontent.com/Gankro/thesis/master/thesis.pdf). Alexis Beingessner's master's thesis.\n"
  },
  {
    "path": "trpl/borrow-and-asref.md",
    "content": "% Borrow and AsRef\n\nThe [`Borrow`][borrow] and [`AsRef`][asref] traits are very similar, but\ndifferent. Here’s a quick refresher on what these two traits mean.\n\n[borrow]: ../std/borrow/trait.Borrow.html\n[asref]: ../std/convert/trait.AsRef.html\n\n# Borrow\n\nThe `Borrow` trait is used when you’re writing a datastructure, and you want to\nuse either an owned or borrowed type as synonymous for some purpose.\n\nFor example, [`HashMap`][hashmap] has a [`get` method][get] which uses `Borrow`:\n\n```rust,ignore\nfn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>\n    where K: Borrow<Q>,\n          Q: Hash + Eq\n```\n\n[hashmap]: ../std/collections/struct.HashMap.html\n[get]: ../std/collections/struct.HashMap.html#method.get\n\nThis signature is pretty complicated. The `K` parameter is what we’re interested\nin here. It refers to a parameter of the `HashMap` itself:\n\n```rust,ignore\nstruct HashMap<K, V, S = RandomState> {\n```\n\nThe `K` parameter is the type of _key_ the `HashMap` uses. So, looking at\nthe signature of `get()` again, we can use `get()` when the key implements\n`Borrow<Q>`. That way, we can make a `HashMap` which uses `String` keys,\nbut use `&str`s when we’re searching:\n\n```rust\nuse std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(\"Foo\".to_string(), 42);\n\nassert_eq!(map.get(\"Foo\"), Some(&42));\n```\n\nThis is because the standard library has `impl Borrow<str> for String`.\n\nFor most types, when you want to take an owned or borrowed type, a `&T` is\nenough. But one area where `Borrow` is effective is when there’s more than one\nkind of borrowed value. This is especially true of references and slices: you\ncan have both an `&T` or a `&mut T`. If we wanted to accept both of these types,\n`Borrow` is up for it:\n\n```rust\nuse std::borrow::Borrow;\nuse std::fmt::Display;\n\nfn foo<T: Borrow<i32> + Display>(a: T) {\n    println!(\"a is borrowed: {}\", a);\n}\n\nlet mut i = 5;\n\nfoo(&i);\nfoo(&mut i);\n```\n\nThis will print out `a is borrowed: 5` twice.\n\n# AsRef\n\nThe `AsRef` trait is a conversion trait. It’s used for converting some value to\na reference in generic code. Like this:\n\n```rust\nlet s = \"Hello\".to_string();\n\nfn foo<T: AsRef<str>>(s: T) {\n    let slice = s.as_ref();\n}\n```\n\n# Which should I use?\n\nWe can see how they’re kind of the same: they both deal with owned and borrowed\nversions of some type. However, they’re a bit different.\n\nChoose `Borrow` when you want to abstract over different kinds of borrowing, or\nwhen you’re building a datastructure that treats owned and borrowed values in\nequivalent ways, such as hashing and comparison.\n\nChoose `AsRef` when you want to convert something to a reference directly, and\nyou’re writing generic code.\n"
  },
  {
    "path": "trpl/box-syntax-and-patterns.md",
    "content": "%  Box Syntax and Patterns\n\nCurrently the only stable way to create a `Box` is via the `Box::new` method.\nAlso it is not possible in stable Rust to destructure a `Box` in a match\npattern. The unstable `box` keyword can be used to both create and destructure\na `Box`. An example usage would be:\n\n```rust\n#![feature(box_syntax, box_patterns)]\n\nfn main() {\n    let b = Some(box 5);\n    match b {\n        Some(box n) if n < 0 => {\n            println!(\"Box contains negative number {}\", n);\n        },\n        Some(box n) if n >= 0 => {\n            println!(\"Box contains non-negative number {}\", n);\n        },\n        None => {\n            println!(\"No box\");\n        },\n        _ => unreachable!()\n    }\n}\n```\n\nNote that these features are currently hidden behind the `box_syntax` (box\ncreation) and `box_patterns` (destructuring and pattern matching) gates\nbecause the syntax may still change in the future.\n\n# Returning Pointers\n\nIn many languages with pointers, you'd return a pointer from a function\nso as to avoid copying a large data structure. For example:\n\n```rust\nstruct BigStruct {\n    one: i32,\n    two: i32,\n    // etc\n    one_hundred: i32,\n}\n\nfn foo(x: Box<BigStruct>) -> Box<BigStruct> {\n    Box::new(*x)\n}\n\nfn main() {\n    let x = Box::new(BigStruct {\n        one: 1,\n        two: 2,\n        one_hundred: 100,\n    });\n\n    let y = foo(x);\n}\n```\n\nThe idea is that by passing around a box, you're only copying a pointer, rather\nthan the hundred `i32`s that make up the `BigStruct`.\n\nThis is an antipattern in Rust. Instead, write this:\n\n```rust\n#![feature(box_syntax)]\n\nstruct BigStruct {\n    one: i32,\n    two: i32,\n    // etc\n    one_hundred: i32,\n}\n\nfn foo(x: Box<BigStruct>) -> BigStruct {\n    *x\n}\n\nfn main() {\n    let x = Box::new(BigStruct {\n        one: 1,\n        two: 2,\n        one_hundred: 100,\n    });\n\n    let y: Box<BigStruct> = box foo(x);\n}\n```\n\nThis gives you flexibility without sacrificing performance.\n\nYou may think that this gives us terrible performance: return a value and then\nimmediately box it up ?! Isn't this pattern the worst of both worlds? Rust is\nsmarter than that. There is no copy in this code. `main` allocates enough room\nfor the `box`, passes a pointer to that memory into `foo` as `x`, and then\n`foo` writes the value straight into the `Box<T>`.\n\nThis is important enough that it bears repeating: pointers are not for\noptimizing returning values from your code. Allow the caller to choose how they\nwant to use your output.\n"
  },
  {
    "path": "trpl/casting-between-types.md",
    "content": "% Casting Between Types\n\nRust, with its focus on safety, provides two different ways of casting\ndifferent types between each other. The first, `as`, is for safe casts.\nIn contrast, `transmute` allows for arbitrary casting, and is one of the\nmost dangerous features of Rust!\n\n# Coercion\n\nCoercion between types is implicit and has no syntax of its own, but can\nbe spelled out with [`as`](#explicit-coercions).\n\nCoercion occurs in `let`, `const`, and `static` statements; in\nfunction call arguments; in field values in struct initialization; and in a\nfunction result.\n\nThe most common case of coercion is removing mutability from a reference:\n\n * `&mut T` to `&T`\n\nAn analogous conversion is to remove mutability from a\n[raw pointer](raw-pointers.md):\n\n * `*mut T` to `*const T`\n\nReferences can also be coerced to raw pointers:\n\n * `&T` to `*const T`\n\n * `&mut T` to `*mut T`\n\nCustom coercions may be defined using [`Deref`](deref-coercions.md).\n\nCoercion is transitive.\n\n# `as`\n\nThe `as` keyword does safe casting:\n\n```rust\nlet x: i32 = 5;\n\nlet y = x as i64;\n```\n\nThere are three major categories of safe cast: explicit coercions, casts\nbetween numeric types, and pointer casts.\n\nCasting is not transitive: even if `e as U1 as U2` is a valid\nexpression, `e as U2` is not necessarily so (in fact it will only be valid if\n`U1` coerces to `U2`).\n\n\n## Explicit coercions\n\nA cast `e as U` is valid if `e` has type `T` and `T` *coerces* to `U`.\n\n## Numeric casts\n\nA cast `e as U` is also valid in any of the following cases:\n\n * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*\n * `e` is a C-like enum (with no data attached to the variants),\n    and `U` is an integer type; *enum-cast*\n * `e` has type `bool` or `char` and `U` is an integer type; *prim-int-cast*\n * `e` has type `u8` and `U` is `char`; *u8-char-cast*\n\nFor example\n\n```rust\nlet one = true as u8;\nlet at_sign = 64 as char;\nlet two_hundred = -56i8 as u8;\n```\n\nThe semantics of numeric casts are:\n\n* Casting between two integers of the same size (e.g. i32 -> u32) is a no-op\n* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will\n  truncate\n* Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will\n    * zero-extend if the source is unsigned\n    * sign-extend if the source is signed\n* Casting from a float to an integer will round the float towards zero\n    * **[NOTE: currently this will cause Undefined Behavior if the rounded\n      value cannot be represented by the target integer type][float-int]**.\n      This includes Inf and NaN. This is a bug and will be fixed.\n* Casting from an integer to float will produce the floating point\n  representation of the integer, rounded if necessary (rounding strategy\n  unspecified)\n* Casting from an f32 to an f64 is perfect and lossless\n* Casting from an f64 to an f32 will produce the closest possible value\n  (rounding strategy unspecified)\n    * **[NOTE: currently this will cause Undefined Behavior if the value\n      is finite but larger or smaller than the largest or smallest finite\n      value representable by f32][float-float]**. This is a bug and will\n      be fixed.\n\n[float-int]: https://github.com/rust-lang/rust/issues/10184\n[float-float]: https://github.com/rust-lang/rust/issues/15536\n\n## Pointer casts\n\nPerhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.md) to and\nfrom integers, and to cast between pointers to different types subject to\nsome constraints. It is only unsafe to dereference the pointer:\n\n```rust\nlet a = 300 as *const char; // a pointer to location 300\nlet b = a as u32;\n```\n\n`e as U` is a valid pointer cast in any of the following cases:\n\n* `e` has type `*T`, `U` has type `*U_0`, and either `U_0: Sized` or\n  `unsize_kind(T) == unsize_kind(U_0)`; a *ptr-ptr-cast*\n\n* `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*\n\n* `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*\n\n* `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*\n\n* `e` is a function pointer type and `U` has type `*T`,\n  while `T: Sized`; *fptr-ptr-cast*\n\n* `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*\n\n\n# `transmute`\n\n`as` only allows safe casting, and will for example reject an attempt to\ncast four bytes into a `u32`:\n\n```rust,ignore\nlet a = [0u8, 0u8, 0u8, 0u8];\n\nlet b = a as u32; // four u8s makes a u32\n```\n\nThis errors with:\n\n```text\nerror: non-scalar cast: `[u8; 4]` as `u32`\nlet b = a as u32; // four u8s makes a u32\n        ^~~~~~~~\n```\n\nThis is a ‘non-scalar cast’ because we have multiple values here: the four\nelements of the array. These kinds of casts are very dangerous, because they\nmake assumptions about the way that multiple underlying structures are\nimplemented. For this, we need something more dangerous.\n\nThe `transmute` function is provided by a [compiler intrinsic][intrinsics], and\nwhat it does is very simple, but very scary. It tells Rust to treat a value of\none type as though it were another type. It does this regardless of the\ntypechecking system, and completely trusts you.\n\n[intrinsics]: intrinsics.html\n\nIn our previous example, we know that an array of four `u8`s represents a `u32`\nproperly, and so we want to do the cast. Using `transmute` instead of `as`,\nRust lets us:\n\n```rust\nuse std::mem;\n\nfn main() {\n    unsafe {\n        let a = [0u8, 1u8, 0u8, 0u8];\n        let b = mem::transmute::<[u8; 4], u32>(a);\n        println!(\"{}\", b); // 256\n        // or, more concisely:\n        let c: u32 = mem::transmute(a);\n        println!(\"{}\", c); // 256\n    }\n}\n```\n\nWe have to wrap the operation in an `unsafe` block for this to compile\nsuccessfully. Technically, only the `mem::transmute` call itself needs to be in\nthe block, but it's nice in this case to enclose everything related, so you\nknow where to look. In this case, the details about `a` are also important, and\nso they're in the block. You'll see code in either style, sometimes the context\nis too far away, and wrapping all of the code in `unsafe` isn't a great idea.\n\nWhile `transmute` does very little checking, it will at least make sure that\nthe types are the same size. This errors:\n\n```rust,ignore\nuse std::mem;\n\nunsafe {\n    let a = [0u8, 0u8, 0u8, 0u8];\n\n    let b = mem::transmute::<[u8; 4], u64>(a);\n}\n```\n\nwith:\n\n```text\nerror: transmute called with differently sized types: [u8; 4] (32 bits) to u64\n(64 bits)\n```\n\nOther than that, you're on your own!\n"
  },
  {
    "path": "trpl/choosing-your-guarantees.md",
    "content": "% Choosing your Guarantees\n\nOne important feature of Rust is that it lets us control the costs and guarantees\nof a program.\n\nThere are various &ldquo;wrapper type&rdquo; abstractions in the Rust standard library which embody\na multitude of tradeoffs between cost, ergonomics, and guarantees. Many let one choose between\nrun time and compile time enforcement. This section will explain a few selected abstractions in\ndetail.\n\nBefore proceeding, it is highly recommended that one reads about [ownership][ownership] and\n[borrowing][borrowing] in Rust.\n\n[ownership]: ownership.html\n[borrowing]: references-and-borrowing.html\n\n# Basic pointer types\n\n## `Box<T>`\n\n[`Box<T>`][box] is an &ldquo;owned&rdquo; pointer, or a &ldquo;box&rdquo;. While it can hand\nout references to the contained data, it is the only owner of the data. In particular, consider\nthe following:\n\n```rust\nlet x = Box::new(1);\nlet y = x;\n// x no longer accessible here\n```\n\nHere, the box was _moved_ into `y`. As `x` no longer owns it, the compiler will no longer allow the\nprogrammer to use `x` after this. A box can similarly be moved _out_ of a function by returning it.\n\nWhen a box (that hasn't been moved) goes out of scope, destructors are run. These destructors take\ncare of deallocating the inner data.\n\nThis is a zero-cost abstraction for dynamic allocation. If you want to allocate some memory on the\nheap and safely pass around a pointer to that memory, this is ideal. Note that you will only be\nallowed to share references to this by the regular borrowing rules, checked at compile time.\n\n[box]: ../std/boxed/struct.Box.html\n\n## `&T` and `&mut T`\n\nThese are immutable and mutable references respectively. They follow the &ldquo;read-write lock&rdquo;\npattern, such that one may either have only one mutable reference to some data, or any number of\nimmutable ones, but not both. This guarantee is enforced at compile time, and has no visible cost at\nruntime. In most cases these two pointer types suffice for sharing cheap references between sections\nof code.\n\nThese pointers cannot be copied in such a way that they outlive the lifetime associated with them.\n\n## `*const T` and `*mut T`\n\nThese are C-like raw pointers with no lifetime or ownership attached to them. They point to\nsome location in memory with no other restrictions. The only guarantee that these provide is that\nthey cannot be dereferenced except in code marked `unsafe`.\n\nThese are useful when building safe, low cost abstractions like `Vec<T>`, but should be avoided in\nsafe code.\n\n## `Rc<T>`\n\nThis is the first wrapper we will cover that has a runtime cost.\n\n[`Rc<T>`][rc] is a reference counted pointer. In other words, this lets us have multiple \"owning\"\npointers to the same data, and the data will be dropped (destructors will be run) when all pointers\nare out of scope.\n\nInternally, it contains a shared &ldquo;reference count&rdquo; (also called &ldquo;refcount&rdquo;),\nwhich is incremented each time the `Rc` is cloned, and decremented each time one of the `Rc`s goes\nout of scope. The main responsibility of `Rc<T>` is to ensure that destructors are called for shared\ndata.\n\nThe internal data here is immutable, and if a cycle of references is created, the data will be\nleaked. If we want data that doesn't leak when there are cycles, we need a garbage collector.\n\n#### Guarantees\n\nThe main guarantee provided here is that the data will not be destroyed until all references to it\nare out of scope.\n\nThis should be used when we wish to dynamically allocate and share some data (read-only) between\nvarious portions of your program, where it is not certain which portion will finish using the pointer\nlast. It's a viable alternative to `&T` when `&T` is either impossible to statically check for\ncorrectness, or creates extremely unergonomic code where the programmer does not wish to spend the\ndevelopment cost of working with.\n\nThis pointer is _not_ thread safe, and Rust will not let it be sent or shared with other threads.\nThis lets one avoid the cost of atomics in situations where they are unnecessary.\n\nThere is a sister smart pointer to this one, `Weak<T>`. This is a non-owning, but also non-borrowed,\nsmart pointer. It is also similar to `&T`, but it is not restricted in lifetime&mdash;a `Weak<T>`\ncan be held on to forever. However, it is possible that an attempt to access the inner data may fail\nand return `None`, since this can outlive the owned `Rc`s. This is useful for cyclic\ndata structures and other things.\n\n#### Cost\n\nAs far as memory goes, `Rc<T>` is a single allocation, though it will allocate two extra words (i.e.\ntwo `usize` values) as compared to a regular `Box<T>` (for \"strong\" and \"weak\" refcounts).\n\n`Rc<T>` has the computational cost of incrementing/decrementing the refcount whenever it is cloned\nor goes out of scope respectively. Note that a clone will not do a deep copy, rather it will simply\nincrement the inner reference count and return a copy of the `Rc<T>`.\n\n[rc]: ../std/rc/struct.Rc.html\n\n# Cell types\n\n`Cell`s provide interior mutability. In other words, they contain data which can be manipulated even\nif the type cannot be obtained in a mutable form (for example, when it is behind an `&`-ptr or\n`Rc<T>`).\n\n[The documentation for the `cell` module has a pretty good explanation for these][cell-mod].\n\nThese types are _generally_ found in struct fields, but they may be found elsewhere too.\n\n## `Cell<T>`\n\n[`Cell<T>`][cell] is a type that provides zero-cost interior mutability, but only for `Copy` types.\nSince the compiler knows that all the data owned by the contained value is on the stack, there's\nno worry of leaking any data behind references (or worse!) by simply replacing the data.\n\nIt is still possible to violate your own invariants using this wrapper, so be careful when using it.\nIf a field is wrapped in `Cell`, it's a nice indicator that the chunk of data is mutable and may not\nstay the same between the time you first read it and when you intend to use it.\n\n```rust\nuse std::cell::Cell;\n\nlet x = Cell::new(1);\nlet y = &x;\nlet z = &x;\nx.set(2);\ny.set(3);\nz.set(4);\nprintln!(\"{}\", x.get());\n```\n\nNote that here we were able to mutate the same value from various immutable references.\n\nThis has the same runtime cost as the following:\n\n```rust,ignore\nlet mut x = 1;\nlet y = &mut x;\nlet z = &mut x;\nx = 2;\n*y = 3;\n*z = 4;\nprintln!(\"{}\", x);\n```\n\nbut it has the added benefit of actually compiling successfully.\n\n#### Guarantees\n\nThis relaxes the &ldquo;no aliasing with mutability&rdquo; restriction in places where it's\nunnecessary. However, this also relaxes the guarantees that the restriction provides; so if your\ninvariants depend on data stored within `Cell`, you should be careful.\n\nThis is useful for mutating primitives and other `Copy` types when there is no easy way of\ndoing it in line with the static rules of `&` and `&mut`.\n\n`Cell` does not let you obtain interior references to the data, which makes it safe to freely\nmutate.\n\n#### Cost\n\nThere is no runtime cost to using `Cell<T>`, however if you are using it to wrap larger (`Copy`)\nstructs, it might be worthwhile to instead wrap individual fields in `Cell<T>` since each write is\notherwise a full copy of the struct.\n\n\n## `RefCell<T>`\n\n[`RefCell<T>`][refcell] also provides interior mutability, but isn't restricted to `Copy` types.\n\nInstead, it has a runtime cost. `RefCell<T>` enforces the read-write lock pattern at runtime (it's\nlike a single-threaded mutex), unlike `&T`/`&mut T` which do so at compile time. This is done by the\n`borrow()` and `borrow_mut()` functions, which modify an internal reference count and return smart\npointers which can be dereferenced immutably and mutably respectively. The refcount is restored when\nthe smart pointers go out of scope. With this system, we can dynamically ensure that there are never\nany other borrows active when a mutable borrow is active. If the programmer attempts to make such a\nborrow, the thread will panic.\n\n```rust\nuse std::cell::RefCell;\n\nlet x = RefCell::new(vec![1,2,3,4]);\n{\n    println!(\"{:?}\", *x.borrow())\n}\n\n{\n    let mut my_ref = x.borrow_mut();\n    my_ref.push(1);\n}\n```\n\nSimilar to `Cell`, this is mainly useful for situations where it's hard or impossible to satisfy the\nborrow checker. Generally we know that such mutations won't happen in a nested form, but it's good\nto check.\n\nFor large, complicated programs, it becomes useful to put some things in `RefCell`s to make things\nsimpler. For example, a lot of the maps in the `ctxt` struct in the Rust compiler internals\nare inside this wrapper. These are only modified once (during creation, which is not right after\ninitialization) or a couple of times in well-separated places. However, since this struct is\npervasively used everywhere, juggling mutable and immutable pointers would be hard (perhaps\nimpossible) and probably form a soup of `&`-ptrs which would be hard to extend. On the other hand,\nthe `RefCell` provides a cheap (not zero-cost) way of safely accessing these. In the future, if\nsomeone adds some code that attempts to modify the cell when it's already borrowed, it will cause a\n(usually deterministic) panic which can be traced back to the offending borrow.\n\nSimilarly, in Servo's DOM there is a lot of mutation, most of which is local to a DOM type, but some\nof which crisscrosses the DOM and modifies various things. Using `RefCell` and `Cell` to guard all\nmutation lets us avoid worrying about mutability everywhere, and it simultaneously highlights the\nplaces where mutation is _actually_ happening.\n\nNote that `RefCell` should be avoided if a mostly simple solution is possible with `&` pointers.\n\n#### Guarantees\n\n`RefCell` relaxes the _static_ restrictions preventing aliased mutation, and replaces them with\n_dynamic_ ones. As such the guarantees have not changed.\n\n#### Cost\n\n`RefCell` does not allocate, but it contains an additional \"borrow state\"\nindicator (one word in size) along with the data.\n\nAt runtime each borrow causes a modification/check of the refcount.\n\n[cell-mod]: ../std/cell/index.html\n[cell]: ../std/cell/struct.Cell.html\n[refcell]: ../std/cell/struct.RefCell.html\n\n# Synchronous types\n\nMany of the types above cannot be used in a threadsafe manner. Particularly, `Rc<T>` and\n`RefCell<T>`, which both use non-atomic reference counts (_atomic_ reference counts are those which\ncan be incremented from multiple threads without causing a data race), cannot be used this way. This\nmakes them cheaper to use, but we need thread safe versions of these too. They exist, in the form of\n`Arc<T>` and `Mutex<T>`/`RwLock<T>`\n\nNote that the non-threadsafe types _cannot_ be sent between threads, and this is checked at compile\ntime.\n\nThere are many useful wrappers for concurrent programming in the [sync][sync] module, but only the\nmajor ones will be covered below.\n\n[sync]: ../std/sync/index.html\n\n## `Arc<T>`\n\n[`Arc<T>`][arc] is a version of `Rc<T>` that uses an atomic reference count (hence, \"Arc\").\nThis can be sent freely between threads.\n\nC++'s `shared_ptr` is similar to `Arc`, however in the case of C++ the inner data is always mutable.\nFor semantics similar to that from C++, we should use `Arc<Mutex<T>>`, `Arc<RwLock<T>>`, or\n`Arc<UnsafeCell<T>>`[^4] (`UnsafeCell<T>` is a cell type that can be used to hold any data and has\nno runtime cost, but accessing it requires `unsafe` blocks). The last one should only be used if we\nare certain that the usage won't cause any memory unsafety. Remember that writing to a struct is not\nan atomic operation, and many functions like `vec.push()` can reallocate internally and cause unsafe\nbehavior, so even monotonicity may not be enough to justify `UnsafeCell`.\n\n[^4]: `Arc<UnsafeCell<T>>` actually won't compile since `UnsafeCell<T>` isn't `Send` or `Sync`, but we can wrap it in a type and implement `Send`/`Sync` for it manually to get `Arc<Wrapper<T>>` where `Wrapper` is `struct Wrapper<T>(UnsafeCell<T>)`.\n\n#### Guarantees\n\nLike `Rc`, this provides the (thread safe) guarantee that the destructor for the internal data will\nbe run when the last `Arc` goes out of scope (barring any cycles).\n\n#### Cost\n\nThis has the added cost of using atomics for changing the refcount (which will happen whenever it is\ncloned or goes out of scope). When sharing data from an `Arc` in a single thread, it is preferable\nto share `&` pointers whenever possible.\n\n[arc]: ../std/sync/struct.Arc.html\n\n## `Mutex<T>` and `RwLock<T>`\n\n[`Mutex<T>`][mutex] and [`RwLock<T>`][rwlock] provide mutual-exclusion via RAII guards (guards are\nobjects which maintain some state, like a lock, until their destructor is called). For both of\nthese, the mutex is opaque until we call `lock()` on it, at which point the thread will block\nuntil a lock can be acquired, and then a guard will be returned. This guard can be used to access\nthe inner data (mutably), and the lock will be released when the guard goes out of scope.\n\n```rust,ignore\n{\n    let guard = mutex.lock();\n    // guard dereferences mutably to the inner type\n    *guard += 1;\n} // lock released when destructor runs\n```\n\n\n`RwLock` has the added benefit of being efficient for multiple reads. It is always safe to have\nmultiple readers to shared data as long as there are no writers; and `RwLock` lets readers acquire a\n\"read lock\". Such locks can be acquired concurrently and are kept track of via a reference count.\nWriters must obtain a \"write lock\" which can only be obtained when all readers have gone out of\nscope.\n\n#### Guarantees\n\nBoth of these provide safe shared mutability across threads, however they are prone to deadlocks.\nSome level of additional protocol safety can be obtained via the type system.\n\n#### Costs\n\nThese use internal atomic-like types to maintain the locks, which are pretty costly (they can block\nall memory reads across processors till they're done). Waiting on these locks can also be slow when\nthere's a lot of concurrent access happening.\n\n[rwlock]: ../std/sync/struct.RwLock.html\n[mutex]: ../std/sync/struct.Mutex.html\n[sessions]: https://github.com/Munksgaard/rust-sessions\n\n# Composition\n\nA common gripe when reading Rust code is with types like `Rc<RefCell<Vec<T>>>` (or even more\ncomplicated compositions of such types). It's not always clear what the composition does, or why the\nauthor chose one like this (and when one should be using such a composition in one's own code)\n\nUsually, it's a case of composing together the guarantees that you need, without paying for stuff\nthat is unnecessary.\n\nFor example, `Rc<RefCell<T>>` is one such composition. `Rc<T>` itself can't be dereferenced mutably;\nbecause `Rc<T>` provides sharing and shared mutability can lead to unsafe behavior, so we put\n`RefCell<T>` inside to get dynamically verified shared mutability. Now we have shared mutable data,\nbut it's shared in a way that there can only be one mutator (and no readers) or multiple readers.\n\nNow, we can take this a step further, and have `Rc<RefCell<Vec<T>>>` or `Rc<Vec<RefCell<T>>>`. These\nare both shareable, mutable vectors, but they're not the same.\n\nWith the former, the `RefCell<T>` is wrapping the `Vec<T>`, so the `Vec<T>` in its entirety is\nmutable. At the same time, there can only be one mutable borrow of the whole `Vec` at a given time.\nThis means that your code cannot simultaneously work on different elements of the vector from\ndifferent `Rc` handles. However, we are able to push and pop from the `Vec<T>` at will. This is\nsimilar to a `&mut Vec<T>` with the borrow checking done at runtime.\n\nWith the latter, the borrowing is of individual elements, but the overall vector is immutable. Thus,\nwe can independently borrow separate elements, but we cannot push or pop from the vector. This is\nsimilar to a `&mut [T]`[^3], but, again, the borrow checking is at runtime.\n\nIn concurrent programs, we have a similar situation with `Arc<Mutex<T>>`, which provides shared\nmutability and ownership.\n\nWhen reading code that uses these, go in step by step and look at the guarantees/costs provided.\n\nWhen choosing a composed type, we must do the reverse; figure out which guarantees we want, and at\nwhich point of the composition we need them. For example, if there is a choice between\n`Vec<RefCell<T>>` and `RefCell<Vec<T>>`, we should figure out the tradeoffs as done above and pick\none.\n\n[^3]: `&[T]` and `&mut [T]` are _slices_; they consist of a pointer and a length and can refer to a portion of a vector or array. `&mut [T]` can have its elements mutated, however its length cannot be touched.\n"
  },
  {
    "path": "trpl/closures.md",
    "content": "% Closures\n\nSometimes it is useful to wrap up a function and _free variables_ for better\nclarity and reuse. The free variables that can be used come from the\nenclosing scope and are ‘closed over’ when used in the function. From this, we\nget the name ‘closures’ and Rust provides a really great implementation of\nthem, as we’ll see.\n\n# Syntax\n\nClosures look like this:\n\n```rust\nlet plus_one = |x: i32| x + 1;\n\nassert_eq!(2, plus_one(1));\n```\n\nWe create a binding, `plus_one`, and assign it to a closure. The closure’s\narguments go between the pipes (`|`), and the body is an expression, in this\ncase, `x + 1`. Remember that `{ }` is an expression, so we can have multi-line\nclosures too:\n\n```rust\nlet plus_two = |x| {\n    let mut result: i32 = x;\n\n    result += 1;\n    result += 1;\n\n    result\n};\n\nassert_eq!(4, plus_two(2));\n```\n\nYou’ll notice a few things about closures that are a bit different from regular\nnamed functions defined with `fn`. The first is that we did not need to\nannotate the types of arguments the closure takes or the values it returns. We\ncan:\n\n```rust\nlet plus_one = |x: i32| -> i32 { x + 1 };\n\nassert_eq!(2, plus_one(1));\n```\n\nBut we don’t have to. Why is this? Basically, it was chosen for ergonomic\nreasons. While specifying the full type for named functions is helpful with\nthings like documentation and type inference, the full type signatures of\nclosures are rarely documented since they’re anonymous, and they don’t cause\nthe kinds of error-at-a-distance problems that inferring named function types\ncan.\n\nThe second is that the syntax is similar, but a bit different. I’ve added\nspaces here for easier comparison:\n\n```rust\nfn  plus_one_v1   (x: i32) -> i32 { x + 1 }\nlet plus_one_v2 = |x: i32| -> i32 { x + 1 };\nlet plus_one_v3 = |x: i32|          x + 1  ;\n```\n\nSmall differences, but they’re similar.\n\n# Closures and their environment\n\nThe environment for a closure can include bindings from its enclosing scope in\naddition to parameters and local bindings. It looks like this:\n\n```rust\nlet num = 5;\nlet plus_num = |x: i32| x + num;\n\nassert_eq!(10, plus_num(5));\n```\n\nThis closure, `plus_num`, refers to a `let` binding in its scope: `num`. More\nspecifically, it borrows the binding. If we do something that would conflict\nwith that binding, we get an error. Like this one:\n\n```rust,ignore\nlet mut num = 5;\nlet plus_num = |x: i32| x + num;\n\nlet y = &mut num;\n```\n\nWhich errors with:\n\n```text\nerror: cannot borrow `num` as mutable because it is also borrowed as immutable\n    let y = &mut num;\n                 ^~~\nnote: previous borrow of `num` occurs here due to use in closure; the immutable\n  borrow prevents subsequent moves or mutable borrows of `num` until the borrow\n  ends\n    let plus_num = |x| x + num;\n                   ^~~~~~~~~~~\nnote: previous borrow ends here\nfn main() {\n    let mut num = 5;\n    let plus_num = |x| x + num;\n\n    let y = &mut num;\n}\n^\n```\n\nA verbose yet helpful error message! As it says, we can’t take a mutable borrow\non `num` because the closure is already borrowing it. If we let the closure go\nout of scope, we can:\n\n```rust\nlet mut num = 5;\n{\n    let plus_num = |x: i32| x + num;\n\n} // plus_num goes out of scope, borrow of num ends\n\nlet y = &mut num;\n```\n\nIf your closure requires it, however, Rust will take ownership and move\nthe environment instead. This doesn’t work:\n\n```rust,ignore\nlet nums = vec![1, 2, 3];\n\nlet takes_nums = || nums;\n\nprintln!(\"{:?}\", nums);\n```\n\nWe get this error:\n\n```text\nnote: `nums` moved into closure environment here because it has type\n  `[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable\nlet takes_nums = || nums;\n                 ^~~~~~~\n```\n\n`Vec<T>` has ownership over its contents, and therefore, when we refer to it\nin our closure, we have to take ownership of `nums`. It’s the same as if we’d\npassed `nums` to a function that took ownership of it.\n\n## `move` closures\n\nWe can force our closure to take ownership of its environment with the `move`\nkeyword:\n\n```rust\nlet num = 5;\n\nlet owns_num = move |x: i32| x + num;\n```\n\nNow, even though the keyword is `move`, the variables follow normal move semantics.\nIn this case, `5` implements `Copy`, and so `owns_num` takes ownership of a copy\nof `num`. So what’s the difference?\n\n```rust\nlet mut num = 5;\n\n{\n    let mut add_num = |x: i32| num += x;\n\n    add_num(5);\n}\n\nassert_eq!(10, num);\n```\n\nSo in this case, our closure took a mutable reference to `num`, and then when\nwe called `add_num`, it mutated the underlying value, as we’d expect. We also\nneeded to declare `add_num` as `mut` too, because we’re mutating its\nenvironment.\n\nIf we change to a `move` closure, it’s different:\n\n```rust\nlet mut num = 5;\n\n{\n    let mut add_num = move |x: i32| num += x;\n\n    add_num(5);\n}\n\nassert_eq!(5, num);\n```\n\nWe only get `5`. Rather than taking a mutable borrow out on our `num`, we took\nownership of a copy.\n\nAnother way to think about `move` closures: they give a closure its own stack\nframe.  Without `move`, a closure may be tied to the stack frame that created\nit, while a `move` closure is self-contained. This means that you cannot\ngenerally return a non-`move` closure from a function, for example.\n\nBut before we talk about taking and returning closures, we should talk some\nmore about the way that closures are implemented. As a systems language, Rust\ngives you tons of control over what your code does, and closures are no\ndifferent.\n\n# Closure implementation\n\nRust’s implementation of closures is a bit different than other languages. They\nare effectively syntax sugar for traits. You’ll want to make sure to have read\nthe [traits][traits] section before this one, as well as the section on [trait\nobjects][trait-objects].\n\n[traits]: traits.html\n[trait-objects]: trait-objects.html\n\nGot all that? Good.\n\nThe key to understanding how closures work under the hood is something a bit\nstrange: Using `()` to call a function, like `foo()`, is an overloadable\noperator. From this, everything else clicks into place. In Rust, we use the\ntrait system to overload operators. Calling functions is no different. We have\nthree separate traits to overload with:\n\n```rust\n# #![feature(unboxed_closures)]\n# mod foo {\npub trait Fn<Args> : FnMut<Args> {\n    extern \"rust-call\" fn call(&self, args: Args) -> Self::Output;\n}\n\npub trait FnMut<Args> : FnOnce<Args> {\n    extern \"rust-call\" fn call_mut(&mut self, args: Args) -> Self::Output;\n}\n\npub trait FnOnce<Args> {\n    type Output;\n\n    extern \"rust-call\" fn call_once(self, args: Args) -> Self::Output;\n}\n# }\n```\n\nYou’ll notice a few differences between these traits, but a big one is `self`:\n`Fn` takes `&self`, `FnMut` takes `&mut self`, and `FnOnce` takes `self`. This\ncovers all three kinds of `self` via the usual method call syntax. But we’ve\nsplit them up into three traits, rather than having a single one. This gives us\na large amount of control over what kind of closures we can take.\n\nThe `|| {}` syntax for closures is sugar for these three traits. Rust will\ngenerate a struct for the environment, `impl` the appropriate trait, and then\nuse it.\n\n# Taking closures as arguments\n\nNow that we know that closures are traits, we already know how to accept and\nreturn closures: the same as any other trait!\n\nThis also means that we can choose static vs dynamic dispatch as well. First,\nlet’s write a function which takes something callable, calls it, and returns\nthe result:\n\n```rust\nfn call_with_one<F>(some_closure: F) -> i32\n    where F : Fn(i32) -> i32 {\n\n    some_closure(1)\n}\n\nlet answer = call_with_one(|x| x + 2);\n\nassert_eq!(3, answer);\n```\n\nWe pass our closure, `|x| x + 2`, to `call_with_one`. It does what it\nsuggests: it calls the closure, giving it `1` as an argument.\n\nLet’s examine the signature of `call_with_one` in more depth:\n\n```rust\nfn call_with_one<F>(some_closure: F) -> i32\n#    where F : Fn(i32) -> i32 {\n#    some_closure(1) }\n```\n\nWe take one parameter, and it has the type `F`. We also return a `i32`. This part\nisn’t interesting. The next part is:\n\n```rust\n# fn call_with_one<F>(some_closure: F) -> i32\n    where F : Fn(i32) -> i32 {\n#   some_closure(1) }\n```\n\nBecause `Fn` is a trait, we can use it as a bound for our generic type. In\nthis case, our closure takes a `i32` as an argument and returns an `i32`, and\nso the generic bound we use is `Fn(i32) -> i32`.\n\nThere’s one other key point here: because we’re bounding a generic with a\ntrait, this will get monomorphized, and therefore, we’ll be doing static\ndispatch into the closure. That’s pretty neat. In many languages, closures are\ninherently heap allocated, and will always involve dynamic dispatch. In Rust,\nwe can stack allocate our closure environment, and statically dispatch the\ncall. This happens quite often with iterators and their adapters, which often\ntake closures as arguments.\n\nOf course, if we want dynamic dispatch, we can get that too. A trait object\nhandles this case, as usual:\n\n```rust\nfn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {\n    some_closure(1)\n}\n\nlet answer = call_with_one(&|x| x + 2);\n\nassert_eq!(3, answer);\n```\n\nNow we take a trait object, a `&Fn`. And we have to make a reference\nto our closure when we pass it to `call_with_one`, so we use `&||`.\n\nA quick note about closures that use explicit lifetimes. Sometimes you might have a closure\nthat takes a reference like so:\n\n```rust\nfn call_with_ref<F>(some_closure:F) -> i32\n    where F: Fn(&i32) -> i32 {\n\n    let mut value = 0;\n    some_closure(&value)\n}\n```\n\nNormally you can specify the lifetime of the parameter to our closure. We\ncould annotate it on the function declaration:\n\n```rust,ignore\nfn call_with_ref<'a, F>(some_closure:F) -> i32\n    where F: Fn(&'a i32) -> i32 {\n```\n\nHowever this presents a problem with in our case. When you specify the explicit\nlifetime on a function it binds that lifetime to the *entire* scope of the function\ninstead of just the invocation scope of our closure. This means that the borrow checker\nwill see a mutable reference in the same lifetime as our immutable reference and fail\nto compile.\n\nIn order to say that we only need the lifetime to be valid for the invocation scope\nof the closure we can use Higher-Ranked Trait Bounds with the `for<...>` syntax:\n\n```ignore\nfn call_with_ref<F>(some_closure:F) -> i32\n    where F: for<'a> Fn(&'a i32) -> i32 {\n```\n\nThis lets the Rust compiler find the minimum lifetime to invoke our closure and\nsatisfy the borrow checker's rules. Our function then compiles and executes as we\nexpect.\n\n```rust\nfn call_with_ref<F>(some_closure:F) -> i32\n    where F: for<'a> Fn(&'a i32) -> i32 {\n\n    let mut value = 0;\n    some_closure(&value)\n}\n```\n\n# Function pointers and closures\n\nA function pointer is kind of like a closure that has no environment. As such,\nyou can pass a function pointer to any function expecting a closure argument,\nand it will work:\n\n```rust\nfn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {\n    some_closure(1)\n}\n\nfn add_one(i: i32) -> i32 {\n    i + 1\n}\n\nlet f = add_one;\n\nlet answer = call_with_one(&f);\n\nassert_eq!(2, answer);\n```\n\nIn this example, we don’t strictly need the intermediate variable `f`,\nthe name of the function works just fine too:\n\n```rust,ignore\nlet answer = call_with_one(&add_one);\n```\n\n# Returning closures\n\nIt’s very common for functional-style code to return closures in various\nsituations. If you try to return a closure, you may run into an error. At\nfirst, it may seem strange, but we’ll figure it out. Here’s how you’d probably\ntry to return a closure from a function:\n\n```rust,ignore\nfn factory() -> (Fn(i32) -> i32) {\n    let num = 5;\n\n    |x| x + num\n}\n\nlet f = factory();\n\nlet answer = f(1);\nassert_eq!(6, answer);\n```\n\nThis gives us these long, related errors:\n\n```text\nerror: the trait bound `core::ops::Fn(i32) -> i32 : core::marker::Sized` is not satisfied [E0277]\nfn factory() -> (Fn(i32) -> i32) {\n                ^~~~~~~~~~~~~~~~\nnote: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time\nfn factory() -> (Fn(i32) -> i32) {\n                ^~~~~~~~~~~~~~~~\nerror: the trait bound `core::ops::Fn(i32) -> i32 : core::marker::Sized` is not satisfied [E0277]\nlet f = factory();\n    ^\nnote: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time\nlet f = factory();\n    ^\n```\n\nIn order to return something from a function, Rust needs to know what\nsize the return type is. But since `Fn` is a trait, it could be various\nthings of various sizes: many different types can implement `Fn`. An easy\nway to give something a size is to take a reference to it, as references\nhave a known size. So we’d write this:\n\n```rust,ignore\nfn factory() -> &(Fn(i32) -> i32) {\n    let num = 5;\n\n    |x| x + num\n}\n\nlet f = factory();\n\nlet answer = f(1);\nassert_eq!(6, answer);\n```\n\nBut we get another error:\n\n```text\nerror: missing lifetime specifier [E0106]\nfn factory() -> &(Fn(i32) -> i32) {\n                ^~~~~~~~~~~~~~~~~\n```\n\nRight. Because we have a reference, we need to give it a lifetime. But\nour `factory()` function takes no arguments, so\n[elision](lifetimes.html#lifetime-elision) doesn’t kick in here. Then what\nchoices do we have? Try `'static`:\n\n```rust,ignore\nfn factory() -> &'static (Fn(i32) -> i32) {\n    let num = 5;\n\n    |x| x + num\n}\n\nlet f = factory();\n\nlet answer = f(1);\nassert_eq!(6, answer);\n```\n\nBut we get another error:\n\n```text\nerror: mismatched types:\n expected `&'static core::ops::Fn(i32) -> i32`,\n    found `[closure@<anon>:7:9: 7:20]`\n(expected &-ptr,\n    found closure) [E0308]\n         |x| x + num\n         ^~~~~~~~~~~\n\n```\n\nThis error is letting us know that we don’t have a `&'static Fn(i32) -> i32`,\nwe have a `[closure@<anon>:7:9: 7:20]`. Wait, what?\n\nBecause each closure generates its own environment `struct` and implementation\nof `Fn` and friends, these types are anonymous. They exist solely for\nthis closure. So Rust shows them as `closure@<anon>`, rather than some\nautogenerated name.\n\nThe error also points out that the return type is expected to be a reference,\nbut what we are trying to return is not. Further, we cannot directly assign a\n`'static` lifetime to an object. So we'll take a different approach and return\na ‘trait object’ by `Box`ing up the `Fn`. This _almost_ works:\n\n```rust,ignore\nfn factory() -> Box<Fn(i32) -> i32> {\n    let num = 5;\n\n    Box::new(|x| x + num)\n}\n# fn main() {\nlet f = factory();\n\nlet answer = f(1);\nassert_eq!(6, answer);\n# }\n```\n\nThere’s just one last problem:\n\n```text\nerror: closure may outlive the current function, but it borrows `num`,\nwhich is owned by the current function [E0373]\nBox::new(|x| x + num)\n         ^~~~~~~~~~~\n```\n\nWell, as we discussed before, closures borrow their environment. And in this\ncase, our environment is based on a stack-allocated `5`, the `num` variable\nbinding. So the borrow has a lifetime of the stack frame. So if we returned\nthis closure, the function call would be over, the stack frame would go away,\nand our closure is capturing an environment of garbage memory! With one last\nfix, we can make this work:\n\n```rust\nfn factory() -> Box<Fn(i32) -> i32> {\n    let num = 5;\n\n    Box::new(move |x| x + num)\n}\nfn main() {\nlet f = factory();\n\nlet answer = f(1);\nassert_eq!(6, answer);\n}\n```\n\nBy making the inner closure a `move Fn`, we create a new stack frame for our\nclosure. By `Box`ing it up, we’ve given it a known size, allowing it to\nescape our stack frame.\n"
  },
  {
    "path": "trpl/comments.md",
    "content": "% Comments\n\nNow that we have some functions, it’s a good idea to learn about comments.\nComments are notes that you leave to other programmers to help explain things\nabout your code. The compiler mostly ignores them.\n\nRust has two kinds of comments that you should care about: *line comments*\nand *doc comments*.\n\n```rust\n// Line comments are anything after ‘//’ and extend to the end of the line.\n\nlet x = 5; // this is also a line comment.\n\n// If you have a long explanation for something, you can put line comments next\n// to each other. Put a space between the // and your comment so that it’s\n// more readable.\n```\n\nThe other kind of comment is a doc comment. Doc comments use `///` instead of\n`//`, and support Markdown notation inside:\n\n```rust\n/// Adds one to the number given.\n///\n/// # Examples\n///\n/// ```\n/// let five = 5;\n///\n/// assert_eq!(6, add_one(5));\n/// # fn add_one(x: i32) -> i32 {\n/// #     x + 1\n/// # }\n/// ```\nfn add_one(x: i32) -> i32 {\n    x + 1\n}\n```\n\nThere is another style of doc comment, `//!`, to comment containing items (e.g.\ncrates, modules or functions), instead of the items following it. Commonly used\ninside crates root (lib.rs) or modules root (mod.rs):\n\n```\n//! # The Rust Standard Library\n//!\n//! The Rust Standard Library provides the essential runtime\n//! functionality for building portable Rust software.\n```\n\nWhen writing doc comments, providing some examples of usage is very, very\nhelpful. You’ll notice we’ve used a new macro here: `assert_eq!`. This compares\ntwo values, and `panic!`s if they’re not equal to each other. It’s very helpful\nin documentation. There’s another macro, `assert!`, which `panic!`s if the\nvalue passed to it is `false`.\n\nYou can use the [`rustdoc`](documentation.html) tool to generate HTML documentation\nfrom these doc comments, and also to run the code examples as tests!\n"
  },
  {
    "path": "trpl/compiler-plugins.md",
    "content": "% Compiler Plugins\n\n# Introduction\n\n`rustc` can load compiler plugins, which are user-provided libraries that\nextend the compiler's behavior with new syntax extensions, lint checks, etc.\n\nA plugin is a dynamic library crate with a designated *registrar* function that\nregisters extensions with `rustc`. Other crates can load these extensions using\nthe crate attribute `#![plugin(...)]`.  See the\n`rustc_plugin` documentation for more about the\nmechanics of defining and loading a plugin.\n\nIf present, arguments passed as `#![plugin(foo(... args ...))]` are not\ninterpreted by rustc itself.  They are provided to the plugin through the\n`Registry`'s `args` method.\n\nIn the vast majority of cases, a plugin should *only* be used through\n`#![plugin]` and not through an `extern crate` item.  Linking a plugin would\npull in all of libsyntax and librustc as dependencies of your crate.  This is\ngenerally unwanted unless you are building another plugin.  The\n`plugin_as_library` lint checks these guidelines.\n\nThe usual practice is to put compiler plugins in their own crate, separate from\nany `macro_rules!` macros or ordinary Rust code meant to be used by consumers\nof a library.\n\n# Syntax extensions\n\nPlugins can extend Rust's syntax in various ways. One kind of syntax extension\nis the procedural macro. These are invoked the same way as [ordinary\nmacros](macros.html), but the expansion is performed by arbitrary Rust\ncode that manipulates syntax trees at\ncompile time.\n\nLet's write a plugin\n[`roman_numerals.rs`](https://github.com/rust-lang/rust/blob/master/src/test/run-pass-fulldeps/auxiliary/roman_numerals.rs)\nthat implements Roman numeral integer literals.\n\n```rust,ignore\n#![crate_type=\"dylib\"]\n#![feature(plugin_registrar, rustc_private)]\n\nextern crate syntax;\nextern crate rustc;\nextern crate rustc_plugin;\n\nuse syntax::parse::token;\nuse syntax::ast::TokenTree;\nuse syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};\nuse syntax::ext::build::AstBuilder;  // trait for expr_usize\nuse syntax_pos::Span;\nuse rustc_plugin::Registry;\n\nfn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])\n        -> Box<MacResult + 'static> {\n\n    static NUMERALS: &'static [(&'static str, usize)] = &[\n        (\"M\", 1000), (\"CM\", 900), (\"D\", 500), (\"CD\", 400),\n        (\"C\",  100), (\"XC\",  90), (\"L\",  50), (\"XL\",  40),\n        (\"X\",   10), (\"IX\",   9), (\"V\",   5), (\"IV\",   4),\n        (\"I\",    1)];\n\n    if args.len() != 1 {\n        cx.span_err(\n            sp,\n            &format!(\"argument should be a single identifier, but got {} arguments\", args.len()));\n        return DummyResult::any(sp);\n    }\n\n    let text = match args[0] {\n        TokenTree::Token(_, token::Ident(s, _)) => s.to_string(),\n        _ => {\n            cx.span_err(sp, \"argument should be a single identifier\");\n            return DummyResult::any(sp);\n        }\n    };\n\n    let mut text = &*text;\n    let mut total = 0;\n    while !text.is_empty() {\n        match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {\n            Some(&(rn, val)) => {\n                total += val;\n                text = &text[rn.len()..];\n            }\n            None => {\n                cx.span_err(sp, \"invalid Roman numeral\");\n                return DummyResult::any(sp);\n            }\n        }\n    }\n\n    MacEager::expr(cx.expr_usize(sp, total))\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n    reg.register_macro(\"rn\", expand_rn);\n}\n```\n\nThen we can use `rn!()` like any other macro:\n\n```rust,ignore\n#![feature(plugin)]\n#![plugin(roman_numerals)]\n\nfn main() {\n    assert_eq!(rn!(MMXV), 2015);\n}\n```\n\nThe advantages over a simple `fn(&str) -> u32` are:\n\n* The (arbitrarily complex) conversion is done at compile time.\n* Input validation is also performed at compile time.\n* It can be extended to allow use in patterns, which effectively gives\n  a way to define new literal syntax for any data type.\n\nIn addition to procedural macros, you can define new\n[`derive`](../reference.html#derive)-like attributes and other kinds of\nextensions.  See `Registry::register_syntax_extension` and the `SyntaxExtension`\nenum.  For a more involved macro example, see\n[`regex_macros`](https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs).\n\n\n## Tips and tricks\n\nSome of the [macro debugging tips](macros.html#debugging-macro-code) are applicable.\n\nYou can use `syntax::parse` to turn token trees into\nhigher-level syntax elements like expressions:\n\n```rust,ignore\nfn expand_foo(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])\n        -> Box<MacResult+'static> {\n\n    let mut parser = cx.new_parser_from_tts(args);\n\n    let expr: P<Expr> = parser.parse_expr();\n```\n\nLooking through [`libsyntax` parser\ncode](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs)\nwill give you a feel for how the parsing infrastructure works.\n\nKeep the `Span`s of everything you parse, for better error reporting. You can\nwrap `Spanned` around your custom data structures.\n\nCalling `ExtCtxt::span_fatal` will immediately abort compilation. It's better to\ninstead call `ExtCtxt::span_err` and return `DummyResult` so that the compiler\ncan continue and find further errors.\n\nTo print syntax fragments for debugging, you can use `span_note` together with\n`syntax::print::pprust::*_to_string`.\n\nThe example above produced an integer literal using `AstBuilder::expr_usize`.\nAs an alternative to the `AstBuilder` trait, `libsyntax` provides a set of\nquasiquote macros. They are undocumented and very rough around the edges.\nHowever, the implementation may be a good starting point for an improved\nquasiquote as an ordinary plugin library.\n\n\n# Lint plugins\n\nPlugins can extend [Rust's lint\ninfrastructure](../reference.html#lint-check-attributes) with additional checks for\ncode style, safety, etc. Now let's write a plugin\n[`lint_plugin_test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/run-pass-fulldeps/auxiliary/lint_plugin_test.rs)\nthat warns about any item named `lintme`.\n\n```rust,ignore\n#![feature(plugin_registrar)]\n#![feature(box_syntax, rustc_private)]\n\nextern crate syntax;\n\n// Load rustc as a plugin to get macros\n#[macro_use]\nextern crate rustc;\nextern crate rustc_plugin;\n\nuse rustc::lint::{EarlyContext, LintContext, LintPass, EarlyLintPass,\n                  EarlyLintPassObject, LintArray};\nuse rustc_plugin::Registry;\nuse syntax::ast;\n\ndeclare_lint!(TEST_LINT, Warn, \"Warn about items named 'lintme'\");\n\nstruct Pass;\n\nimpl LintPass for Pass {\n    fn get_lints(&self) -> LintArray {\n        lint_array!(TEST_LINT)\n    }\n}\n\nimpl EarlyLintPass for Pass {\n    fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {\n        if it.ident.name.as_str() == \"lintme\" {\n            cx.span_lint(TEST_LINT, it.span, \"item is named 'lintme'\");\n        }\n    }\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n    reg.register_early_lint_pass(box Pass as EarlyLintPassObject);\n}\n```\n\nThen code like\n\n```rust,ignore\n#![plugin(lint_plugin_test)]\n\nfn lintme() { }\n```\n\nwill produce a compiler warning:\n\n```txt\nfoo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default\nfoo.rs:4 fn lintme() { }\n         ^~~~~~~~~~~~~~~\n```\n\nThe components of a lint plugin are:\n\n* one or more `declare_lint!` invocations, which define static `Lint` structs;\n\n* a struct holding any state needed by the lint pass (here, none);\n\n* a `LintPass`\n  implementation defining how to check each syntax element. A single\n  `LintPass` may call `span_lint` for several different `Lint`s, but should\n  register them all through the `get_lints` method.\n\nLint passes are syntax traversals, but they run at a late stage of compilation\nwhere type information is available. `rustc`'s [built-in\nlints](https://github.com/rust-lang/rust/blob/master/src/librustc/lint/builtin.rs)\nmostly use the same infrastructure as lint plugins, and provide examples of how\nto access type information.\n\nLints defined by plugins are controlled by the usual [attributes and compiler\nflags](../reference.html#lint-check-attributes), e.g. `#[allow(test_lint)]` or\n`-A test-lint`. These identifiers are derived from the first argument to\n`declare_lint!`, with appropriate case and punctuation conversion.\n\nYou can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,\nincluding those provided by plugins loaded by `foo.rs`.\n"
  },
  {
    "path": "trpl/concurrency.md",
    "content": "% Concurrency\n\nConcurrency and parallelism are incredibly important topics in computer\nscience, and are also a hot topic in industry today. Computers are gaining more\nand more cores, yet many programmers aren't prepared to fully utilize them.\n\nRust's memory safety features also apply to its concurrency story too. Even\nconcurrent Rust programs must be memory safe, having no data races. Rust's type\nsystem is up to the task, and gives you powerful ways to reason about\nconcurrent code at compile time.\n\nBefore we talk about the concurrency features that come with Rust, it's important\nto understand something: Rust is low-level enough that the vast majority of\nthis is provided by the standard library, not by the language. This means that\nif you don't like some aspect of the way Rust handles concurrency, you can\nimplement an alternative way of doing things.\n[mio](https://github.com/carllerche/mio) is a real-world example of this\nprinciple in action.\n\n## Background: `Send` and `Sync`\n\nConcurrency is difficult to reason about. In Rust, we have a strong, static\ntype system to help us reason about our code. As such, Rust gives us two traits\nto help us make sense of code that can possibly be concurrent.\n\n### `Send`\n\nThe first trait we're going to talk about is\n[`Send`](../std/marker/trait.Send.html). When a type `T` implements `Send`, it\nindicates that something of this type is able to have ownership transferred\nsafely between threads.\n\nThis is important to enforce certain restrictions. For example, if we have a\nchannel connecting two threads, we would want to be able to send some data\ndown the channel and to the other thread. Therefore, we'd ensure that `Send` was\nimplemented for that type.\n\nIn the opposite way, if we were wrapping a library with [FFI][ffi] that isn't\nthreadsafe, we wouldn't want to implement `Send`, and so the compiler will help\nus enforce that it can't leave the current thread.\n\n[ffi]: ffi.html\n\n### `Sync`\n\nThe second of these traits is called [`Sync`](../std/marker/trait.Sync.html).\nWhen a type `T` implements `Sync`, it indicates that something\nof this type has no possibility of introducing memory unsafety when used from\nmultiple threads concurrently through shared references. This implies that\ntypes which don't have [interior mutability](mutability.html) are inherently\n`Sync`, which includes simple primitive types (like `u8`) and aggregate types\ncontaining them.\n\nFor sharing references across threads, Rust provides a wrapper type called\n`Arc<T>`. `Arc<T>` implements `Send` and `Sync` if and only if `T` implements\nboth `Send` and `Sync`. For example, an object of type `Arc<RefCell<U>>` cannot\nbe transferred across threads because\n[`RefCell`](choosing-your-guarantees.html#refcellt) does not implement\n`Sync`, consequently `Arc<RefCell<U>>` would not implement `Send`.\n\nThese two traits allow you to use the type system to make strong guarantees\nabout the properties of your code under concurrency. Before we demonstrate\nwhy, we need to learn how to create a concurrent Rust program in the first\nplace!\n\n## Threads\n\nRust's standard library provides a library for threads, which allow you to\nrun Rust code in parallel. Here's a basic example of using `std::thread`:\n\n```rust\nuse std::thread;\n\nfn main() {\n    thread::spawn(|| {\n        println!(\"Hello from a thread!\");\n    });\n}\n```\n\nThe `thread::spawn()` method accepts a [closure](closures.html), which is executed in a\nnew thread. It returns a handle to the thread, that can be used to\nwait for the child thread to finish and extract its result:\n\n```rust\nuse std::thread;\n\nfn main() {\n    let handle = thread::spawn(|| {\n        \"Hello from a thread!\"\n    });\n\n    println!(\"{}\", handle.join().unwrap());\n}\n```\n\nAs closures can capture variables from their environment, we can also try to\nbring some data into the other thread:\n\n```rust,ignore\nuse std::thread;\n\nfn main() {\n    let x = 1;\n    thread::spawn(|| {\n        println!(\"x is {}\", x);\n    });\n}\n```\n\nHowever, this gives us an error:\n\n```text\n5:19: 7:6 error: closure may outlive the current function, but it\n                 borrows `x`, which is owned by the current function\n...\n5:19: 7:6 help: to force the closure to take ownership of `x` (and any other referenced variables),\n          use the `move` keyword, as shown:\n      thread::spawn(move || {\n          println!(\"x is {}\", x);\n      });\n```\n\nThis is because by default closures capture variables by reference, and thus the\nclosure only captures a _reference to `x`_. This is a problem, because the\nthread may outlive the scope of `x`, leading to a dangling pointer.\n\nTo fix this, we use a `move` closure as mentioned in the error message. `move`\nclosures are explained in depth [here](closures.html#move-closures); basically\nthey move variables from their environment into themselves.\n\n```rust\nuse std::thread;\n\nfn main() {\n    let x = 1;\n    thread::spawn(move || {\n        println!(\"x is {}\", x);\n    });\n}\n```\n\nMany languages have the ability to execute threads, but it's wildly unsafe.\nThere are entire books about how to prevent errors that occur from shared\nmutable state. Rust helps out with its type system here as well, by preventing\ndata races at compile time. Let's talk about how you actually share things\nbetween threads.\n\n## Safe Shared Mutable State\n\nDue to Rust's type system, we have a concept that sounds like a lie: \"safe\nshared mutable state.\" Many programmers agree that shared mutable state is\nvery, very bad.\n\nSomeone once said this:\n\n> Shared mutable state is the root of all evil. Most languages attempt to deal\n> with this problem through the 'mutable' part, but Rust deals with it by\n> solving the 'shared' part.\n\nThe same [ownership system](ownership.html) that helps prevent using pointers\nincorrectly also helps rule out data races, one of the worst kinds of\nconcurrency bugs.\n\nAs an example, here is a Rust program that would have a data race in many\nlanguages. It will not compile:\n\n```rust,ignore\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n    let mut data = vec![1, 2, 3];\n\n    for i in 0..3 {\n        thread::spawn(move || {\n            data[0] += i;\n        });\n    }\n\n    thread::sleep(Duration::from_millis(50));\n}\n```\n\nThis gives us an error:\n\n```text\n8:17 error: capture of moved value: `data`\n        data[0] += i;\n        ^~~~\n```\n\nRust knows this wouldn't be safe! If we had a reference to `data` in each\nthread, and the thread takes ownership of the reference, we'd have three owners!\n`data` gets moved out of `main` in the first call to `spawn()`, so subsequent\ncalls in the loop cannot use this variable.\n\nSo, we need some type that lets us have more than one owning reference to a\nvalue. Usually, we'd use `Rc<T>` for this, which is a reference counted type\nthat provides shared ownership. It has some runtime bookkeeping that keeps track\nof the number of references to it, hence the \"reference count\" part of its name.\n\nCalling `clone()` on an `Rc<T>` will return a new owned reference and bump the\ninternal reference count. We create one of these for each thread:\n\n\n```rust,ignore\nuse std::thread;\nuse std::time::Duration;\nuse std::rc::Rc;\n\nfn main() {\n    let mut data = Rc::new(vec![1, 2, 3]);\n\n    for i in 0..3 {\n        // create a new owned reference\n        let data_ref = data.clone();\n\n        // use it in a thread\n        thread::spawn(move || {\n            data_ref[0] += i;\n        });\n    }\n\n    thread::sleep(Duration::from_millis(50));\n}\n```\n\nThis won't work, however, and will give us the error:\n\n```text\n13:9: 13:22 error: the trait bound `alloc::rc::Rc<collections::vec::Vec<i32>> : core::marker::Send`\n            is not satisfied\n...\n13:9: 13:22 note: `alloc::rc::Rc<collections::vec::Vec<i32>>`\n            cannot be sent between threads safely\n```\n\nAs the error message mentions, `Rc` cannot be sent between threads safely. This\nis because the internal reference count is not maintained in a thread safe\nmatter and can have a data race.\n\nTo solve this, we'll use `Arc<T>`, Rust's standard atomic reference count type.\n\nThe Atomic part means `Arc<T>` can safely be accessed from multiple threads.\nTo do this the compiler guarantees that mutations of the internal count use\nindivisible operations which can't have data races.\n\nIn essence, `Arc<T>` is a type that lets us share ownership of data _across\nthreads_.\n\n\n```rust,ignore\nuse std::thread;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nfn main() {\n    let mut data = Arc::new(vec![1, 2, 3]);\n\n    for i in 0..3 {\n        let data = data.clone();\n        thread::spawn(move || {\n            data[0] += i;\n        });\n    }\n\n    thread::sleep(Duration::from_millis(50));\n}\n```\n\nSimilarly to last time, we use `clone()` to create a new owned handle.\nThis handle is then moved into the new thread.\n\nAnd... still gives us an error.\n\n```text\n<anon>:11:24 error: cannot borrow immutable borrowed content as mutable\n<anon>:11                    data[0] += i;\n                             ^~~~\n```\n\n`Arc<T>` by default has immutable contents. It allows the _sharing_ of data\nbetween threads, but shared mutable data is unsafe and when threads are\ninvolved can cause data races!\n\n\nUsually when we wish to make something in an immutable position mutable, we use\n`Cell<T>` or `RefCell<T>` which allow safe mutation via runtime checks or\notherwise (see also: [Choosing Your Guarantees](choosing-your-guarantees.html)).\nHowever, similar to `Rc`, these are not thread safe. If we try using these, we\nwill get an error about these types not being `Sync`, and the code will fail to\ncompile.\n\nIt looks like we need some type that allows us to safely mutate a shared value\nacross threads, for example a type that can ensure only one thread at a time is\nable to mutate the value inside it at any one time.\n\nFor that, we can use the `Mutex<T>` type!\n\nHere's the working version:\n\n```rust\nuse std::sync::{Arc, Mutex};\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n    let data = Arc::new(Mutex::new(vec![1, 2, 3]));\n\n    for i in 0..3 {\n        let data = data.clone();\n        thread::spawn(move || {\n            let mut data = data.lock().unwrap();\n            data[0] += i;\n        });\n    }\n\n    thread::sleep(Duration::from_millis(50));\n}\n```\n\nNote that the value of `i` is bound (copied) to the closure and not shared\namong the threads.\n\nWe're \"locking\" the mutex here. A mutex (short for \"mutual exclusion\"), as\nmentioned, only allows one thread at a time to access a value. When we wish to\naccess the value, we use `lock()` on it. This will \"lock\" the mutex, and no\nother thread will be able to lock it (and hence, do anything with the value)\nuntil we're done with it. If a thread attempts to lock a mutex which is already\nlocked, it will wait until the other thread releases the lock.\n\nThe lock \"release\" here is implicit; when the result of the lock (in this case,\n`data`) goes out of scope, the lock is automatically released.\n\nNote that [`lock`](../std/sync/struct.Mutex.html#method.lock) method of\n[`Mutex`](../std/sync/struct.Mutex.html) has this signature:\n\n```rust,ignore\nfn lock(&self) -> LockResult<MutexGuard<T>>\n```\n\nand because `Send` is not implemented for `MutexGuard<T>`, the guard cannot\ncross thread boundaries, ensuring thread-locality of lock acquire and release.\n\nLet's examine the body of the thread more closely:\n\n```rust\n# use std::sync::{Arc, Mutex};\n# use std::thread;\n# use std::time::Duration;\n# fn main() {\n#     let data = Arc::new(Mutex::new(vec![1, 2, 3]));\n#     for i in 0..3 {\n#         let data = data.clone();\nthread::spawn(move || {\n    let mut data = data.lock().unwrap();\n    data[0] += i;\n});\n#     }\n#     thread::sleep(Duration::from_millis(50));\n# }\n```\n\nFirst, we call `lock()`, which acquires the mutex's lock. Because this may fail,\nit returns a `Result<T, E>`, and because this is just an example, we `unwrap()`\nit to get a reference to the data. Real code would have more robust error handling\nhere. We're then free to mutate it, since we have the lock.\n\nLastly, while the threads are running, we wait on a short timer. But\nthis is not ideal: we may have picked a reasonable amount of time to\nwait but it's more likely we'll either be waiting longer than\nnecessary or not long enough, depending on just how much time the\nthreads actually take to finish computing when the program runs.\n\nA more precise alternative to the timer would be to use one of the\nmechanisms provided by the Rust standard library for synchronizing\nthreads with each other. Let's talk about one of them: channels.\n\n## Channels\n\nHere's a version of our code that uses channels for synchronization, rather\nthan waiting for a specific time:\n\n```rust\nuse std::sync::{Arc, Mutex};\nuse std::thread;\nuse std::sync::mpsc;\n\nfn main() {\n    let data = Arc::new(Mutex::new(0));\n\n    // `tx` is the \"transmitter\" or \"sender\"\n    // `rx` is the \"receiver\"\n    let (tx, rx) = mpsc::channel();\n\n    for _ in 0..10 {\n        let (data, tx) = (data.clone(), tx.clone());\n\n        thread::spawn(move || {\n            let mut data = data.lock().unwrap();\n            *data += 1;\n\n            tx.send(()).unwrap();\n        });\n    }\n\n    for _ in 0..10 {\n        rx.recv().unwrap();\n    }\n}\n```\n\nWe use the `mpsc::channel()` method to construct a new channel. We `send`\na simple `()` down the channel, and then wait for ten of them to come back.\n\nWhile this channel is sending a generic signal, we can send any data that\nis `Send` over the channel!\n\n```rust\nuse std::thread;\nuse std::sync::mpsc;\n\nfn main() {\n    let (tx, rx) = mpsc::channel();\n\n    for i in 0..10 {\n        let tx = tx.clone();\n\n        thread::spawn(move || {\n            let answer = i * i;\n\n            tx.send(answer).unwrap();\n        });\n    }\n\n    for _ in 0..10 {\n        println!(\"{}\", rx.recv().unwrap());\n    }\n}\n```\n\nHere we create 10 threads, asking each to calculate the square of a number (`i`\nat the time of `spawn()`), and then `send()` back the answer over the channel.\n\n\n## Panics\n\nA `panic!` will crash the currently executing thread. You can use Rust's\nthreads as a simple isolation mechanism:\n\n```rust\nuse std::thread;\n\nlet handle = thread::spawn(move || {\n    panic!(\"oops!\");\n});\n\nlet result = handle.join();\n\nassert!(result.is_err());\n```\n\n`Thread.join()` gives us a `Result` back, which allows us to check if the thread\nhas panicked or not.\n"
  },
  {
    "path": "trpl/conditional-compilation.md",
    "content": "% Conditional Compilation\n\nRust has a special attribute, `#[cfg]`, which allows you to compile code\nbased on a flag passed to the compiler. It has two forms:\n\n```rust\n#[cfg(foo)]\n# fn foo() {}\n\n#[cfg(bar = \"baz\")]\n# fn bar() {}\n```\n\nThey also have some helpers:\n\n```rust\n#[cfg(any(unix, windows))]\n# fn foo() {}\n\n#[cfg(all(unix, target_pointer_width = \"32\"))]\n# fn bar() {}\n\n#[cfg(not(foo))]\n# fn not_foo() {}\n```\n\nThese can nest arbitrarily:\n\n```rust\n#[cfg(any(not(unix), all(target_os=\"macos\", target_arch = \"powerpc\")))]\n# fn foo() {}\n```\n\nAs for how to enable or disable these switches, if you’re using Cargo,\nthey get set in the [`[features]` section][features] of your `Cargo.toml`:\n\n[features]: http://doc.crates.io/manifest.html#the-features-section\n\n```toml\n[features]\n# no features by default\ndefault = []\n\n# Add feature \"foo\" here, then you can use it. \n# Our \"foo\" feature depends on nothing else.\nfoo = []\n```\n\nWhen you do this, Cargo passes along a flag to `rustc`:\n\n```text\n--cfg feature=\"${feature_name}\"\n```\n\nThe sum of these `cfg` flags will determine which ones get activated, and\ntherefore, which code gets compiled. Let’s take this code:\n\n```rust\n#[cfg(feature = \"foo\")]\nmod foo {\n}\n```\n\nIf we compile it with `cargo build --features \"foo\"`, it will send the `--cfg\nfeature=\"foo\"` flag to `rustc`, and the output will have the `mod foo` in it.\nIf we compile it with a regular `cargo build`, no extra flags get passed on,\nand so, no `foo` module will exist.\n\n# cfg_attr\n\nYou can also set another attribute based on a `cfg` variable with `cfg_attr`:\n\n```rust\n#[cfg_attr(a, b)]\n# fn foo() {}\n```\n\nWill be the same as `#[b]` if `a` is set by `cfg` attribute, and nothing otherwise.\n\n# cfg!\n\nThe `cfg!` [syntax extension][compilerplugins] lets you use these kinds of flags\nelsewhere in your code, too:\n\n```rust\nif cfg!(target_os = \"macos\") || cfg!(target_os = \"ios\") {\n    println!(\"Think Different!\");\n}\n```\n\n[compilerplugins]: compiler-plugins.html\n\nThese will be replaced by a `true` or `false` at compile-time, depending on the\nconfiguration settings.\n"
  },
  {
    "path": "trpl/const-and-static.md",
    "content": "% `const` and `static`\n\nRust has a way of defining constants with the `const` keyword:\n\n```rust\nconst N: i32 = 5;\n```\n\nUnlike [`let`][let] bindings, you must annotate the type of a `const`.\n\n[let]: variable-bindings.html\n\nConstants live for the entire lifetime of a program. More specifically,\nconstants in Rust have no fixed address in memory. This is because they’re\neffectively inlined to each place that they’re used. References to the same\nconstant are not necessarily guaranteed to refer to the same memory address for\nthis reason.\n\n# `static`\n\nRust provides a ‘global variable’ sort of facility in static items. They’re\nsimilar to constants, but static items aren’t inlined upon use. This means that\nthere is only one instance for each value, and it’s at a fixed location in\nmemory.\n\nHere’s an example:\n\n```rust\nstatic N: i32 = 5;\n```\n\nUnlike [`let`][let] bindings, you must annotate the type of a `static`.\n\nStatics live for the entire lifetime of a program, and therefore any\nreference stored in a constant has a [`'static` lifetime][lifetimes]:\n\n```rust\nstatic NAME: &'static str = \"Steve\";\n```\n\n[lifetimes]: lifetimes.html\n\n## Mutability\n\nYou can introduce mutability with the `mut` keyword:\n\n```rust\nstatic mut N: i32 = 5;\n```\n\nBecause this is mutable, one thread could be updating `N` while another is\nreading it, causing memory unsafety. As such both accessing and mutating a\n`static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block:\n\n```rust\n# static mut N: i32 = 5;\n\nunsafe {\n    N += 1;\n\n    println!(\"N: {}\", N);\n}\n```\n\n[unsafe]: unsafe.html\n\nFurthermore, any type stored in a `static` must be `Sync`, and must not have\na [`Drop`][drop] implementation.\n\n[drop]: drop.html\n\n# Initializing\n\nBoth `const` and `static` have requirements for giving them a value. They must\nbe given a value that’s a constant expression. In other words, you cannot use\nthe result of a function call or anything similarly complex or at runtime.\n\n# Which construct should I use?\n\nAlmost always, if you can choose between the two, choose `const`. It’s pretty\nrare that you actually want a memory location associated with your constant,\nand using a `const` allows for optimizations like constant propagation not only\nin your crate but downstream crates.\n"
  },
  {
    "path": "trpl/crates-and-modules.md",
    "content": "% Crates and Modules\n\nWhen a project starts getting large, it’s considered good software\nengineering practice to split it up into a bunch of smaller pieces, and then\nfit them together. It is also important to have a well-defined interface, so\nthat some of your functionality is private, and some is public. To facilitate\nthese kinds of things, Rust has a module system.\n\n# Basic terminology: Crates and Modules\n\nRust has two distinct terms that relate to the module system: ‘crate’ and\n‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other\nlanguages. Hence “Cargo” as the name of Rust’s package management tool: you\nship your crates to others with Cargo. Crates can produce an executable or a\nlibrary, depending on the project.\n\nEach crate has an implicit *root module* that contains the code for that crate.\nYou can then define a tree of sub-modules under that root module. Modules allow\nyou to partition your code within the crate itself.\n\nAs an example, let’s make a *phrases* crate, which will give us various phrases\nin different languages. To keep things simple, we’ll stick to ‘greetings’ and\n‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as\ntwo languages for those phrases to be in. We’ll use this module layout:\n\n```text\n                                    +-----------+\n                                +---| greetings |\n                  +---------+   |   +-----------+\n              +---| english |---+\n              |   +---------+   |   +-----------+\n              |                 +---| farewells |\n+---------+   |                     +-----------+\n| phrases |---+\n+---------+   |                     +-----------+\n              |                 +---| greetings |\n              |   +----------+  |   +-----------+\n              +---| japanese |--+\n                  +----------+  |   +-----------+\n                                +---| farewells |\n                                    +-----------+\n```\n\nIn this example, `phrases` is the name of our crate. All of the rest are\nmodules.  You can see that they form a tree, branching out from the crate\n*root*, which is the root of the tree: `phrases` itself.\n\nNow that we have a plan, let’s define these modules in code. To start,\ngenerate a new crate with Cargo:\n\n```bash\n$ cargo new phrases\n$ cd phrases\n```\n\nIf you remember, this generates a simple project for us:\n\n```bash\n$ tree .\n.\n├── Cargo.toml\n└── src\n    └── lib.rs\n\n1 directory, 2 files\n```\n\n`src/lib.rs` is our crate root, corresponding to the `phrases` in our diagram\nabove.\n\n# Defining Modules\n\nTo define each of our modules, we use the `mod` keyword. Let’s make our\n`src/lib.rs` look like this:\n\n```rust\nmod english {\n    mod greetings {\n    }\n\n    mod farewells {\n    }\n}\n\nmod japanese {\n    mod greetings {\n    }\n\n    mod farewells {\n    }\n}\n```\n\nAfter the `mod` keyword, you give the name of the module. Module names follow\nthe conventions for other Rust identifiers: `lower_snake_case`. The contents of\neach module are within curly braces (`{}`).\n\nWithin a given `mod`, you can declare sub-`mod`s. We can refer to sub-modules\nwith double-colon (`::`) notation: our four nested modules are\n`english::greetings`, `english::farewells`, `japanese::greetings`, and\n`japanese::farewells`. Because these sub-modules are namespaced under their\nparent module, the names don’t conflict: `english::greetings` and\n`japanese::greetings` are distinct, even though their names are both\n`greetings`.\n\nBecause this crate does not have a `main()` function, and is called `lib.rs`,\nCargo will build this crate as a library:\n\n```bash\n$ cargo build\n   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)\n$ ls target/debug\nbuild  deps  examples  libphrases-a7448e02a0468eaa.rlib  native\n```\n\n`libphrases-<hash>.rlib` is the compiled crate. Before we see how to use this\ncrate from another crate, let’s break it up into multiple files.\n\n# Multiple File Crates\n\nIf each crate were just one file, these files would get very large. It’s often\neasier to split up crates into multiple files, and Rust supports this in two\nways.\n\nInstead of declaring a module like this:\n\n```rust,ignore\nmod english {\n    // contents of our module go here\n}\n```\n\nWe can instead declare our module like this:\n\n```rust,ignore\nmod english;\n```\n\nIf we do that, Rust will expect to find either a `english.rs` file, or a\n`english/mod.rs` file with the contents of our module.\n\nNote that in these files, you don’t need to re-declare the module: that’s\nalready been done with the initial `mod` declaration.\n\nUsing these two techniques, we can break up our crate into two directories and\nseven files:\n\n```bash\n$ tree .\n.\n├── Cargo.lock\n├── Cargo.toml\n├── src\n│   ├── english\n│   │   ├── farewells.rs\n│   │   ├── greetings.rs\n│   │   └── mod.rs\n│   ├── japanese\n│   │   ├── farewells.rs\n│   │   ├── greetings.rs\n│   │   └── mod.rs\n│   └── lib.rs\n└── target\n    └── debug\n        ├── build\n        ├── deps\n        ├── examples\n        ├── libphrases-a7448e02a0468eaa.rlib\n        └── native\n```\n\n`src/lib.rs` is our crate root, and looks like this:\n\n```rust,ignore\nmod english;\nmod japanese;\n```\n\nThese two declarations tell Rust to look for either `src/english.rs` and\n`src/japanese.rs`, or `src/english/mod.rs` and `src/japanese/mod.rs`, depending\non our preference. In this case, because our modules have sub-modules, we’ve\nchosen the second. Both `src/english/mod.rs` and `src/japanese/mod.rs` look\nlike this:\n\n```rust,ignore\nmod greetings;\nmod farewells;\n```\n\nAgain, these declarations tell Rust to look for either\n`src/english/greetings.rs`, `src/english/farewells.rs`,\n`src/japanese/greetings.rs` and `src/japanese/farewells.rs` or\n`src/english/greetings/mod.rs`, `src/english/farewells/mod.rs`,\n`src/japanese/greetings/mod.rs` and\n`src/japanese/farewells/mod.rs`. Because these sub-modules don’t have\ntheir own sub-modules, we’ve chosen to make them\n`src/english/greetings.rs`, `src/english/farewells.rs`,\n`src/japanese/greetings.rs` and `src/japanese/farewells.rs`. Whew!\n\nThe contents of `src/english/greetings.rs`,\n`src/english/farewells.rs`, `src/japanese/greetings.rs` and\n`src/japanese/farewells.rs` are all empty at the moment. Let’s add\nsome functions.\n\nPut this in `src/english/greetings.rs`:\n\n```rust\nfn hello() -> String {\n    \"Hello!\".to_string()\n}\n```\n\nPut this in `src/english/farewells.rs`:\n\n```rust\nfn goodbye() -> String {\n    \"Goodbye.\".to_string()\n}\n```\n\nPut this in `src/japanese/greetings.rs`:\n\n```rust\nfn hello() -> String {\n    \"こんにちは\".to_string()\n}\n```\n\nOf course, you can copy and paste this from this web page, or type\nsomething else. It’s not important that you actually put ‘konnichiwa’ to learn\nabout the module system.\n\nPut this in `src/japanese/farewells.rs`:\n\n```rust\nfn goodbye() -> String {\n    \"さようなら\".to_string()\n}\n```\n\n(This is ‘Sayōnara’, if you’re curious.)\n\nNow that we have some functionality in our crate, let’s try to use it from\nanother crate.\n\n# Importing External Crates\n\nWe have a library crate. Let’s make an executable crate that imports and uses\nour library.\n\nMake a `src/main.rs` and put this in it (it won’t quite compile yet):\n\n```rust,ignore\nextern crate phrases;\n\nfn main() {\n    println!(\"Hello in English: {}\", phrases::english::greetings::hello());\n    println!(\"Goodbye in English: {}\", phrases::english::farewells::goodbye());\n\n    println!(\"Hello in Japanese: {}\", phrases::japanese::greetings::hello());\n    println!(\"Goodbye in Japanese: {}\", phrases::japanese::farewells::goodbye());\n}\n```\n\nThe `extern crate` declaration tells Rust that we need to compile and link to\nthe `phrases` crate. We can then use `phrases`’ modules in this one. As we\nmentioned earlier, you can use double colons to refer to sub-modules and the\nfunctions inside of them.\n\n(Note: when importing a crate that has dashes in its name \"like-this\", which is\nnot a valid Rust identifier, it will be converted by changing the dashes to\nunderscores, so you would write `extern crate like_this;`.)\n\nAlso, Cargo assumes that `src/main.rs` is the crate root of a binary crate,\nrather than a library crate. Our package now has two crates: `src/lib.rs` and\n`src/main.rs`. This pattern is quite common for executable crates: most\nfunctionality is in a library crate, and the executable crate uses that\nlibrary. This way, other programs can also use the library crate, and it’s also\na nice separation of concerns.\n\nThis doesn’t quite work yet, though. We get four errors that look similar to\nthis:\n\n```bash\n$ cargo build\n   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)\nsrc/main.rs:4:38: 4:72 error: function `hello` is private\nsrc/main.rs:4     println!(\"Hello in English: {}\", phrases::english::greetings::hello());\n                                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nnote: in expansion of format_args!\n<std macros>:2:25: 2:58 note: expansion site\n<std macros>:1:1: 2:62 note: in expansion of print!\n<std macros>:3:1: 3:54 note: expansion site\n<std macros>:1:1: 3:58 note: in expansion of println!\nphrases/src/main.rs:4:5: 4:76 note: expansion site\n```\n\nBy default, everything is private in Rust. Let’s talk about this in some more\ndepth.\n\n# Exporting a Public Interface\n\nRust allows you to precisely control which aspects of your interface are\npublic, and so private is the default. To make things public, you use the `pub`\nkeyword. Let’s focus on the `english` module first, so let’s reduce our `src/main.rs`\nto only this:\n\n```rust,ignore\nextern crate phrases;\n\nfn main() {\n    println!(\"Hello in English: {}\", phrases::english::greetings::hello());\n    println!(\"Goodbye in English: {}\", phrases::english::farewells::goodbye());\n}\n```\n\nIn our `src/lib.rs`, let’s add `pub` to the `english` module declaration:\n\n```rust,ignore\npub mod english;\nmod japanese;\n```\n\nAnd in our `src/english/mod.rs`, let’s make both `pub`:\n\n```rust,ignore\npub mod greetings;\npub mod farewells;\n```\n\nIn our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration:\n\n```rust,ignore\npub fn hello() -> String {\n    \"Hello!\".to_string()\n}\n```\n\nAnd also in `src/english/farewells.rs`:\n\n```rust,ignore\npub fn goodbye() -> String {\n    \"Goodbye.\".to_string()\n}\n```\n\nNow, our crate compiles, albeit with warnings about not using the `japanese`\nfunctions:\n\n```bash\n$ cargo run\n   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)\nsrc/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default\nsrc/japanese/greetings.rs:1 fn hello() -> String {\nsrc/japanese/greetings.rs:2     \"こんにちは\".to_string()\nsrc/japanese/greetings.rs:3 }\nsrc/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default\nsrc/japanese/farewells.rs:1 fn goodbye() -> String {\nsrc/japanese/farewells.rs:2     \"さようなら\".to_string()\nsrc/japanese/farewells.rs:3 }\n     Running `target/debug/phrases`\nHello in English: Hello!\nGoodbye in English: Goodbye.\n```\n\n`pub` also applies to `struct`s and their member fields. In keeping with Rust’s\ntendency toward safety, simply making a `struct` public won't automatically\nmake its members public: you must mark the fields individually with `pub`.\n\nNow that our functions are public, we can use them. Great! However, typing out\n`phrases::english::greetings::hello()` is very long and repetitive. Rust has\nanother keyword for importing names into the current scope, so that you can\nrefer to them with shorter names. Let’s talk about `use`.\n\n# Importing Modules with `use`\n\nRust has a `use` keyword, which allows us to import names into our local scope.\nLet’s change our `src/main.rs` to look like this:\n\n```rust,ignore\nextern crate phrases;\n\nuse phrases::english::greetings;\nuse phrases::english::farewells;\n\nfn main() {\n    println!(\"Hello in English: {}\", greetings::hello());\n    println!(\"Goodbye in English: {}\", farewells::goodbye());\n}\n```\n\nThe two `use` lines import each module into the local scope, so we can refer to\nthe functions by a much shorter name. By convention, when importing functions, it’s\nconsidered best practice to import the module, rather than the function directly. In\nother words, you _can_ do this:\n\n```rust,ignore\nextern crate phrases;\n\nuse phrases::english::greetings::hello;\nuse phrases::english::farewells::goodbye;\n\nfn main() {\n    println!(\"Hello in English: {}\", hello());\n    println!(\"Goodbye in English: {}\", goodbye());\n}\n```\n\nBut it is not idiomatic. This is significantly more likely to introduce a\nnaming conflict. In our short program, it’s not a big deal, but as it grows, it\nbecomes a problem. If we have conflicting names, Rust will give a compilation\nerror. For example, if we made the `japanese` functions public, and tried to do\nthis:\n\n```rust,ignore\nextern crate phrases;\n\nuse phrases::english::greetings::hello;\nuse phrases::japanese::greetings::hello;\n\nfn main() {\n    println!(\"Hello in English: {}\", hello());\n    println!(\"Hello in Japanese: {}\", hello());\n}\n```\n\nRust will give us a compile-time error:\n\n```text\n   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)\nsrc/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252]\nsrc/main.rs:4 use phrases::japanese::greetings::hello;\n                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nerror: aborting due to previous error\nCould not compile `phrases`.\n```\n\nIf we’re importing multiple names from the same module, we don’t have to type it out\ntwice. Instead of this:\n\n```rust,ignore\nuse phrases::english::greetings;\nuse phrases::english::farewells;\n```\n\nWe can use this shortcut:\n\n```rust,ignore\nuse phrases::english::{greetings, farewells};\n```\n\n## Re-exporting with `pub use`\n\nYou don’t only use `use` to shorten identifiers. You can also use it inside of your crate\nto re-export a function inside another module. This allows you to present an external\ninterface that may not directly map to your internal code organization.\n\nLet’s look at an example. Modify your `src/main.rs` to read like this:\n\n```rust,ignore\nextern crate phrases;\n\nuse phrases::english::{greetings,farewells};\nuse phrases::japanese;\n\nfn main() {\n    println!(\"Hello in English: {}\", greetings::hello());\n    println!(\"Goodbye in English: {}\", farewells::goodbye());\n\n    println!(\"Hello in Japanese: {}\", japanese::hello());\n    println!(\"Goodbye in Japanese: {}\", japanese::goodbye());\n}\n```\n\nThen, modify your `src/lib.rs` to make the `japanese` mod public:\n\n```rust,ignore\npub mod english;\npub mod japanese;\n```\n\nNext, make the two functions public, first in `src/japanese/greetings.rs`:\n\n```rust,ignore\npub fn hello() -> String {\n    \"こんにちは\".to_string()\n}\n```\n\nAnd then in `src/japanese/farewells.rs`:\n\n```rust,ignore\npub fn goodbye() -> String {\n    \"さようなら\".to_string()\n}\n```\n\nFinally, modify your `src/japanese/mod.rs` to read like this:\n\n```rust,ignore\npub use self::greetings::hello;\npub use self::farewells::goodbye;\n\nmod greetings;\nmod farewells;\n```\n\nThe `pub use` declaration brings the function into scope at this part of our\nmodule hierarchy. Because we’ve `pub use`d this inside of our `japanese`\nmodule, we now have a `phrases::japanese::hello()` function and a\n`phrases::japanese::goodbye()` function, even though the code for them lives in\n`phrases::japanese::greetings::hello()` and\n`phrases::japanese::farewells::goodbye()`. Our internal organization doesn’t\ndefine our external interface.\n\nHere we have a `pub use` for each function we want to bring into the\n`japanese` scope. We could alternatively use the wildcard syntax to include\neverything from `greetings` into the current scope: `pub use self::greetings::*`.\n\nWhat about the `self`? Well, by default, `use` declarations are absolute paths,\nstarting from your crate root. `self` makes that path relative to your current\nplace in the hierarchy instead. There’s one more special form of `use`: you can\n`use super::` to reach one level up the tree from your current location. Some\npeople like to think of `self` as `.` and `super` as `..`, from many shells’\ndisplay for the current directory and the parent directory.\n\nOutside of `use`, paths are relative: `foo::bar()` refers to a function inside\nof `foo` relative to where we are. If that’s prefixed with `::`, as in\n`::foo::bar()`, it refers to a different `foo`, an absolute path from your\ncrate root.\n\nThis will build and run:\n\n```bash\n$ cargo run\n   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)\n     Running `target/debug/phrases`\nHello in English: Hello!\nGoodbye in English: Goodbye.\nHello in Japanese: こんにちは\nGoodbye in Japanese: さようなら\n```\n\n## Complex imports\n\nRust offers several advanced options that can add compactness and\nconvenience to your `extern crate` and `use` statements. Here is an example:\n\n```rust,ignore\nextern crate phrases as sayings;\n\nuse sayings::japanese::greetings as ja_greetings;\nuse sayings::japanese::farewells::*;\nuse sayings::english::{self, greetings as en_greetings, farewells as en_farewells};\n\nfn main() {\n    println!(\"Hello in English; {}\", en_greetings::hello());\n    println!(\"And in Japanese: {}\", ja_greetings::hello());\n    println!(\"Goodbye in English: {}\", english::farewells::goodbye());\n    println!(\"Again: {}\", en_farewells::goodbye());\n    println!(\"And in Japanese: {}\", goodbye());\n}\n```\n\nWhat's going on here?\n\nFirst, both `extern crate` and `use` allow renaming the thing that is being\nimported. So the crate is still called \"phrases\", but here we will refer\nto it as \"sayings\". Similarly, the first `use` statement pulls in the\n`japanese::greetings` module from the crate, but makes it available as\n`ja_greetings` as opposed to simply `greetings`. This can help to avoid\nambiguity when importing similarly-named items from different places.\n\nThe second `use` statement uses a star glob to bring in all public symbols from\nthe `sayings::japanese::farewells` module. As you can see we can later refer to\nthe Japanese `goodbye` function with no module qualifiers. This kind of glob\nshould be used sparingly. It’s worth noting that it only imports the public\nsymbols, even if the code doing the globbing is in the same module.\n\nThe third `use` statement bears more explanation. It's using \"brace expansion\"\nglobbing to compress three `use` statements into one (this sort of syntax\nmay be familiar if you've written Linux shell scripts before). The\nuncompressed form of this statement would be:\n\n```rust,ignore\nuse sayings::english;\nuse sayings::english::greetings as en_greetings;\nuse sayings::english::farewells as en_farewells;\n```\n\nAs you can see, the curly brackets compress `use` statements for several items\nunder the same path, and in this context `self` refers back to that path.\nNote: The curly brackets cannot be nested or mixed with star globbing.\n"
  },
  {
    "path": "trpl/custom-allocators.md",
    "content": "% Custom Allocators\n\nAllocating memory isn't always the easiest thing to do, and while Rust generally\ntakes care of this by default it often becomes necessary to customize how\nallocation occurs. The compiler and standard library currently allow switching\nout the default global allocator in use at compile time. The design is currently\nspelled out in [RFC 1183][rfc] but this will walk you through how to get your\nown allocator up and running.\n\n[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1183-swap-out-jemalloc.md\n\n# Default Allocator\n\nThe compiler currently ships two default allocators: `alloc_system` and\n`alloc_jemalloc` (some targets don't have jemalloc, however). These allocators\nare normal Rust crates and contain an implementation of the routines to\nallocate and deallocate memory. The standard library is not compiled assuming\neither one, and the compiler will decide which allocator is in use at\ncompile-time depending on the type of output artifact being produced.\n\nBinaries generated by the compiler will use `alloc_jemalloc` by default (where\navailable). In this situation the compiler \"controls the world\" in the sense of\nit has power over the final link. Primarily this means that the allocator\ndecision can be left up the compiler.\n\nDynamic and static libraries, however, will use `alloc_system` by default. Here\nRust is typically a 'guest' in another application or another world where it\ncannot authoritatively decide what allocator is in use. As a result it resorts\nback to the standard APIs (e.g. `malloc` and `free`) for acquiring and releasing\nmemory.\n\n# Switching Allocators\n\nAlthough the compiler's default choices may work most of the time, it's often\nnecessary to tweak certain aspects. Overriding the compiler's decision about\nwhich allocator is in use is done simply by linking to the desired allocator:\n\n```rust,no_run\n#![feature(alloc_system)]\n\nextern crate alloc_system;\n\nfn main() {\n    let a = Box::new(4); // allocates from the system allocator\n    println!(\"{}\", a);\n}\n```\n\nIn this example the binary generated will not link to jemalloc by default but\ninstead use the system allocator. Conversely to generate a dynamic library which\nuses jemalloc by default one would write:\n\n```rust,ignore\n#![feature(alloc_jemalloc)]\n#![crate_type = \"dylib\"]\n\nextern crate alloc_jemalloc;\n\npub fn foo() {\n    let a = Box::new(4); // allocates from jemalloc\n    println!(\"{}\", a);\n}\n# fn main() {}\n```\n\n# Writing a custom allocator\n\nSometimes even the choices of jemalloc vs the system allocator aren't enough and\nan entirely new custom allocator is required. In this you'll write your own\ncrate which implements the allocator API (e.g. the same as `alloc_system` or\n`alloc_jemalloc`). As an example, let's take a look at a simplified and\nannotated version of `alloc_system`\n\n```rust,no_run\n# // only needed for rustdoc --test down below\n# #![feature(lang_items)]\n// The compiler needs to be instructed that this crate is an allocator in order\n// to realize that when this is linked in another allocator like jemalloc should\n// not be linked in\n#![feature(allocator)]\n#![allocator]\n\n// Allocators are not allowed to depend on the standard library which in turn\n// requires an allocator in order to avoid circular dependencies. This crate,\n// however, can use all of libcore.\n#![no_std]\n\n// Let's give a unique name to our custom allocator\n#![crate_name = \"my_allocator\"]\n#![crate_type = \"rlib\"]\n\n// Our system allocator will use the in-tree libc crate for FFI bindings. Note\n// that currently the external (crates.io) libc cannot be used because it links\n// to the standard library (e.g. `#![no_std]` isn't stable yet), so that's why\n// this specifically requires the in-tree version.\n#![feature(libc)]\nextern crate libc;\n\n// Listed below are the five allocation functions currently required by custom\n// allocators. Their signatures and symbol names are not currently typechecked\n// by the compiler, but this is a future extension and are required to match\n// what is found below.\n//\n// Note that the standard `malloc` and `realloc` functions do not provide a way\n// to communicate alignment so this implementation would need to be improved\n// with respect to alignment in that aspect.\n\n#[no_mangle]\npub extern fn __rust_allocate(size: usize, _align: usize) -> *mut u8 {\n    unsafe { libc::malloc(size as libc::size_t) as *mut u8 }\n}\n\n#[no_mangle]\npub extern fn __rust_deallocate(ptr: *mut u8, _old_size: usize, _align: usize) {\n    unsafe { libc::free(ptr as *mut libc::c_void) }\n}\n\n#[no_mangle]\npub extern fn __rust_reallocate(ptr: *mut u8, _old_size: usize, size: usize,\n                                _align: usize) -> *mut u8 {\n    unsafe {\n        libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8\n    }\n}\n\n#[no_mangle]\npub extern fn __rust_reallocate_inplace(_ptr: *mut u8, old_size: usize,\n                                        _size: usize, _align: usize) -> usize {\n    old_size // this api is not supported by libc\n}\n\n#[no_mangle]\npub extern fn __rust_usable_size(size: usize, _align: usize) -> usize {\n    size\n}\n\n# // only needed to get rustdoc to test this\n# fn main() {}\n# #[lang = \"panic_fmt\"] fn panic_fmt() {}\n# #[lang = \"eh_personality\"] fn eh_personality() {}\n# #[lang = \"eh_unwind_resume\"] extern fn eh_unwind_resume() {}\n# #[no_mangle] pub extern fn rust_eh_register_frames () {}\n# #[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nAfter we compile this crate, it can be used as follows:\n\n```rust,ignore\nextern crate my_allocator;\n\nfn main() {\n    let a = Box::new(8); // allocates memory via our custom allocator crate\n    println!(\"{}\", a);\n}\n```\n\n# Custom allocator limitations\n\nThere are a few restrictions when working with custom allocators which may cause\ncompiler errors:\n\n* Any one artifact may only be linked to at most one allocator. Binaries,\n  dylibs, and staticlibs must link to exactly one allocator, and if none have\n  been explicitly chosen the compiler will choose one. On the other hand rlibs\n  do not need to link to an allocator (but still can).\n\n* A consumer of an allocator is tagged with `#![needs_allocator]` (e.g. the\n  `liballoc` crate currently) and an `#[allocator]` crate cannot transitively\n  depend on a crate which needs an allocator (e.g. circular dependencies are not\n  allowed). This basically means that allocators must restrict themselves to\n  libcore currently.\n"
  },
  {
    "path": "trpl/deref-coercions.md",
    "content": "% `Deref` coercions\n\nThe standard library provides a special trait, [`Deref`][deref]. It’s normally\nused to overload `*`, the dereference operator:\n\n```rust\nuse std::ops::Deref;\n\nstruct DerefExample<T> {\n    value: T,\n}\n\nimpl<T> Deref for DerefExample<T> {\n    type Target = T;\n\n    fn deref(&self) -> &T {\n        &self.value\n    }\n}\n\nfn main() {\n    let x = DerefExample { value: 'a' };\n    assert_eq!('a', *x);\n}\n```\n\n[deref]: ../std/ops/trait.Deref.html\n\nThis is useful for writing custom pointer types. However, there’s a language\nfeature related to `Deref`: ‘deref coercions’. Here’s the rule: If you have a\ntype `U`, and it implements `Deref<Target=T>`, values of `&U` will\nautomatically coerce to a `&T`. Here’s an example:\n\n```rust\nfn foo(s: &str) {\n    // borrow a string for a second\n}\n\n// String implements Deref<Target=str>\nlet owned = \"Hello\".to_string();\n\n// therefore, this works:\nfoo(&owned);\n```\n\nUsing an ampersand in front of a value takes a reference to it. So `owned` is a\n`String`, `&owned` is an `&String`, and since `impl Deref<Target=str> for\nString`, `&String` will deref to `&str`, which `foo()` takes.\n\nThat’s it. This rule is one of the only places in which Rust does an automatic\nconversion for you, but it adds a lot of flexibility. For example, the `Rc<T>`\ntype implements `Deref<Target=T>`, so this works:\n\n```rust\nuse std::rc::Rc;\n\nfn foo(s: &str) {\n    // borrow a string for a second\n}\n\n// String implements Deref<Target=str>\nlet owned = \"Hello\".to_string();\nlet counted = Rc::new(owned);\n\n// therefore, this works:\nfoo(&counted);\n```\n\nAll we’ve done is wrap our `String` in an `Rc<T>`. But we can now pass the\n`Rc<String>` around anywhere we’d have a `String`. The signature of `foo`\ndidn’t change, but works just as well with either type. This example has two\nconversions: `Rc<String>` to `String` and then `String` to `&str`. Rust will do\nthis as many times as possible until the types match.\n\nAnother very common implementation provided by the standard library is:\n\n```rust\nfn foo(s: &[i32]) {\n    // borrow a slice for a second\n}\n\n// Vec<T> implements Deref<Target=[T]>\nlet owned = vec![1, 2, 3];\n\nfoo(&owned);\n```\n\nVectors can `Deref` to a slice.\n\n## Deref and method calls\n\n`Deref` will also kick in when calling a method. Consider the following\nexample.\n\n```rust\nstruct Foo;\n\nimpl Foo {\n    fn foo(&self) { println!(\"Foo\"); }\n}\n\nlet f = &&Foo;\n\nf.foo();\n```\n\nEven though `f` is a `&&Foo` and `foo` takes `&self`, this works. That’s\nbecause these things are the same:\n\n```rust,ignore\nf.foo();\n(&f).foo();\n(&&f).foo();\n(&&&&&&&&f).foo();\n```\n\nA value of type `&&&&&&&&&&&&&&&&Foo` can still have methods defined on `Foo`\ncalled, because the compiler will insert as many * operations as necessary to\nget it right. And since it’s inserting `*`s, that uses `Deref`.\n"
  },
  {
    "path": "trpl/documentation.md",
    "content": "% Documentation\n\nDocumentation is an important part of any software project, and it's\nfirst-class in Rust. Let's talk about the tooling Rust gives you to\ndocument your project.\n\n## About `rustdoc`\n\nThe Rust distribution includes a tool, `rustdoc`, that generates documentation.\n`rustdoc` is also used by Cargo through `cargo doc`.\n\nDocumentation can be generated in two ways: from source code, and from\nstandalone Markdown files.\n\n## Documenting source code\n\nThe primary way of documenting a Rust project is through annotating the source\ncode. You can use documentation comments for this purpose:\n\n```rust,ignore\n/// Constructs a new `Rc<T>`.\n///\n/// # Examples\n///\n/// ```\n/// use std::rc::Rc;\n///\n/// let five = Rc::new(5);\n/// ```\npub fn new(value: T) -> Rc<T> {\n    // implementation goes here\n}\n```\n\nThis code generates documentation that looks [like this][rc-new]. I've left the\nimplementation out, with a regular comment in its place.\n\nThe first thing to notice about this annotation is that it uses\n`///` instead of `//`. The triple slash\nindicates a documentation comment.\n\nDocumentation comments are written in Markdown.\n\nRust keeps track of these comments, and uses them when generating\ndocumentation. This is important when documenting things like enums:\n\n```rust\n/// The `Option` type. See [the module level documentation](index.html) for more.\nenum Option<T> {\n    /// No value\n    None,\n    /// Some value `T`\n    Some(T),\n}\n```\n\nThe above works, but this does not:\n\n```rust,ignore\n/// The `Option` type. See [the module level documentation](index.html) for more.\nenum Option<T> {\n    None, /// No value\n    Some(T), /// Some value `T`\n}\n```\n\nYou'll get an error:\n\n```text\nhello.rs:4:1: 4:2 error: expected ident, found `}`\nhello.rs:4 }\n           ^\n```\n\nThis [unfortunate error](https://github.com/rust-lang/rust/issues/22547) is\ncorrect; documentation comments apply to the thing after them, and there's\nnothing after that last comment.\n\n[rc-new]: ../std/rc/struct.Rc.html#method.new\n\n### Writing documentation comments\n\nAnyway, let's cover each part of this comment in detail:\n\n```rust\n/// Constructs a new `Rc<T>`.\n# fn foo() {}\n```\n\nThe first line of a documentation comment should be a short summary of its\nfunctionality. One sentence. Just the basics. High level.\n\n```rust\n///\n/// Other details about constructing `Rc<T>`s, maybe describing complicated\n/// semantics, maybe additional options, all kinds of stuff.\n///\n# fn foo() {}\n```\n\nOur original example had just a summary line, but if we had more things to say,\nwe could have added more explanation in a new paragraph.\n\n#### Special sections\n\nNext, are special sections. These are indicated with a header, `#`. There\nare four kinds of headers that are commonly used. They aren't special syntax,\njust convention, for now.\n\n```rust\n/// # Panics\n# fn foo() {}\n```\n\nUnrecoverable misuses of a function (i.e. programming errors) in Rust are\nusually indicated by panics, which kill the whole current thread at the very\nleast. If your function has a non-trivial contract like this, that is\ndetected/enforced by panics, documenting it is very important.\n\n```rust\n/// # Errors\n# fn foo() {}\n```\n\nIf your function or method returns a `Result<T, E>`, then describing the\nconditions under which it returns `Err(E)` is a nice thing to do. This is\nslightly less important than `Panics`, because failure is encoded into the type\nsystem, but it's still a good thing to do.\n\n```rust\n/// # Safety\n# fn foo() {}\n```\n\nIf your function is `unsafe`, you should explain which invariants the caller is\nresponsible for upholding.\n\n```rust\n/// # Examples\n///\n/// ```\n/// use std::rc::Rc;\n///\n/// let five = Rc::new(5);\n/// ```\n# fn foo() {}\n```\n\nFourth, `Examples`. Include one or more examples of using your function or\nmethod, and your users will love you for it. These examples go inside of\ncode block annotations, which we'll talk about in a moment, and can have\nmore than one section:\n\n```rust\n/// # Examples\n///\n/// Simple `&str` patterns:\n///\n/// ```\n/// let v: Vec<&str> = \"Mary had a little lamb\".split(' ').collect();\n/// assert_eq!(v, vec![\"Mary\", \"had\", \"a\", \"little\", \"lamb\"]);\n/// ```\n///\n/// More complex patterns with a lambda:\n///\n/// ```\n/// let v: Vec<&str> = \"abc1def2ghi\".split(|c: char| c.is_numeric()).collect();\n/// assert_eq!(v, vec![\"abc\", \"def\", \"ghi\"]);\n/// ```\n# fn foo() {}\n```\n\nLet's discuss the details of these code blocks.\n\n#### Code block annotations\n\nTo write some Rust code in a comment, use the triple graves:\n\n```rust\n/// ```\n/// println!(\"Hello, world\");\n/// ```\n# fn foo() {}\n```\n\nIf you want something that's not Rust code, you can add an annotation:\n\n```rust\n/// ```c\n/// printf(\"Hello, world\\n\");\n/// ```\n# fn foo() {}\n```\n\nThis will highlight according to whatever language you're showing off.\nIf you're only showing plain text, choose `text`.\n\nIt's important to choose the correct annotation here, because `rustdoc` uses it\nin an interesting way: It can be used to actually test your examples in a\nlibrary crate, so that they don't get out of date. If you have some C code but\n`rustdoc` thinks it's Rust because you left off the annotation, `rustdoc` will\ncomplain when trying to generate the documentation.\n\n## Documentation as tests\n\nLet's discuss our sample example documentation:\n\n```rust\n/// ```\n/// println!(\"Hello, world\");\n/// ```\n# fn foo() {}\n```\n\nYou'll notice that you don't need a `fn main()` or anything here. `rustdoc` will\nautomatically add a `main()` wrapper around your code, using heuristics to attempt\nto put it in the right place. For example:\n\n```rust\n/// ```\n/// use std::rc::Rc;\n///\n/// let five = Rc::new(5);\n/// ```\n# fn foo() {}\n```\n\nThis will end up testing:\n\n```rust\nfn main() {\n    use std::rc::Rc;\n    let five = Rc::new(5);\n}\n```\n\nHere's the full algorithm rustdoc uses to preprocess examples:\n\n1. Any leading `#![foo]` attributes are left intact as crate attributes.\n2. Some common `allow` attributes are inserted, including\n   `unused_variables`, `unused_assignments`, `unused_mut`,\n   `unused_attributes`, and `dead_code`. Small examples often trigger\n   these lints.\n3. If the example does not contain `extern crate`, then `extern crate\n   <mycrate>;` is inserted (note the lack of `#[macro_use]`).\n4. Finally, if the example does not contain `fn main`, the remainder of the\n   text is wrapped in `fn main() { your_code }`.\n\nThis generated `fn main` can be a problem! If you have `extern crate` or a `mod`\nstatements in the example code that are referred to by `use` statements, they will\nfail to resolve unless you include at least `fn main() {}` to inhibit step 4.\n`#[macro_use] extern crate` also does not work except at the crate root, so when\ntesting macros an explicit `main` is always required. It doesn't have to clutter\nup your docs, though -- keep reading!\n\nSometimes this algorithm isn't enough, though. For example, all of these code samples\nwith `///` we've been talking about? The raw text:\n\n```text\n/// Some documentation.\n# fn foo() {}\n```\n\nlooks different than the output:\n\n```rust\n/// Some documentation.\n# fn foo() {}\n```\n\nYes, that's right: you can add lines that start with `# `, and they will\nbe hidden from the output, but will be used when compiling your code. You\ncan use this to your advantage. In this case, documentation comments need\nto apply to some kind of function, so if I want to show you just a\ndocumentation comment, I need to add a little function definition below\nit. At the same time, it's only there to satisfy the compiler, so hiding\nit makes the example more clear. You can use this technique to explain\nlonger examples in detail, while still preserving the testability of your\ndocumentation.\n\nFor example, imagine that we wanted to document this code:\n\n```rust\nlet x = 5;\nlet y = 6;\nprintln!(\"{}\", x + y);\n```\n\nWe might want the documentation to end up looking like this:\n\n> First, we set `x` to five:\n>\n> ```rust\n> let x = 5;\n> # let y = 6;\n> # println!(\"{}\", x + y);\n> ```\n>\n> Next, we set `y` to six:\n>\n> ```rust\n> # let x = 5;\n> let y = 6;\n> # println!(\"{}\", x + y);\n> ```\n>\n> Finally, we print the sum of `x` and `y`:\n>\n> ```rust\n> # let x = 5;\n> # let y = 6;\n> println!(\"{}\", x + y);\n> ```\n\nTo keep each code block testable, we want the whole program in each block, but\nwe don't want the reader to see every line every time.  Here's what we put in\nour source code:\n\n```text\n    First, we set `x` to five:\n\n    ```rust\n    let x = 5;\n    # let y = 6;\n    # println!(\"{}\", x + y);\n    ```\n\n    Next, we set `y` to six:\n\n    ```rust\n    # let x = 5;\n    let y = 6;\n    # println!(\"{}\", x + y);\n    ```\n\n    Finally, we print the sum of `x` and `y`:\n\n    ```rust\n    # let x = 5;\n    # let y = 6;\n    println!(\"{}\", x + y);\n    ```\n```\n\nBy repeating all parts of the example, you can ensure that your example still\ncompiles, while only showing the parts that are relevant to that part of your\nexplanation.\n\n### Documenting macros\n\nHere’s an example of documenting a macro:\n\n```rust\n/// Panic with a given message unless an expression evaluates to true.\n///\n/// # Examples\n///\n/// ```\n/// # #[macro_use] extern crate foo;\n/// # fn main() {\n/// panic_unless!(1 + 1 == 2, “Math is broken.”);\n/// # }\n/// ```\n///\n/// ```rust,should_panic\n/// # #[macro_use] extern crate foo;\n/// # fn main() {\n/// panic_unless!(true == false, “I’m broken.”);\n/// # }\n/// ```\n#[macro_export]\nmacro_rules! panic_unless {\n    ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });\n}\n# fn main() {}\n```\n\nYou’ll note three things: we need to add our own `extern crate` line, so that\nwe can add the `#[macro_use]` attribute. Second, we’ll need to add our own\n`main()` as well (for reasons discussed above). Finally, a judicious use of\n`#` to comment out those two things, so they don’t show up in the output.\n\nAnother case where the use of `#` is handy is when you want to ignore\nerror handling. Lets say you want the following,\n\n```rust,ignore\n/// use std::io;\n/// let mut input = String::new();\n/// try!(io::stdin().read_line(&mut input));\n```\n\nThe problem is that `try!` returns a `Result<T, E>` and test functions\ndon't return anything so this will give a mismatched types error.\n\n```rust,ignore\n/// A doc test using try!\n///\n/// ```\n/// use std::io;\n/// # fn foo() -> io::Result<()> {\n/// let mut input = String::new();\n/// try!(io::stdin().read_line(&mut input));\n/// # Ok(())\n/// # }\n/// ```\n# fn foo() {}\n```\n\nYou can get around this by wrapping the code in a function. This catches\nand swallows the `Result<T, E>` when running tests on the docs. This\npattern appears regularly in the standard library.\n\n### Running documentation tests\n\nTo run the tests, either:\n\n```bash\n$ rustdoc --test path/to/my/crate/root.rs\n# or\n$ cargo test\n```\n\nThat's right, `cargo test` tests embedded documentation too. **However,\n`cargo test` will not test binary crates, only library ones.** This is\ndue to the way `rustdoc` works: it links against the library to be tested,\nbut with a binary, there’s nothing to link to.\n\nThere are a few more annotations that are useful to help `rustdoc` do the right\nthing when testing your code:\n\n```rust\n/// ```rust,ignore\n/// fn foo() {\n/// ```\n# fn foo() {}\n```\n\nThe `ignore` directive tells Rust to ignore your code. This is almost never\nwhat you want, as it's the most generic. Instead, consider annotating it\nwith `text` if it's not code, or using `#`s to get a working example that\nonly shows the part you care about.\n\n```rust\n/// ```rust,should_panic\n/// assert!(false);\n/// ```\n# fn foo() {}\n```\n\n`should_panic` tells `rustdoc` that the code should compile correctly, but\nnot actually pass as a test.\n\n```rust\n/// ```rust,no_run\n/// loop {\n///     println!(\"Hello, world\");\n/// }\n/// ```\n# fn foo() {}\n```\n\nThe `no_run` attribute will compile your code, but not run it. This is\nimportant for examples such as \"Here's how to start up a network service,\"\nwhich you would want to make sure compile, but might run in an infinite loop!\n\n### Documenting modules\n\nRust has another kind of doc comment, `//!`. This comment doesn't document the next item, but the enclosing item. In other words:\n\n```rust\nmod foo {\n    //! This is documentation for the `foo` module.\n    //!\n    //! # Examples\n\n    // ...\n}\n```\n\nThis is where you'll see `//!` used most often: for module documentation. If\nyou have a module in `foo.rs`, you'll often open its code and see this:\n\n```rust\n//! A module for using `foo`s.\n//!\n//! The `foo` module contains a lot of useful functionality blah blah blah\n```\n\n### Crate documentation\n\nCrates can be documented by placing an inner doc comment (`//!`) at the\nbeginning of the crate root, aka `lib.rs`:\n\n```rust\n//! This is documentation for the `foo` crate.\n//!\n//! The foo crate is meant to be used for bar.\n```\n\n### Documentation comment style\n\nCheck out [RFC 505][rfc505] for full conventions around the style and format of\ndocumentation.\n\n[rfc505]: https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md\n\n## Other documentation\n\nAll of this behavior works in non-Rust source files too. Because comments\nare written in Markdown, they're often `.md` files.\n\nWhen you write documentation in Markdown files, you don't need to prefix\nthe documentation with comments. For example:\n\n```rust\n/// # Examples\n///\n/// ```\n/// use std::rc::Rc;\n///\n/// let five = Rc::new(5);\n/// ```\n# fn foo() {}\n```\n\nis:\n\n~~~markdown\n# Examples\n\n```\nuse std::rc::Rc;\n\nlet five = Rc::new(5);\n```\n~~~\n\nwhen it's in a Markdown file. There is one wrinkle though: Markdown files need\nto have a title like this:\n\n```markdown\n% The title\n\nThis is the example documentation.\n```\n\nThis `%` line needs to be the very first line of the file.\n\n## `doc` attributes\n\nAt a deeper level, documentation comments are syntactic sugar for documentation\nattributes:\n\n```rust\n/// this\n# fn foo() {}\n\n#[doc=\"this\"]\n# fn bar() {}\n```\n\nare the same, as are these:\n\n```rust\n//! this\n\n#![doc=\"this\"]\n```\n\nYou won't often see this attribute used for writing documentation, but it\ncan be useful when changing some options, or when writing a macro.\n\n### Re-exports\n\n`rustdoc` will show the documentation for a public re-export in both places:\n\n```rust,ignore\nextern crate foo;\n\npub use foo::bar;\n```\n\nThis will create documentation for `bar` both inside the documentation for the\ncrate `foo`, as well as the documentation for your crate. It will use the same\ndocumentation in both places.\n\nThis behavior can be suppressed with `no_inline`:\n\n```rust,ignore\nextern crate foo;\n\n#[doc(no_inline)]\npub use foo::bar;\n```\n\n## Missing documentation\n\nSometimes you want to make sure that every single public thing in your project\nis documented, especially when you are working on a library. Rust allows you to\nto generate warnings or errors, when an item is missing documentation.\nTo generate warnings you use `warn`:\n\n```rust\n#![warn(missing_docs)]\n```\n\nAnd to generate errors you use `deny`:\n\n```rust,ignore\n#![deny(missing_docs)]\n```\n\nThere are cases where you want to disable these warnings/errors to explicitly\nleave something undocumented. This is done by using `allow`:\n\n```rust\n#[allow(missing_docs)]\nstruct Undocumented;\n```\n\nYou might even want to hide items from the documentation completely:\n\n```rust\n#[doc(hidden)]\nstruct Hidden;\n```\n\n### Controlling HTML\n\nYou can control a few aspects of the HTML that `rustdoc` generates through the\n`#![doc]` version of the attribute:\n\n```rust\n#![doc(html_logo_url = \"https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png\",\n       html_favicon_url = \"https://www.rust-lang.org/favicon.ico\",\n       html_root_url = \"https://doc.rust-lang.org/\")]\n```\n\nThis sets a few different options, with a logo, favicon, and a root URL.\n\n### Configuring documentation tests\n\nYou can also configure the way that `rustdoc` tests your documentation examples\nthrough the `#![doc(test(..))]` attribute.\n\n```rust\n#![doc(test(attr(allow(unused_variables), deny(warnings))))]\n```\n\nThis allows unused variables within the examples, but will fail the test for any\nother lint warning thrown.\n\n## Generation options\n\n`rustdoc` also contains a few other options on the command line, for further customization:\n\n- `--html-in-header FILE`: includes the contents of FILE at the end of the\n  `<head>...</head>` section.\n- `--html-before-content FILE`: includes the contents of FILE directly after\n  `<body>`, before the rendered content (including the search bar).\n- `--html-after-content FILE`: includes the contents of FILE after all the rendered content.\n\n## Security note\n\nThe Markdown in documentation comments is placed without processing into\nthe final webpage. Be careful with literal HTML:\n\n```rust\n/// <script>alert(document.cookie)</script>\n# fn foo() {}\n```\n"
  },
  {
    "path": "trpl/drop.md",
    "content": "% Drop\n\nNow that we’ve discussed traits, let’s talk about a particular trait provided\nby the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way\nto run some code when a value goes out of scope. For example:\n\n[drop]: ../std/ops/trait.Drop.html\n\n```rust\nstruct HasDrop;\n\nimpl Drop for HasDrop {\n    fn drop(&mut self) {\n        println!(\"Dropping!\");\n    }\n}\n\nfn main() {\n    let x = HasDrop;\n\n    // do stuff\n\n} // x goes out of scope here\n```\n\nWhen `x` goes out of scope at the end of `main()`, the code for `Drop` will\nrun. `Drop` has one method, which is also called `drop()`. It takes a mutable\nreference to `self`.\n\nThat’s it! The mechanics of `Drop` are very simple, but there are some\nsubtleties. For example, values are dropped in the opposite order they are\ndeclared. Here’s another example:\n\n```rust\nstruct Firework {\n    strength: i32,\n}\n\nimpl Drop for Firework {\n    fn drop(&mut self) {\n        println!(\"BOOM times {}!!!\", self.strength);\n    }\n}\n\nfn main() {\n    let firecracker = Firework { strength: 1 };\n    let tnt = Firework { strength: 100 };\n}\n```\n\nThis will output:\n\n```text\nBOOM times 100!!!\nBOOM times 1!!!\n```\n\nThe `tnt` goes off before the `firecracker` does, because it was declared\nafterwards. Last in, first out.\n\nSo what is `Drop` good for? Generally, `Drop` is used to clean up any resources\nassociated with a `struct`. For example, the [`Arc<T>` type][arc] is a\nreference-counted type. When `Drop` is called, it will decrement the reference\ncount, and if the total number of references is zero, will clean up the\nunderlying value.\n\n[arc]: ../std/sync/struct.Arc.html\n"
  },
  {
    "path": "trpl/effective-rust.md",
    "content": "% Effective Rust\n\nSo you’ve learned how to write some Rust code. But there’s a difference between\nwriting *any* Rust code and writing *good* Rust code.\n\nThis chapter consists of relatively independent tutorials which show you how to\ntake your Rust to the next level. Common patterns and standard library features\nwill be introduced. Read these sections in any order of your choosing.\n"
  },
  {
    "path": "trpl/enums.md",
    "content": "% Enums\n\nAn `enum` in Rust is a type that represents data that is one of\nseveral possible variants. Each variant in the `enum` can optionally\nhave data associated with it:\n\n```rust\nenum Message {\n    Quit,\n    ChangeColor(i32, i32, i32),\n    Move { x: i32, y: i32 },\n    Write(String),\n}\n```\n\nThe syntax for defining variants resembles the syntaxes used to define structs:\nyou can have variants with no data (like unit-like structs), variants with named\ndata, and variants with unnamed data (like tuple structs). Unlike\nseparate struct definitions, however, an `enum` is a single type. A\nvalue of the enum can match any of the variants. For this reason, an\nenum is sometimes called a ‘sum type’: the set of possible values of the\nenum is the sum of the sets of possible values for each variant.\n\nWe use the `::` syntax to use the name of each variant: they’re scoped by the name\nof the `enum` itself. This allows both of these to work:\n\n```rust\n# enum Message {\n#     Move { x: i32, y: i32 },\n# }\nlet x: Message = Message::Move { x: 3, y: 4 };\n\nenum BoardGameTurn {\n    Move { squares: i32 },\n    Pass,\n}\n\nlet y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };\n```\n\nBoth variants are named `Move`, but since they’re scoped to the name of\nthe enum, they can both be used without conflict.\n\nA value of an `enum` type contains information about which variant it is,\nin addition to any data associated with that variant. This is sometimes\nreferred to as a ‘tagged union’, since the data includes a ‘tag’\nindicating what type it is. The compiler uses this information to\nenforce that you’re accessing the data in the enum safely. For instance,\nyou can’t simply try to destructure a value as if it were one of the\npossible variants:\n\n```rust,ignore\nfn process_color_change(msg: Message) {\n    let Message::ChangeColor(r, g, b) = msg; // compile-time error\n}\n```\n\nNot supporting these operations may seem rather limiting, but it’s a limitation\nwhich we can overcome. There are two ways: by implementing equality ourselves,\nor by pattern matching variants with [`match`][match] expressions, which you’ll\nlearn in the next section. We don’t know enough about Rust to implement\nequality yet, but we’ll find out in the [`traits`][traits] section.\n\n[match]: match.html\n[traits]: traits.html\n\n# Constructors as functions\n\nAn `enum` constructor can also be used like a function. For example:\n\n```rust\n# enum Message {\n# Write(String),\n# }\nlet m = Message::Write(\"Hello, world\".to_string());\n```\n\nis the same as\n\n```rust\n# enum Message {\n# Write(String),\n# }\nfn foo(x: String) -> Message {\n    Message::Write(x)\n}\n\nlet x = foo(\"Hello, world\".to_string());\n```\n\nThis is not immediately useful to us, but when we get to\n[`closures`][closures], we’ll talk about passing functions as arguments to\nother functions. For example, with [`iterators`][iterators], we can do this\nto convert a vector of `String`s into a vector of `Message::Write`s:\n\n```rust\n# enum Message {\n# Write(String),\n# }\n\nlet v = vec![\"Hello\".to_string(), \"World\".to_string()];\n\nlet v1: Vec<Message> = v.into_iter().map(Message::Write).collect();\n```\n\n[closures]: closures.html\n[iterators]: iterators.html\n"
  },
  {
    "path": "trpl/error-handling.md",
    "content": "% Error Handling\n\nLike most programming languages, Rust encourages the programmer to handle\nerrors in a particular way. Generally speaking, error handling is divided into\ntwo broad categories: exceptions and return values. Rust opts for return\nvalues.\n\nIn this section, we intend to provide a comprehensive treatment of how to deal\nwith errors in Rust. More than that, we will attempt to introduce error handling\none piece at a time so that you'll come away with a solid working knowledge of\nhow everything fits together.\n\nWhen done naïvely, error handling in Rust can be verbose and annoying. This\nsection will explore those stumbling blocks and demonstrate how to use the\nstandard library to make error handling concise and ergonomic.\n\n# Table of Contents\n\nThis section is very long, mostly because we start at the very beginning with\nsum types and combinators, and try to motivate the way Rust does error handling\nincrementally. As such, programmers with experience in other expressive type\nsystems may want to jump around.\n\n* [The Basics](#the-basics)\n    * [Unwrapping explained](#unwrapping-explained)\n    * [The `Option` type](#the-option-type)\n        * [Composing `Option<T>` values](#composing-optiont-values)\n    * [The `Result` type](#the-result-type)\n        * [Parsing integers](#parsing-integers)\n        * [The `Result` type alias idiom](#the-result-type-alias-idiom)\n    * [A brief interlude: unwrapping isn't evil](#a-brief-interlude-unwrapping-isnt-evil)\n* [Working with multiple error types](#working-with-multiple-error-types)\n    * [Composing `Option` and `Result`](#composing-option-and-result)\n    * [The limits of combinators](#the-limits-of-combinators)\n    * [Early returns](#early-returns)\n    * [The `try!` macro](#the-try-macro)\n    * [Defining your own error type](#defining-your-own-error-type)\n* [Standard library traits used for error handling](#standard-library-traits-used-for-error-handling)\n    * [The `Error` trait](#the-error-trait)\n    * [The `From` trait](#the-from-trait)\n    * [The real `try!` macro](#the-real-try-macro)\n    * [Composing custom error types](#composing-custom-error-types)\n    * [Advice for library writers](#advice-for-library-writers)\n* [Case study: A program to read population data](#case-study-a-program-to-read-population-data)\n    * [Initial setup](#initial-setup)\n    * [Argument parsing](#argument-parsing)\n    * [Writing the logic](#writing-the-logic)\n    * [Error handling with `Box<Error>`](#error-handling-with-boxerror)\n    * [Reading from stdin](#reading-from-stdin)\n    * [Error handling with a custom type](#error-handling-with-a-custom-type)\n    * [Adding functionality](#adding-functionality)\n* [The short story](#the-short-story)\n\n# The Basics\n\nYou can think of error handling as using *case analysis* to determine whether\na computation was successful or not. As you will see, the key to ergonomic error\nhandling is reducing the amount of explicit case analysis the programmer has to\ndo while keeping code composable.\n\nKeeping code composable is important, because without that requirement, we\ncould [`panic`](../std/macro.panic!.html) whenever we\ncome across something unexpected. (`panic` causes the current task to unwind,\nand in most cases, the entire program aborts.) Here's an example:\n\n```rust,should_panic\n// Guess a number between 1 and 10.\n// If it matches the number we had in mind, return true. Else, return false.\nfn guess(n: i32) -> bool {\n    if n < 1 || n > 10 {\n        panic!(\"Invalid number: {}\", n);\n    }\n    n == 5\n}\n\nfn main() {\n    guess(11);\n}\n```\n\nIf you try running this code, the program will crash with a message like this:\n\n```text\nthread 'main' panicked at 'Invalid number: 11', src/bin/panic-simple.rs:5\n```\n\nHere's another example that is slightly less contrived. A program that accepts\nan integer as an argument, doubles it and prints it.\n\n<span id=\"code-unwrap-double\"></span>\n\n```rust,should_panic\nuse std::env;\n\nfn main() {\n    let mut argv = env::args();\n    let arg: String = argv.nth(1).unwrap(); // error 1\n    let n: i32 = arg.parse().unwrap(); // error 2\n    println!(\"{}\", 2 * n);\n}\n```\n\nIf you give this program zero arguments (error 1) or if the first argument\nisn't an integer (error 2), the program will panic just like in the first\nexample.\n\nYou can think of this style of error handling as similar to a bull running\nthrough a china shop. The bull will get to where it wants to go, but it will\ntrample everything in the process.\n\n## Unwrapping explained\n\nIn the previous example, we claimed\nthat the program would simply panic if it reached one of the two error\nconditions, yet, the program does not include an explicit call to `panic` like\nthe first example. This is because the\npanic is embedded in the calls to `unwrap`.\n\nTo “unwrap” something in Rust is to say, “Give me the result of the\ncomputation, and if there was an error, panic and stop the program.”\nIt would be better if we showed the code for unwrapping because it is so\nsimple, but to do that, we will first need to explore the `Option` and `Result`\ntypes. Both of these types have a method called `unwrap` defined on them.\n\n### The `Option` type\n\nThe `Option` type is [defined in the standard library][5]:\n\n```rust\nenum Option<T> {\n    None,\n    Some(T),\n}\n```\n\nThe `Option` type is a way to use Rust's type system to express the\n*possibility of absence*. Encoding the possibility of absence into the type\nsystem is an important concept because it will cause the compiler to force the\nprogrammer to handle that absence. Let's take a look at an example that tries\nto find a character in a string:\n\n<span id=\"code-option-ex-string-find\"></span>\n\n```rust\n// Searches `haystack` for the Unicode character `needle`. If one is found, the\n// byte offset of the character is returned. Otherwise, `None` is returned.\nfn find(haystack: &str, needle: char) -> Option<usize> {\n    for (offset, c) in haystack.char_indices() {\n        if c == needle {\n            return Some(offset);\n        }\n    }\n    None\n}\n```\n\nNotice that when this function finds a matching character, it doesn't only\nreturn the `offset`. Instead, it returns `Some(offset)`. `Some` is a variant or\na *value constructor* for the `Option` type. You can think of it as a function\nwith the type `fn<T>(value: T) -> Option<T>`. Correspondingly, `None` is also a\nvalue constructor, except it has no arguments. You can think of `None` as a\nfunction with the type `fn<T>() -> Option<T>`.\n\nThis might seem like much ado about nothing, but this is only half of the\nstory. The other half is *using* the `find` function we've written. Let's try\nto use it to find the extension in a file name.\n\n```rust\n# fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }\nfn main() {\n    let file_name = \"foobar.rs\";\n    match find(file_name, '.') {\n        None => println!(\"No file extension found.\"),\n        Some(i) => println!(\"File extension: {}\", &file_name[i+1..]),\n    }\n}\n```\n\nThis code uses [pattern matching][1] to do *case\nanalysis* on the `Option<usize>` returned by the `find` function. In fact, case\nanalysis is the only way to get at the value stored inside an `Option<T>`. This\nmeans that you, as the programmer, must handle the case when an `Option<T>` is\n`None` instead of `Some(t)`.\n\nBut wait, what about `unwrap`, which we used [previously](#code-unwrap-double)?\nThere was no case analysis there! Instead, the case analysis was put inside the\n`unwrap` method for you. You could define it yourself if you want:\n\n<span id=\"code-option-def-unwrap\"></span>\n\n```rust\nenum Option<T> {\n    None,\n    Some(T),\n}\n\nimpl<T> Option<T> {\n    fn unwrap(self) -> T {\n        match self {\n            Option::Some(val) => val,\n            Option::None =>\n              panic!(\"called `Option::unwrap()` on a `None` value\"),\n        }\n    }\n}\n```\n\nThe `unwrap` method *abstracts away the case analysis*. This is precisely the thing\nthat makes `unwrap` ergonomic to use. Unfortunately, that `panic!` means that\n`unwrap` is not composable: it is the bull in the china shop.\n\n### Composing `Option<T>` values\n\nIn an [example from before](#code-option-ex-string-find),\nwe saw how to use `find` to discover the extension in a file name. Of course,\nnot all file names have a `.` in them, so it's possible that the file name has\nno extension. This *possibility of absence* is encoded into the types using\n`Option<T>`. In other words, the compiler will force us to address the\npossibility that an extension does not exist. In our case, we only print out a\nmessage saying as such.\n\nGetting the extension of a file name is a pretty common operation, so it makes\nsense to put it into a function:\n\n```rust\n# fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }\n// Returns the extension of the given file name, where the extension is defined\n// as all characters following the first `.`.\n// If `file_name` has no `.`, then `None` is returned.\nfn extension_explicit(file_name: &str) -> Option<&str> {\n    match find(file_name, '.') {\n        None => None,\n        Some(i) => Some(&file_name[i+1..]),\n    }\n}\n```\n\n(Pro-tip: don't use this code. Use the\n[`extension`](../std/path/struct.Path.html#method.extension)\nmethod in the standard library instead.)\n\nThe code stays simple, but the important thing to notice is that the type of\n`find` forces us to consider the possibility of absence. This is a good thing\nbecause it means the compiler won't let us accidentally forget about the case\nwhere a file name doesn't have an extension. On the other hand, doing explicit\ncase analysis like we've done in `extension_explicit` every time can get a bit\ntiresome.\n\nIn fact, the case analysis in `extension_explicit` follows a very common\npattern: *map* a function on to the value inside of an `Option<T>`, unless the\noption is `None`, in which case, return `None`.\n\nRust has parametric polymorphism, so it is very easy to define a combinator\nthat abstracts this pattern:\n\n<span id=\"code-option-map\"></span>\n\n```rust\nfn map<F, T, A>(option: Option<T>, f: F) -> Option<A> where F: FnOnce(T) -> A {\n    match option {\n        None => None,\n        Some(value) => Some(f(value)),\n    }\n}\n```\n\nIndeed, `map` is [defined as a method][2] on `Option<T>` in the standard library.\nAs a method, it has a slightly different signature: methods take `self`, `&self`,\nor `&mut self` as their first argument.\n\nArmed with our new combinator, we can rewrite our `extension_explicit` method\nto get rid of the case analysis:\n\n```rust\n# fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }\n// Returns the extension of the given file name, where the extension is defined\n// as all characters following the first `.`.\n// If `file_name` has no `.`, then `None` is returned.\nfn extension(file_name: &str) -> Option<&str> {\n    find(file_name, '.').map(|i| &file_name[i+1..])\n}\n```\n\nOne other pattern we commonly find is assigning a default value to the case\nwhen an `Option` value is `None`. For example, maybe your program assumes that\nthe extension of a file is `rs` even if none is present. As you might imagine,\nthe case analysis for this is not specific to file extensions - it can work\nwith any `Option<T>`:\n\n```rust\nfn unwrap_or<T>(option: Option<T>, default: T) -> T {\n    match option {\n        None => default,\n        Some(value) => value,\n    }\n}\n```\n\nLike with `map` above, the standard library implementation is a method instead\nof a free function.\n\nThe trick here is that the default value must have the same type as the value\nthat might be inside the `Option<T>`. Using it is dead simple in our case:\n\n```rust\n# fn find(haystack: &str, needle: char) -> Option<usize> {\n#     for (offset, c) in haystack.char_indices() {\n#         if c == needle {\n#             return Some(offset);\n#         }\n#     }\n#     None\n# }\n#\n# fn extension(file_name: &str) -> Option<&str> {\n#     find(file_name, '.').map(|i| &file_name[i+1..])\n# }\nfn main() {\n    assert_eq!(extension(\"foobar.csv\").unwrap_or(\"rs\"), \"csv\");\n    assert_eq!(extension(\"foobar\").unwrap_or(\"rs\"), \"rs\");\n}\n```\n\n(Note that `unwrap_or` is [defined as a method][3] on `Option<T>` in the\nstandard library, so we use that here instead of the free-standing function we\ndefined above. Don't forget to check out the more general [`unwrap_or_else`][4]\nmethod.)\n\nThere is one more combinator that we think is worth paying special attention to:\n`and_then`. It makes it easy to compose distinct computations that admit the\n*possibility of absence*. For example, much of the code in this section is\nabout finding an extension given a file name. In order to do this, you first\nneed the file name which is typically extracted from a file *path*. While most\nfile paths have a file name, not *all* of them do. For example, `.`, `..` or\n`/`.\n\nSo, we are tasked with the challenge of finding an extension given a file\n*path*. Let's start with explicit case analysis:\n\n```rust\n# fn extension(file_name: &str) -> Option<&str> { None }\nfn file_path_ext_explicit(file_path: &str) -> Option<&str> {\n    match file_name(file_path) {\n        None => None,\n        Some(name) => match extension(name) {\n            None => None,\n            Some(ext) => Some(ext),\n        }\n    }\n}\n\nfn file_name(file_path: &str) -> Option<&str> {\n  // implementation elided\n  unimplemented!()\n}\n```\n\nYou might think that we could use the `map` combinator to reduce the case\nanalysis, but its type doesn't quite fit...\n\n```rust,ignore\nfn file_path_ext(file_path: &str) -> Option<&str> {\n    file_name(file_path).map(|x| extension(x)) //Compilation error\n}\n```\n\nThe `map` function here wraps the value returned by the `extension` function\ninside an `Option<_>` and since the `extension` function itself returns an\n`Option<&str>` the expression `file_name(file_path).map(|x| extension(x))`\nactually returns an `Option<Option<&str>>`.\n\nBut since `file_path_ext` just returns `Option<&str>` (and not\n`Option<Option<&str>>`) we get a compilation error.\n\nThe result of the function taken by map as input is *always* [rewrapped with\n`Some`](#code-option-map). Instead, we need something like `map`, but which\nallows the caller to return a `Option<_>` directly without wrapping it in\nanother `Option<_>`.\n\nIts generic implementation is even simpler than `map`:\n\n```rust\nfn and_then<F, T, A>(option: Option<T>, f: F) -> Option<A>\n        where F: FnOnce(T) -> Option<A> {\n    match option {\n        None => None,\n        Some(value) => f(value),\n    }\n}\n```\n\nNow we can rewrite our `file_path_ext` function without explicit case analysis:\n\n```rust\n# fn extension(file_name: &str) -> Option<&str> { None }\n# fn file_name(file_path: &str) -> Option<&str> { None }\nfn file_path_ext(file_path: &str) -> Option<&str> {\n    file_name(file_path).and_then(extension)\n}\n```\n\nSide note: Since `and_then` essentially works like `map` but returns an\n`Option<_>` instead of an `Option<Option<_>>` it is known as `flatmap` in some\nother languages.\n\nThe `Option` type has many other combinators [defined in the standard\nlibrary][5]. It is a good idea to skim this list and familiarize\nyourself with what's available—they can often reduce case analysis\nfor you. Familiarizing yourself with these combinators will pay\ndividends because many of them are also defined (with similar\nsemantics) for `Result`, which we will talk about next.\n\nCombinators make using types like `Option` ergonomic because they reduce\nexplicit case analysis. They are also composable because they permit the caller\nto handle the possibility of absence in their own way. Methods like `unwrap`\nremove choices because they will panic if `Option<T>` is `None`.\n\n## The `Result` type\n\nThe `Result` type is also\n[defined in the standard library][6]:\n\n<span id=\"code-result-def\"></span>\n\n```rust\nenum Result<T, E> {\n    Ok(T),\n    Err(E),\n}\n```\n\nThe `Result` type is a richer version of `Option`. Instead of expressing the\npossibility of *absence* like `Option` does, `Result` expresses the possibility\nof *error*. Usually, the *error* is used to explain why the execution of some\ncomputation failed. This is a strictly more general form of `Option`. Consider\nthe following type alias, which is semantically equivalent to the real\n`Option<T>` in every way:\n\n```rust\ntype Option<T> = Result<T, ()>;\n```\n\nThis fixes the second type parameter of `Result` to always be `()` (pronounced\n“unit” or “empty tuple”). Exactly one value inhabits the `()` type: `()`. (Yup,\nthe type and value level terms have the same notation!)\n\nThe `Result` type is a way of representing one of two possible outcomes in a\ncomputation. By convention, one outcome is meant to be expected or “`Ok`” while\nthe other outcome is meant to be unexpected or “`Err`”.\n\nJust like `Option`, the `Result` type also has an\n[`unwrap` method\ndefined][7]\nin the standard library. Let's define it:\n\n```rust\n# enum Result<T, E> { Ok(T), Err(E) }\nimpl<T, E: ::std::fmt::Debug> Result<T, E> {\n    fn unwrap(self) -> T {\n        match self {\n            Result::Ok(val) => val,\n            Result::Err(err) =>\n              panic!(\"called `Result::unwrap()` on an `Err` value: {:?}\", err),\n        }\n    }\n}\n```\n\nThis is effectively the same as our [definition for\n`Option::unwrap`](#code-option-def-unwrap), except it includes the\nerror value in the `panic!` message. This makes debugging easier, but\nit also requires us to add a [`Debug`][8] constraint on the `E` type\nparameter (which represents our error type). Since the vast majority\nof types should satisfy the `Debug` constraint, this tends to work out\nin practice. (`Debug` on a type simply means that there's a reasonable\nway to print a human readable description of values with that type.)\n\nOK, let's move on to an example.\n\n### Parsing integers\n\nThe Rust standard library makes converting strings to integers dead simple.\nIt's so easy in fact, that it is very tempting to write something like the\nfollowing:\n\n```rust\nfn double_number(number_str: &str) -> i32 {\n    2 * number_str.parse::<i32>().unwrap()\n}\n\nfn main() {\n    let n: i32 = double_number(\"10\");\n    assert_eq!(n, 20);\n}\n```\n\nAt this point, you should be skeptical of calling `unwrap`. For example, if\nthe string doesn't parse as a number, you'll get a panic:\n\n```text\nthread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', /home/rustbuild/src/rust-buildbot/slave/beta-dist-rustc-linux/build/src/libcore/result.rs:729\n```\n\nThis is rather unsightly, and if this happened inside a library you're\nusing, you might be understandably annoyed. Instead, we should try to\nhandle the error in our function and let the caller decide what to\ndo. This means changing the return type of `double_number`. But to\nwhat? Well, that requires looking at the signature of the [`parse`\nmethod][9] in the standard library:\n\n```rust,ignore\nimpl str {\n    fn parse<F: FromStr>(&self) -> Result<F, F::Err>;\n}\n```\n\nHmm. So we at least know that we need to use a `Result`. Certainly, it's\npossible that this could have returned an `Option`. After all, a string either\nparses as a number or it doesn't, right? That's certainly a reasonable way to\ngo, but the implementation internally distinguishes *why* the string didn't\nparse as an integer. (Whether it's an empty string, an invalid digit, too big\nor too small.) Therefore, using a `Result` makes sense because we want to\nprovide more information than simply “absence.” We want to say *why* the\nparsing failed. You should try to emulate this line of reasoning when faced\nwith a choice between `Option` and `Result`. If you can provide detailed error\ninformation, then you probably should. (We'll see more on this later.)\n\nOK, but how do we write our return type? The `parse` method as defined\nabove is generic over all the different number types defined in the\nstandard library. We could (and probably should) also make our\nfunction generic, but let's favor explicitness for the moment. We only\ncare about `i32`, so we need to [find its implementation of\n`FromStr`](../std/primitive.i32.html) (do a `CTRL-F` in your browser\nfor “FromStr”) and look at its [associated type][10] `Err`. We did\nthis so we can find the concrete error type. In this case, it's\n[`std::num::ParseIntError`](../std/num/struct.ParseIntError.html).\nFinally, we can rewrite our function:\n\n```rust\nuse std::num::ParseIntError;\n\nfn double_number(number_str: &str) -> Result<i32, ParseIntError> {\n    match number_str.parse::<i32>() {\n        Ok(n) => Ok(2 * n),\n        Err(err) => Err(err),\n    }\n}\n\nfn main() {\n    match double_number(\"10\") {\n        Ok(n) => assert_eq!(n, 20),\n        Err(err) => println!(\"Error: {:?}\", err),\n    }\n}\n```\n\nThis is a little better, but now we've written a lot more code! The case\nanalysis has once again bitten us.\n\nCombinators to the rescue! Just like `Option`, `Result` has lots of combinators\ndefined as methods. There is a large intersection of common combinators between\n`Result` and `Option`. In particular, `map` is part of that intersection:\n\n```rust\nuse std::num::ParseIntError;\n\nfn double_number(number_str: &str) -> Result<i32, ParseIntError> {\n    number_str.parse::<i32>().map(|n| 2 * n)\n}\n\nfn main() {\n    match double_number(\"10\") {\n        Ok(n) => assert_eq!(n, 20),\n        Err(err) => println!(\"Error: {:?}\", err),\n    }\n}\n```\n\nThe usual suspects are all there for `Result`, including\n[`unwrap_or`](../std/result/enum.Result.html#method.unwrap_or) and\n[`and_then`](../std/result/enum.Result.html#method.and_then).\nAdditionally, since `Result` has a second type parameter, there are\ncombinators that affect only the error type, such as\n[`map_err`](../std/result/enum.Result.html#method.map_err) (instead of\n`map`) and [`or_else`](../std/result/enum.Result.html#method.or_else)\n(instead of `and_then`).\n\n### The `Result` type alias idiom\n\nIn the standard library, you may frequently see types like\n`Result<i32>`. But wait, [we defined `Result`](#code-result-def) to\nhave two type parameters. How can we get away with only specifying\none? The key is to define a `Result` type alias that *fixes* one of\nthe type parameters to a particular type. Usually the fixed type is\nthe error type. For example, our previous example parsing integers\ncould be rewritten like this:\n\n```rust\nuse std::num::ParseIntError;\nuse std::result;\n\ntype Result<T> = result::Result<T, ParseIntError>;\n\nfn double_number(number_str: &str) -> Result<i32> {\n    unimplemented!();\n}\n```\n\nWhy would we do this? Well, if we have a lot of functions that could return\n`ParseIntError`, then it's much more convenient to define an alias that always\nuses `ParseIntError` so that we don't have to write it out all the time.\n\nThe most prominent place this idiom is used in the standard library is\nwith [`io::Result`](../std/io/type.Result.html). Typically, one writes\n`io::Result<T>`, which makes it clear that you're using the `io`\nmodule's type alias instead of the plain definition from\n`std::result`. (This idiom is also used for\n[`fmt::Result`](../std/fmt/type.Result.html).)\n\n## A brief interlude: unwrapping isn't evil\n\nIf you've been following along, you might have noticed that I've taken a pretty\nhard line against calling methods like `unwrap` that could `panic` and abort\nyour program. *Generally speaking*, this is good advice.\n\nHowever, `unwrap` can still be used judiciously. What exactly justifies use of\n`unwrap` is somewhat of a grey area and reasonable people can disagree. I'll\nsummarize some of my *opinions* on the matter.\n\n* **In examples and quick 'n' dirty code.** Sometimes you're writing examples\n  or a quick program, and error handling simply isn't important. Beating the\n  convenience of `unwrap` can be hard in such scenarios, so it is very\n  appealing.\n* **When panicking indicates a bug in the program.** When the invariants of\n  your code should prevent a certain case from happening (like, say, popping\n  from an empty stack), then panicking can be permissible. This is because it\n  exposes a bug in your program. This can be explicit, like from an `assert!`\n  failing, or it could be because your index into an array was out of bounds.\n\nThis is probably not an exhaustive list. Moreover, when using an\n`Option`, it is often better to use its\n[`expect`](../std/option/enum.Option.html#method.expect)\nmethod. `expect` does exactly the same thing as `unwrap`, except it\nprints a message you give to `expect`. This makes the resulting panic\na bit nicer to deal with, since it will show your message instead of\n“called unwrap on a `None` value.”\n\nMy advice boils down to this: use good judgment. There's a reason why the words\n“never do X” or “Y is considered harmful” don't appear in my writing. There are\ntrade offs to all things, and it is up to you as the programmer to determine\nwhat is acceptable for your use cases. My goal is only to help you evaluate\ntrade offs as accurately as possible.\n\nNow that we've covered the basics of error handling in Rust, and\nexplained unwrapping, let's start exploring more of the standard\nlibrary.\n\n# Working with multiple error types\n\nThus far, we've looked at error handling where everything was either an\n`Option<T>` or a `Result<T, SomeError>`. But what happens when you have both an\n`Option` and a `Result`? Or what if you have a `Result<T, Error1>` and a\n`Result<T, Error2>`? Handling *composition of distinct error types* is the next\nchallenge in front of us, and it will be the major theme throughout the rest of\nthis section.\n\n## Composing `Option` and `Result`\n\nSo far, I've talked about combinators defined for `Option` and combinators\ndefined for `Result`. We can use these combinators to compose results of\ndifferent computations without doing explicit case analysis.\n\nOf course, in real code, things aren't always as clean. Sometimes you have a\nmix of `Option` and `Result` types. Must we resort to explicit case analysis,\nor can we continue using combinators?\n\nFor now, let's revisit one of the first examples in this section:\n\n```rust,should_panic\nuse std::env;\n\nfn main() {\n    let mut argv = env::args();\n    let arg: String = argv.nth(1).unwrap(); // error 1\n    let n: i32 = arg.parse().unwrap(); // error 2\n    println!(\"{}\", 2 * n);\n}\n```\n\nGiven our new found knowledge of `Option`, `Result` and their various\ncombinators, we should try to rewrite this so that errors are handled properly\nand the program doesn't panic if there's an error.\n\nThe tricky aspect here is that `argv.nth(1)` produces an `Option` while\n`arg.parse()` produces a `Result`. These aren't directly composable. When faced\nwith both an `Option` and a `Result`, the solution is *usually* to convert the\n`Option` to a `Result`. In our case, the absence of a command line parameter\n(from `env::args()`) means the user didn't invoke the program correctly. We\ncould use a `String` to describe the error. Let's try:\n\n<span id=\"code-error-double-string\"></span>\n\n```rust\nuse std::env;\n\nfn double_arg(mut argv: env::Args) -> Result<i32, String> {\n    argv.nth(1)\n        .ok_or(\"Please give at least one argument\".to_owned())\n        .and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string()))\n        .map(|n| 2 * n)\n}\n\nfn main() {\n    match double_arg(env::args()) {\n        Ok(n) => println!(\"{}\", n),\n        Err(err) => println!(\"Error: {}\", err),\n    }\n}\n```\n\nThere are a couple new things in this example. The first is the use of the\n[`Option::ok_or`](../std/option/enum.Option.html#method.ok_or)\ncombinator. This is one way to convert an `Option` into a `Result`. The\nconversion requires you to specify what error to use if `Option` is `None`.\nLike the other combinators we've seen, its definition is very simple:\n\n```rust\nfn ok_or<T, E>(option: Option<T>, err: E) -> Result<T, E> {\n    match option {\n        Some(val) => Ok(val),\n        None => Err(err),\n    }\n}\n```\n\nThe other new combinator used here is\n[`Result::map_err`](../std/result/enum.Result.html#method.map_err).\nThis is like `Result::map`, except it maps a function on to the *error*\nportion of a `Result` value. If the `Result` is an `Ok(...)` value, then it is\nreturned unmodified.\n\nWe use `map_err` here because it is necessary for the error types to remain\nthe same (because of our use of `and_then`). Since we chose to convert the\n`Option<String>` (from `argv.nth(1)`) to a `Result<String, String>`, we must\nalso convert the `ParseIntError` from `arg.parse()` to a `String`.\n\n## The limits of combinators\n\nDoing IO and parsing input is a very common task, and it's one that I\npersonally have done a lot of in Rust. Therefore, we will use (and continue to\nuse) IO and various parsing routines to exemplify error handling.\n\nLet's start simple. We are tasked with opening a file, reading all of its\ncontents and converting its contents to a number. Then we multiply it by `2`\nand print the output.\n\nAlthough I've tried to convince you not to use `unwrap`, it can be useful\nto first write your code using `unwrap`. It allows you to focus on your problem\ninstead of the error handling, and it exposes the points where proper error\nhandling need to occur. Let's start there so we can get a handle on the code,\nand then refactor it to use better error handling.\n\n```rust,should_panic\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> i32 {\n    let mut file = File::open(file_path).unwrap(); // error 1\n    let mut contents = String::new();\n    file.read_to_string(&mut contents).unwrap(); // error 2\n    let n: i32 = contents.trim().parse().unwrap(); // error 3\n    2 * n\n}\n\nfn main() {\n    let doubled = file_double(\"foobar\");\n    println!(\"{}\", doubled);\n}\n```\n\n(N.B. The `AsRef<Path>` is used because those are the\n[same bounds used on\n`std::fs::File::open`](../std/fs/struct.File.html#method.open).\nThis makes it ergonomic to use any kind of string as a file path.)\n\nThere are three different errors that can occur here:\n\n1. A problem opening the file.\n2. A problem reading data from the file.\n3. A problem parsing the data as a number.\n\nThe first two problems are described via the\n[`std::io::Error`](../std/io/struct.Error.html) type. We know this\nbecause of the return types of\n[`std::fs::File::open`](../std/fs/struct.File.html#method.open) and\n[`std::io::Read::read_to_string`](../std/io/trait.Read.html#method.read_to_string).\n(Note that they both use the [`Result` type alias\nidiom](#the-result-type-alias-idiom) described previously. If you\nclick on the `Result` type, you'll [see the type\nalias](../std/io/type.Result.html), and consequently, the underlying\n`io::Error` type.)  The third problem is described by the\n[`std::num::ParseIntError`](../std/num/struct.ParseIntError.html)\ntype. The `io::Error` type in particular is *pervasive* throughout the\nstandard library. You will see it again and again.\n\nLet's start the process of refactoring the `file_double` function. To make this\nfunction composable with other components of the program, it should *not* panic\nif any of the above error conditions are met. Effectively, this means that the\nfunction should *return an error* if any of its operations fail. Our problem is\nthat the return type of `file_double` is `i32`, which does not give us any\nuseful way of reporting an error. Thus, we must start by changing the return\ntype from `i32` to something else.\n\nThe first thing we need to decide: should we use `Option` or `Result`? We\ncertainly could use `Option` very easily. If any of the three errors occur, we\ncould simply return `None`. This will work *and it is better than panicking*,\nbut we can do a lot better. Instead, we should pass some detail about the error\nthat occurred. Since we want to express the *possibility of error*, we should\nuse `Result<i32, E>`. But what should `E` be? Since two *different* types of\nerrors can occur, we need to convert them to a common type. One such type is\n`String`. Let's see how that impacts our code:\n\n```rust\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {\n    File::open(file_path)\n         .map_err(|err| err.to_string())\n         .and_then(|mut file| {\n              let mut contents = String::new();\n              file.read_to_string(&mut contents)\n                  .map_err(|err| err.to_string())\n                  .map(|_| contents)\n         })\n         .and_then(|contents| {\n              contents.trim().parse::<i32>()\n                      .map_err(|err| err.to_string())\n         })\n         .map(|n| 2 * n)\n}\n\nfn main() {\n    match file_double(\"foobar\") {\n        Ok(n) => println!(\"{}\", n),\n        Err(err) => println!(\"Error: {}\", err),\n    }\n}\n```\n\nThis code looks a bit hairy. It can take quite a bit of practice before code\nlike this becomes easy to write. The way we write it is by *following the\ntypes*. As soon as we changed the return type of `file_double` to\n`Result<i32, String>`, we had to start looking for the right combinators. In\nthis case, we only used three different combinators: `and_then`, `map` and\n`map_err`.\n\n`and_then` is used to chain multiple computations where each computation could\nreturn an error. After opening the file, there are two more computations that\ncould fail: reading from the file and parsing the contents as a number.\nCorrespondingly, there are two calls to `and_then`.\n\n`map` is used to apply a function to the `Ok(...)` value of a `Result`. For\nexample, the very last call to `map` multiplies the `Ok(...)` value (which is\nan `i32`) by `2`. If an error had occurred before that point, this operation\nwould have been skipped because of how `map` is defined.\n\n`map_err` is the trick that makes all of this work. `map_err` is like\n`map`, except it applies a function to the `Err(...)` value of a `Result`. In\nthis case, we want to convert all of our errors to one type: `String`. Since\nboth `io::Error` and `num::ParseIntError` implement `ToString`, we can call the\n`to_string()` method to convert them.\n\nWith all of that said, the code is still hairy. Mastering use of combinators is\nimportant, but they have their limits. Let's try a different approach: early\nreturns.\n\n## Early returns\n\nI'd like to take the code from the previous section and rewrite it using *early\nreturns*. Early returns let you exit the function early. We can't return early\nin `file_double` from inside another closure, so we'll need to revert back to\nexplicit case analysis.\n\n```rust\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {\n    let mut file = match File::open(file_path) {\n        Ok(file) => file,\n        Err(err) => return Err(err.to_string()),\n    };\n    let mut contents = String::new();\n    if let Err(err) = file.read_to_string(&mut contents) {\n        return Err(err.to_string());\n    }\n    let n: i32 = match contents.trim().parse() {\n        Ok(n) => n,\n        Err(err) => return Err(err.to_string()),\n    };\n    Ok(2 * n)\n}\n\nfn main() {\n    match file_double(\"foobar\") {\n        Ok(n) => println!(\"{}\", n),\n        Err(err) => println!(\"Error: {}\", err),\n    }\n}\n```\n\nReasonable people can disagree over whether this code is better than the code\nthat uses combinators, but if you aren't familiar with the combinator approach,\nthis code looks simpler to read to me. It uses explicit case analysis with\n`match` and `if let`. If an error occurs, it simply stops executing the\nfunction and returns the error (by converting it to a string).\n\nIsn't this a step backwards though? Previously, we said that the key to\nergonomic error handling is reducing explicit case analysis, yet we've reverted\nback to explicit case analysis here. It turns out, there are *multiple* ways to\nreduce explicit case analysis. Combinators aren't the only way.\n\n## The `try!` macro\n\nA cornerstone of error handling in Rust is the `try!` macro. The `try!` macro\nabstracts case analysis like combinators, but unlike combinators, it also\nabstracts *control flow*. Namely, it can abstract the *early return* pattern\nseen above.\n\nHere is a simplified definition of a `try!` macro:\n\n<span id=\"code-try-def-simple\"></span>\n\n```rust\nmacro_rules! try {\n    ($e:expr) => (match $e {\n        Ok(val) => val,\n        Err(err) => return Err(err),\n    });\n}\n```\n\n(The [real definition](../std/macro.try!.html) is a bit more\nsophisticated. We will address that later.)\n\nUsing the `try!` macro makes it very easy to simplify our last example. Since\nit does the case analysis and the early return for us, we get tighter code that\nis easier to read:\n\n```rust\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {\n    let mut file = try!(File::open(file_path).map_err(|e| e.to_string()));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents).map_err(|e| e.to_string()));\n    let n = try!(contents.trim().parse::<i32>().map_err(|e| e.to_string()));\n    Ok(2 * n)\n}\n\nfn main() {\n    match file_double(\"foobar\") {\n        Ok(n) => println!(\"{}\", n),\n        Err(err) => println!(\"Error: {}\", err),\n    }\n}\n```\n\nThe `map_err` calls are still necessary given\n[our definition of `try!`](#code-try-def-simple).\nThis is because the error types still need to be converted to `String`.\nThe good news is that we will soon learn how to remove those `map_err` calls!\nThe bad news is that we will need to learn a bit more about a couple important\ntraits in the standard library before we can remove the `map_err` calls.\n\n## Defining your own error type\n\nBefore we dive into some of the standard library error traits, I'd like to wrap\nup this section by removing the use of `String` as our error type in the\nprevious examples.\n\nUsing `String` as we did in our previous examples is convenient because it's\neasy to convert errors to strings, or even make up your own errors as strings\non the spot. However, using `String` for your errors has some downsides.\n\nThe first downside is that the error messages tend to clutter your\ncode. It's possible to define the error messages elsewhere, but unless\nyou're unusually disciplined, it is very tempting to embed the error\nmessage into your code. Indeed, we did exactly this in a [previous\nexample](#code-error-double-string).\n\nThe second and more important downside is that `String`s are *lossy*. That is,\nif all errors are converted to strings, then the errors we pass to the caller\nbecome completely opaque. The only reasonable thing the caller can do with a\n`String` error is show it to the user. Certainly, inspecting the string to\ndetermine the type of error is not robust. (Admittedly, this downside is far\nmore important inside of a library as opposed to, say, an application.)\n\nFor example, the `io::Error` type embeds an\n[`io::ErrorKind`](../std/io/enum.ErrorKind.html),\nwhich is *structured data* that represents what went wrong during an IO\noperation. This is important because you might want to react differently\ndepending on the error. (e.g., A `BrokenPipe` error might mean quitting your\nprogram gracefully while a `NotFound` error might mean exiting with an error\ncode and showing an error to the user.) With `io::ErrorKind`, the caller can\nexamine the type of an error with case analysis, which is strictly superior\nto trying to tease out the details of an error inside of a `String`.\n\nInstead of using a `String` as an error type in our previous example of reading\nan integer from a file, we can define our own error type that represents errors\nwith *structured data*. We endeavor to not drop information from underlying\nerrors in case the caller wants to inspect the details.\n\nThe ideal way to represent *one of many possibilities* is to define our own\nsum type using `enum`. In our case, an error is either an `io::Error` or a\n`num::ParseIntError`, so a natural definition arises:\n\n```rust\nuse std::io;\nuse std::num;\n\n// We derive `Debug` because all types should probably derive `Debug`.\n// This gives us a reasonable human readable description of `CliError` values.\n#[derive(Debug)]\nenum CliError {\n    Io(io::Error),\n    Parse(num::ParseIntError),\n}\n```\n\nTweaking our code is very easy. Instead of converting errors to strings, we\nsimply convert them to our `CliError` type using the corresponding value\nconstructor:\n\n```rust\n# #[derive(Debug)]\n# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) }\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {\n    let mut file = try!(File::open(file_path).map_err(CliError::Io));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents).map_err(CliError::Io));\n    let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse));\n    Ok(2 * n)\n}\n\nfn main() {\n    match file_double(\"foobar\") {\n        Ok(n) => println!(\"{}\", n),\n        Err(err) => println!(\"Error: {:?}\", err),\n    }\n}\n```\n\nThe only change here is switching `map_err(|e| e.to_string())` (which converts\nerrors to strings) to `map_err(CliError::Io)` or `map_err(CliError::Parse)`.\nThe *caller* gets to decide the level of detail to report to the user. In\neffect, using a `String` as an error type removes choices from the caller while\nusing a custom `enum` error type like `CliError` gives the caller all of the\nconveniences as before in addition to *structured data* describing the error.\n\nA rule of thumb is to define your own error type, but a `String` error type\nwill do in a pinch, particularly if you're writing an application. If you're\nwriting a library, defining your own error type should be strongly preferred so\nthat you don't remove choices from the caller unnecessarily.\n\n# Standard library traits used for error handling\n\nThe standard library defines two integral traits for error handling:\n[`std::error::Error`](../std/error/trait.Error.html) and\n[`std::convert::From`](../std/convert/trait.From.html). While `Error`\nis designed specifically for generically describing errors, the `From`\ntrait serves a more general role for converting values between two\ndistinct types.\n\n## The `Error` trait\n\nThe `Error` trait is [defined in the standard\nlibrary](../std/error/trait.Error.html):\n\n```rust\nuse std::fmt::{Debug, Display};\n\ntrait Error: Debug + Display {\n  /// A short description of the error.\n  fn description(&self) -> &str;\n\n  /// The lower level cause of this error, if any.\n  fn cause(&self) -> Option<&Error> { None }\n}\n```\n\nThis trait is super generic because it is meant to be implemented for *all*\ntypes that represent errors. This will prove useful for writing composable code\nas we'll see later. Otherwise, the trait allows you to do at least the\nfollowing things:\n\n* Obtain a `Debug` representation of the error.\n* Obtain a user-facing `Display` representation of the error.\n* Obtain a short description of the error (via the `description` method).\n* Inspect the causal chain of an error, if one exists (via the `cause` method).\n\nThe first two are a result of `Error` requiring impls for both `Debug` and\n`Display`. The latter two are from the two methods defined on `Error`. The\npower of `Error` comes from the fact that all error types impl `Error`, which\nmeans errors can be existentially quantified as a\n[trait object](../book/trait-objects.html).\nThis manifests as either `Box<Error>` or `&Error`. Indeed, the `cause` method\nreturns an `&Error`, which is itself a trait object. We'll revisit the\n`Error` trait's utility as a trait object later.\n\nFor now, it suffices to show an example implementing the `Error` trait. Let's\nuse the error type we defined in the\n[previous section](#defining-your-own-error-type):\n\n```rust\nuse std::io;\nuse std::num;\n\n// We derive `Debug` because all types should probably derive `Debug`.\n// This gives us a reasonable human readable description of `CliError` values.\n#[derive(Debug)]\nenum CliError {\n    Io(io::Error),\n    Parse(num::ParseIntError),\n}\n```\n\nThis particular error type represents the possibility of two types of errors\noccurring: an error dealing with I/O or an error converting a string to a\nnumber. The error could represent as many error types as you want by adding new\nvariants to the `enum` definition.\n\nImplementing `Error` is pretty straight-forward. It's mostly going to be a lot\nexplicit case analysis.\n\n```rust,ignore\nuse std::error;\nuse std::fmt;\n\nimpl fmt::Display for CliError {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            // Both underlying errors already impl `Display`, so we defer to\n            // their implementations.\n            CliError::Io(ref err) => write!(f, \"IO error: {}\", err),\n            CliError::Parse(ref err) => write!(f, \"Parse error: {}\", err),\n        }\n    }\n}\n\nimpl error::Error for CliError {\n    fn description(&self) -> &str {\n        // Both underlying errors already impl `Error`, so we defer to their\n        // implementations.\n        match *self {\n            CliError::Io(ref err) => err.description(),\n            CliError::Parse(ref err) => err.description(),\n        }\n    }\n\n    fn cause(&self) -> Option<&error::Error> {\n        match *self {\n            // N.B. Both of these implicitly cast `err` from their concrete\n            // types (either `&io::Error` or `&num::ParseIntError`)\n            // to a trait object `&Error`. This works because both error types\n            // implement `Error`.\n            CliError::Io(ref err) => Some(err),\n            CliError::Parse(ref err) => Some(err),\n        }\n    }\n}\n```\n\nWe note that this is a very typical implementation of `Error`: match on your\ndifferent error types and satisfy the contracts defined for `description` and\n`cause`.\n\n## The `From` trait\n\nThe `std::convert::From` trait is\n[defined in the standard\nlibrary](../std/convert/trait.From.html):\n\n<span id=\"code-from-def\"></span>\n\n```rust\ntrait From<T> {\n    fn from(T) -> Self;\n}\n```\n\nDeliciously simple, yes? `From` is very useful because it gives us a generic\nway to talk about conversion *from* a particular type `T` to some other type\n(in this case, “some other type” is the subject of the impl, or `Self`).\nThe crux of `From` is the\n[set of implementations provided by the standard\nlibrary](../std/convert/trait.From.html).\n\nHere are a few simple examples demonstrating how `From` works:\n\n```rust\nlet string: String = From::from(\"foo\");\nlet bytes: Vec<u8> = From::from(\"foo\");\nlet cow: ::std::borrow::Cow<str> = From::from(\"foo\");\n```\n\nOK, so `From` is useful for converting between strings. But what about errors?\nIt turns out, there is one critical impl:\n\n```rust,ignore\nimpl<'a, E: Error + 'a> From<E> for Box<Error + 'a>\n```\n\nThis impl says that for *any* type that impls `Error`, we can convert it to a\ntrait object `Box<Error>`. This may not seem terribly surprising, but it is\nuseful in a generic context.\n\nRemember the two errors we were dealing with previously? Specifically,\n`io::Error` and `num::ParseIntError`. Since both impl `Error`, they work with\n`From`:\n\n```rust\nuse std::error::Error;\nuse std::fs;\nuse std::io;\nuse std::num;\n\n// We have to jump through some hoops to actually get error values.\nlet io_err: io::Error = io::Error::last_os_error();\nlet parse_err: num::ParseIntError = \"not a number\".parse::<i32>().unwrap_err();\n\n// OK, here are the conversions.\nlet err1: Box<Error> = From::from(io_err);\nlet err2: Box<Error> = From::from(parse_err);\n```\n\nThere is a really important pattern to recognize here. Both `err1` and `err2`\nhave the *same type*. This is because they are existentially quantified types,\nor trait objects. In particular, their underlying type is *erased* from the\ncompiler's knowledge, so it truly sees `err1` and `err2` as exactly the same.\nAdditionally, we constructed `err1` and `err2` using precisely the same\nfunction call: `From::from`. This is because `From::from` is overloaded on both\nits argument and its return type.\n\nThis pattern is important because it solves a problem we had earlier: it gives\nus a way to reliably convert errors to the same type using the same function.\n\nTime to revisit an old friend; the `try!` macro.\n\n## The real `try!` macro\n\nPreviously, we presented this definition of `try!`:\n\n```rust\nmacro_rules! try {\n    ($e:expr) => (match $e {\n        Ok(val) => val,\n        Err(err) => return Err(err),\n    });\n}\n```\n\nThis is not its real definition. Its real definition is\n[in the standard library](../std/macro.try!.html):\n\n<span id=\"code-try-def\"></span>\n\n```rust\nmacro_rules! try {\n    ($e:expr) => (match $e {\n        Ok(val) => val,\n        Err(err) => return Err(::std::convert::From::from(err)),\n    });\n}\n```\n\nThere's one tiny but powerful change: the error value is passed through\n`From::from`. This makes the `try!` macro a lot more powerful because it gives\nyou automatic type conversion for free.\n\nArmed with our more powerful `try!` macro, let's take a look at code we wrote\npreviously to read a file and convert its contents to an integer:\n\n```rust\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {\n    let mut file = try!(File::open(file_path).map_err(|e| e.to_string()));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents).map_err(|e| e.to_string()));\n    let n = try!(contents.trim().parse::<i32>().map_err(|e| e.to_string()));\n    Ok(2 * n)\n}\n```\n\nEarlier, we promised that we could get rid of the `map_err` calls. Indeed, all\nwe have to do is pick a type that `From` works with. As we saw in the previous\nsection, `From` has an impl that lets it convert any error type into a\n`Box<Error>`:\n\n```rust\nuse std::error::Error;\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, Box<Error>> {\n    let mut file = try!(File::open(file_path));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents));\n    let n = try!(contents.trim().parse::<i32>());\n    Ok(2 * n)\n}\n```\n\nWe are getting very close to ideal error handling. Our code has very little\noverhead as a result from error handling because the `try!` macro encapsulates\nthree things simultaneously:\n\n1. Case analysis.\n2. Control flow.\n3. Error type conversion.\n\nWhen all three things are combined, we get code that is unencumbered by\ncombinators, calls to `unwrap` or case analysis.\n\nThere's one little nit left: the `Box<Error>` type is *opaque*. If we\nreturn a `Box<Error>` to the caller, the caller can't (easily) inspect\nunderlying error type. The situation is certainly better than `String`\nbecause the caller can call methods like\n[`description`](../std/error/trait.Error.html#tymethod.description)\nand [`cause`](../std/error/trait.Error.html#method.cause), but the\nlimitation remains: `Box<Error>` is opaque. (N.B. This isn't entirely\ntrue because Rust does have runtime reflection, which is useful in\nsome scenarios that are [beyond the scope of this\nsection](https://crates.io/crates/error).)\n\nIt's time to revisit our custom `CliError` type and tie everything together.\n\n## Composing custom error types\n\nIn the last section, we looked at the real `try!` macro and how it does\nautomatic type conversion for us by calling `From::from` on the error value.\nIn particular, we converted errors to `Box<Error>`, which works, but the type\nis opaque to callers.\n\nTo fix this, we use the same remedy that we're already familiar with: a custom\nerror type. Once again, here is the code that reads the contents of a file and\nconverts it to an integer:\n\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\nuse std::num;\nuse std::path::Path;\n\n// We derive `Debug` because all types should probably derive `Debug`.\n// This gives us a reasonable human readable description of `CliError` values.\n#[derive(Debug)]\nenum CliError {\n    Io(io::Error),\n    Parse(num::ParseIntError),\n}\n\nfn file_double_verbose<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {\n    let mut file = try!(File::open(file_path).map_err(CliError::Io));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents).map_err(CliError::Io));\n    let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse));\n    Ok(2 * n)\n}\n```\n\nNotice that we still have the calls to `map_err`. Why? Well, recall the\ndefinitions of [`try!`](#code-try-def) and [`From`](#code-from-def). The\nproblem is that there is no `From` impl that allows us to convert from error\ntypes like `io::Error` and `num::ParseIntError` to our own custom `CliError`.\nOf course, it is easy to fix this! Since we defined `CliError`, we can impl\n`From` with it:\n\n```rust\n# #[derive(Debug)]\n# enum CliError { Io(io::Error), Parse(num::ParseIntError) }\nuse std::io;\nuse std::num;\n\nimpl From<io::Error> for CliError {\n    fn from(err: io::Error) -> CliError {\n        CliError::Io(err)\n    }\n}\n\nimpl From<num::ParseIntError> for CliError {\n    fn from(err: num::ParseIntError) -> CliError {\n        CliError::Parse(err)\n    }\n}\n```\n\nAll these impls are doing is teaching `From` how to create a `CliError` from\nother error types. In our case, construction is as simple as invoking the\ncorresponding value constructor. Indeed, it is *typically* this easy.\n\nWe can finally rewrite `file_double`:\n\n```rust\n# use std::io;\n# use std::num;\n# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) }\n# impl From<io::Error> for CliError {\n#     fn from(err: io::Error) -> CliError { CliError::Io(err) }\n# }\n# impl From<num::ParseIntError> for CliError {\n#     fn from(err: num::ParseIntError) -> CliError { CliError::Parse(err) }\n# }\n\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {\n    let mut file = try!(File::open(file_path));\n    let mut contents = String::new();\n    try!(file.read_to_string(&mut contents));\n    let n: i32 = try!(contents.trim().parse());\n    Ok(2 * n)\n}\n```\n\nThe only thing we did here was remove the calls to `map_err`. They are no\nlonger needed because the `try!` macro invokes `From::from` on the error value.\nThis works because we've provided `From` impls for all the error types that\ncould appear.\n\nIf we modified our `file_double` function to perform some other operation, say,\nconvert a string to a float, then we'd need to add a new variant to our error\ntype:\n\n```rust\nuse std::io;\nuse std::num;\n\nenum CliError {\n    Io(io::Error),\n    ParseInt(num::ParseIntError),\n    ParseFloat(num::ParseFloatError),\n}\n```\n\nAnd add a new `From` impl:\n\n```rust\n# enum CliError {\n#     Io(::std::io::Error),\n#     ParseInt(num::ParseIntError),\n#     ParseFloat(num::ParseFloatError),\n# }\n\nuse std::num;\n\nimpl From<num::ParseFloatError> for CliError {\n    fn from(err: num::ParseFloatError) -> CliError {\n        CliError::ParseFloat(err)\n    }\n}\n```\n\nAnd that's it!\n\n## Advice for library writers\n\nIf your library needs to report custom errors, then you should\nprobably define your own error type. It's up to you whether or not to\nexpose its representation (like\n[`ErrorKind`](../std/io/enum.ErrorKind.html)) or keep it hidden (like\n[`ParseIntError`](../std/num/struct.ParseIntError.html)). Regardless\nof how you do it, it's usually good practice to at least provide some\ninformation about the error beyond its `String`\nrepresentation. But certainly, this will vary depending on use cases.\n\nAt a minimum, you should probably implement the\n[`Error`](../std/error/trait.Error.html)\ntrait. This will give users of your library some minimum flexibility for\n[composing errors](#the-real-try-macro). Implementing the `Error` trait also\nmeans that users are guaranteed the ability to obtain a string representation\nof an error (because it requires impls for both `fmt::Debug` and\n`fmt::Display`).\n\nBeyond that, it can also be useful to provide implementations of `From` on your\nerror types. This allows you (the library author) and your users to\n[compose more detailed errors](#composing-custom-error-types). For example,\n[`csv::Error`](http://burntsushi.net/rustdoc/csv/enum.Error.html)\nprovides `From` impls for both `io::Error` and `byteorder::Error`.\n\nFinally, depending on your tastes, you may also want to define a\n[`Result` type alias](#the-result-type-alias-idiom), particularly if your\nlibrary defines a single error type. This is used in the standard library\nfor [`io::Result`](../std/io/type.Result.html)\nand [`fmt::Result`](../std/fmt/type.Result.html).\n\n# Case study: A program to read population data\n\nThis section was long, and depending on your background, it might be\nrather dense. While there is plenty of example code to go along with\nthe prose, most of it was specifically designed to be pedagogical. So,\nwe're going to do something new: a case study.\n\nFor this, we're going to build up a command line program that lets you\nquery world population data. The objective is simple: you give it a location\nand it will tell you the population. Despite the simplicity, there is a lot\nthat can go wrong!\n\nThe data we'll be using comes from the [Data Science\nToolkit][11]. I've prepared some data from it for this exercise. You\ncan either grab the [world population data][12] (41MB gzip compressed,\n145MB uncompressed) or only the [US population data][13] (2.2MB gzip\ncompressed, 7.2MB uncompressed).\n\nUp until now, we've kept the code limited to Rust's standard library. For a real\ntask like this though, we'll want to at least use something to parse CSV data,\nparse the program arguments and decode that stuff into Rust types automatically. For that, we'll use the\n[`csv`](https://crates.io/crates/csv),\nand [`rustc-serialize`](https://crates.io/crates/rustc-serialize) crates.\n\n## Initial setup\n\nWe're not going to spend a lot of time on setting up a project with\nCargo because it is already covered well in [the Cargo\nsection](getting-started.html#hello-cargo) and [Cargo's documentation][14].\n\nTo get started from scratch, run `cargo new --bin city-pop` and make sure your\n`Cargo.toml` looks something like this:\n\n```text\n[package]\nname = \"city-pop\"\nversion = \"0.1.0\"\nauthors = [\"Andrew Gallant <jamslam@gmail.com>\"]\n\n[[bin]]\nname = \"city-pop\"\n\n[dependencies]\ncsv = \"0.*\"\nrustc-serialize = \"0.*\"\ngetopts = \"0.*\"\n```\n\nYou should already be able to run:\n\n```text\ncargo build --release\n./target/release/city-pop\n# Outputs: Hello, world!\n```\n\n## Argument parsing\n\nLet's get argument parsing out of the way. We won't go into too much\ndetail on Getopts, but there is [some good documentation][15]\ndescribing it. The short story is that Getopts generates an argument\nparser and a help message from a vector of options (The fact that it\nis a vector is hidden behind a struct and a set of methods). Once the\nparsing is done, the parser returns a struct that records matches\nfor defined options, and remaining \"free\" arguments.\nFrom there, we can get information about the flags, for\ninstance, whether they were passed in, and what arguments they\nhad. Here's our program with the appropriate `extern crate`\nstatements, and the basic argument setup for Getopts:\n\n```rust,ignore\nextern crate getopts;\nextern crate rustc_serialize;\n\nuse getopts::Options;\nuse std::env;\n\nfn print_usage(program: &str, opts: Options) {\n    println!(\"{}\", opts.usage(&format!(\"Usage: {} [options] <data-path> <city>\", program)));\n}\n\nfn main() {\n    let args: Vec<String> = env::args().collect();\n    let program = &args[0];\n\n    let mut opts = Options::new();\n    opts.optflag(\"h\", \"help\", \"Show this usage message.\");\n\n    let matches = match opts.parse(&args[1..]) {\n        Ok(m)  => { m }\n        Err(e) => { panic!(e.to_string()) }\n    };\n    if matches.opt_present(\"h\") {\n        print_usage(&program, opts);\n        return;\n    }\n    let data_path = &matches.free[0];\n    let city: &str = &matches.free[1];\n\n    // Do stuff with information\n}\n```\n\nFirst, we get a vector of the arguments passed into our program. We\nthen store the first one, knowing that it is our program's name. Once\nthat's done, we set up our argument flags, in this case a simplistic\nhelp message flag. Once we have the argument flags set up, we use\n`Options.parse` to parse the argument vector (starting from index one,\nbecause index 0 is the program name). If this was successful, we\nassign matches to the parsed object, if not, we panic. Once past that,\nwe test if the user passed in the help flag, and if so print the usage\nmessage. The option help messages are constructed by Getopts, so all\nwe have to do to print the usage message is tell it what we want it to\nprint for the program name and template. If the user has not passed in\nthe help flag, we assign the proper variables to their corresponding\narguments.\n\n## Writing the logic\n\nWe all write code differently, but error handling is usually the last thing we\nwant to think about. This isn't great for the overall design of a program, but\nit can be useful for rapid prototyping. Because Rust forces us to be explicit\nabout error handling (by making us call `unwrap`), it is easy to see which\nparts of our program can cause errors.\n\nIn this case study, the logic is really simple. All we need to do is parse the\nCSV data given to us and print out a field in matching rows. Let's do it. (Make\nsure to add `extern crate csv;` to the top of your file.)\n\n```rust,ignore\nuse std::fs::File;\n\n// This struct represents the data in each row of the CSV file.\n// Type based decoding absolves us of a lot of the nitty gritty error\n// handling, like parsing strings as integers or floats.\n#[derive(Debug, RustcDecodable)]\nstruct Row {\n    country: String,\n    city: String,\n    accent_city: String,\n    region: String,\n\n    // Not every row has data for the population, latitude or longitude!\n    // So we express them as `Option` types, which admits the possibility of\n    // absence. The CSV parser will fill in the correct value for us.\n    population: Option<u64>,\n    latitude: Option<f64>,\n    longitude: Option<f64>,\n}\n\nfn print_usage(program: &str, opts: Options) {\n    println!(\"{}\", opts.usage(&format!(\"Usage: {} [options] <data-path> <city>\", program)));\n}\n\nfn main() {\n    let args: Vec<String> = env::args().collect();\n    let program = &args[0];\n\n    let mut opts = Options::new();\n    opts.optflag(\"h\", \"help\", \"Show this usage message.\");\n\n    let matches = match opts.parse(&args[1..]) {\n        Ok(m)  => { m }\n        Err(e) => { panic!(e.to_string()) }\n    };\n\n    if matches.opt_present(\"h\") {\n        print_usage(&program, opts);\n        return;\n    }\n\n    let data_path = &matches.free[0];\n    let city: &str = &matches.free[1];\n\n    let file = File::open(data_path).unwrap();\n    let mut rdr = csv::Reader::from_reader(file);\n\n    for row in rdr.decode::<Row>() {\n        let row = row.unwrap();\n\n        if row.city == city {\n            println!(\"{}, {}: {:?}\",\n                row.city, row.country,\n                row.population.expect(\"population count\"));\n        }\n    }\n}\n```\n\nLet's outline the errors. We can start with the obvious: the three places that\n`unwrap` is called:\n\n1. [`File::open`](../std/fs/struct.File.html#method.open)\n   can return an\n   [`io::Error`](../std/io/struct.Error.html).\n2. [`csv::Reader::decode`](http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.decode)\n   decodes one record at a time, and\n   [decoding a\n   record](http://burntsushi.net/rustdoc/csv/struct.DecodedRecords.html)\n   (look at the `Item` associated type on the `Iterator` impl)\n   can produce a\n   [`csv::Error`](http://burntsushi.net/rustdoc/csv/enum.Error.html).\n3. If `row.population` is `None`, then calling `expect` will panic.\n\nAre there any others? What if we can't find a matching city? Tools like `grep`\nwill return an error code, so we probably should too. So we have logic errors\nspecific to our problem, IO errors and CSV parsing errors. We're going to\nexplore two different ways to approach handling these errors.\n\nI'd like to start with `Box<Error>`. Later, we'll see how defining our own\nerror type can be useful.\n\n## Error handling with `Box<Error>`\n\n`Box<Error>` is nice because it *just works*. You don't need to define your own\nerror types and you don't need any `From` implementations. The downside is that\nsince `Box<Error>` is a trait object, it *erases the type*, which means the\ncompiler can no longer reason about its underlying type.\n\n[Previously](#the-limits-of-combinators) we started refactoring our code by\nchanging the type of our function from `T` to `Result<T, OurErrorType>`. In\nthis case, `OurErrorType` is only `Box<Error>`. But what's `T`? And can we add\na return type to `main`?\n\nThe answer to the second question is no, we can't. That means we'll need to\nwrite a new function. But what is `T`? The simplest thing we can do is to\nreturn a list of matching `Row` values as a `Vec<Row>`. (Better code would\nreturn an iterator, but that is left as an exercise to the reader.)\n\nLet's refactor our code into its own function, but keep the calls to `unwrap`.\nNote that we opt to handle the possibility of a missing population count by\nsimply ignoring that row.\n\n```rust,ignore\nuse std::path::Path;\n\nstruct Row {\n    // unchanged\n}\n\nstruct PopulationCount {\n    city: String,\n    country: String,\n    // This is no longer an `Option` because values of this type are only\n    // constructed if they have a population count.\n    count: u64,\n}\n\nfn print_usage(program: &str, opts: Options) {\n    println!(\"{}\", opts.usage(&format!(\"Usage: {} [options] <data-path> <city>\", program)));\n}\n\nfn search<P: AsRef<Path>>(file_path: P, city: &str) -> Vec<PopulationCount> {\n    let mut found = vec![];\n    let file = File::open(file_path).unwrap();\n    let mut rdr = csv::Reader::from_reader(file);\n    for row in rdr.decode::<Row>() {\n        let row = row.unwrap();\n        match row.population {\n            None => { } // skip it\n            Some(count) => if row.city == city {\n                found.push(PopulationCount {\n                    city: row.city,\n                    country: row.country,\n                    count: count,\n                });\n            },\n        }\n    }\n    found\n}\n\nfn main() {\n    let args: Vec<String> = env::args().collect();\n    let program = &args[0];\n\n    let mut opts = Options::new();\n    opts.optflag(\"h\", \"help\", \"Show this usage message.\");\n\n    let matches = match opts.parse(&args[1..]) {\n        Ok(m)  => { m }\n        Err(e) => { panic!(e.to_string()) }\n    };\n\n    if matches.opt_present(\"h\") {\n        print_usage(&program, opts);\n        return;\n    }\n\n    let data_path = &matches.free[0];\n    let city: &str = &matches.free[1];\n\n    for pop in search(data_path, city) {\n        println!(\"{}, {}: {:?}\", pop.city, pop.country, pop.count);\n    }\n}\n\n```\n\nWhile we got rid of one use of `expect` (which is a nicer variant of `unwrap`),\nwe still should handle the absence of any search results.\n\nTo convert this to proper error handling, we need to do the following:\n\n1. Change the return type of `search` to be `Result<Vec<PopulationCount>,\n   Box<Error>>`.\n2. Use the [`try!` macro](#code-try-def) so that errors are returned to the\n   caller instead of panicking the program.\n3. Handle the error in `main`.\n\nLet's try it:\n\n```rust,ignore\nuse std::error::Error;\n\n// The rest of the code before this is unchanged\n\nfn search<P: AsRef<Path>>\n         (file_path: P, city: &str)\n         -> Result<Vec<PopulationCount>, Box<Error>> {\n    let mut found = vec![];\n    let file = try!(File::open(file_path));\n    let mut rdr = csv::Reader::from_reader(file);\n    for row in rdr.decode::<Row>() {\n        let row = try!(row);\n        match row.population {\n            None => { } // skip it\n            Some(count) => if row.city == city {\n                found.push(PopulationCount {\n                    city: row.city,\n                    country: row.country,\n                    count: count,\n                });\n            },\n        }\n    }\n    if found.is_empty() {\n        Err(From::from(\"No matching cities with a population were found.\"))\n    } else {\n        Ok(found)\n    }\n}\n```\n\nInstead of `x.unwrap()`, we now have `try!(x)`. Since our function returns a\n`Result<T, E>`, the `try!` macro will return early from the function if an\nerror occurs.\n\nAt the end of `search` we also convert a plain string to an error type \nby using the [corresponding `From` impls](../std/convert/trait.From.html):\n\n```rust,ignore\n// We are making use of this impl in the code above, since we call `From::from`\n// on a `&'static str`.\nimpl<'a> From<&'a str> for Box<Error>\n\n// But this is also useful when you need to allocate a new string for an\n// error message, usually with `format!`.\nimpl From<String> for Box<Error>\n```\n\nSince `search` now returns a `Result<T, E>`, `main` should use case analysis\nwhen calling `search`:\n\n```rust,ignore\n...\n    match search(data_path, city) {\n        Ok(pops) => {\n            for pop in pops {\n                println!(\"{}, {}: {:?}\", pop.city, pop.country, pop.count);\n            }\n        }\n        Err(err) => println!(\"{}\", err)\n    }\n...\n```\n\nNow that we've seen how to do proper error handling with `Box<Error>`, let's\ntry a different approach with our own custom error type. But first, let's take\na quick break from error handling and add support for reading from `stdin`.\n\n## Reading from stdin\n\nIn our program, we accept a single file for input and do one pass over the\ndata. This means we probably should be able to accept input on stdin. But maybe\nwe like the current format too—so let's have both!\n\nAdding support for stdin is actually quite easy. There are only three things we\nhave to do:\n\n1. Tweak the program arguments so that a single parameter—the\n   city—can be accepted while the population data is read from stdin.\n2. Modify the program so that an option `-f` can take the file, if it\n    is not passed into stdin.\n3. Modify the `search` function to take an *optional* file path. When `None`,\n   it should know to read from stdin.\n\nFirst, here's the new usage:\n\n```rust,ignore\nfn print_usage(program: &str, opts: Options) {\n    println!(\"{}\", opts.usage(&format!(\"Usage: {} [options] <city>\", program)));\n}\n```\nOf course we need to adapt the argument handling code:\n\n```rust,ignore\n...\n    let mut opts = Options::new();\n    opts.optopt(\"f\", \"file\", \"Choose an input file, instead of using STDIN.\", \"NAME\");\n    opts.optflag(\"h\", \"help\", \"Show this usage message.\");\n    ...\n    let data_path = matches.opt_str(\"f\");\n\n    let city = if !matches.free.is_empty() {\n        &matches.free[0]\n    } else {\n        print_usage(&program, opts);\n        return;\n    };\n\n    match search(&data_path, city) {\n        Ok(pops) => {\n            for pop in pops {\n                println!(\"{}, {}: {:?}\", pop.city, pop.country, pop.count);\n            }\n        }\n        Err(err) => println!(\"{}\", err)\n    }\n...\n```\n\nWe've made the user experience a bit nicer by showing the usage message,\ninstead of a panic from an out-of-bounds index, when `city`, the\nremaining free argument, is not present.\n\nModifying `search` is slightly trickier. The `csv` crate can build a\nparser out of\n[any type that implements `io::Read`](http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.from_reader).\nBut how can we use the same code over both types? There's actually a\ncouple ways we could go about this. One way is to write `search` such\nthat it is generic on some type parameter `R` that satisfies\n`io::Read`. Another way is to use trait objects:\n\n```rust,ignore\nuse std::io;\n\n// The rest of the code before this is unchanged\n\nfn search<P: AsRef<Path>>\n         (file_path: &Option<P>, city: &str)\n         -> Result<Vec<PopulationCount>, Box<Error>> {\n    let mut found = vec![];\n    let input: Box<io::Read> = match *file_path {\n        None => Box::new(io::stdin()),\n        Some(ref file_path) => Box::new(try!(File::open(file_path))),\n    };\n    let mut rdr = csv::Reader::from_reader(input);\n    // The rest remains unchanged!\n}\n```\n\n## Error handling with a custom type\n\nPreviously, we learned how to\n[compose errors using a custom error type](#composing-custom-error-types).\nWe did this by defining our error type as an `enum` and implementing `Error`\nand `From`.\n\nSince we have three distinct errors (IO, CSV parsing and not found), let's\ndefine an `enum` with three variants:\n\n```rust,ignore\n#[derive(Debug)]\nenum CliError {\n    Io(io::Error),\n    Csv(csv::Error),\n    NotFound,\n}\n```\n\nAnd now for impls on `Display` and `Error`:\n\n```rust,ignore\nuse std::fmt;\n\nimpl fmt::Display for CliError {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            CliError::Io(ref err) => err.fmt(f),\n            CliError::Csv(ref err) => err.fmt(f),\n            CliError::NotFound => write!(f, \"No matching cities with a \\\n                                             population were found.\"),\n        }\n    }\n}\n\nimpl Error for CliError {\n    fn description(&self) -> &str {\n        match *self {\n            CliError::Io(ref err) => err.description(),\n            CliError::Csv(ref err) => err.description(),\n            CliError::NotFound => \"not found\",\n        }\n    }\n\n    fn cause(&self) -> Option<&Error> {\n        match *self {\n            CliError::Io(ref err) => Some(err),\n            CliError::Csv(ref err) => Some(err),\n            // Our custom error doesn't have an underlying cause,\n            // but we could modify it so that it does.\n            CliError::NotFound => None,\n        }\n    }\n}\n```\n\nBefore we can use our `CliError` type in our `search` function, we need to\nprovide a couple `From` impls. How do we know which impls to provide? Well,\nwe'll need to convert from both `io::Error` and `csv::Error` to `CliError`.\nThose are the only external errors, so we'll only need two `From` impls for\nnow:\n\n```rust,ignore\nimpl From<io::Error> for CliError {\n    fn from(err: io::Error) -> CliError {\n        CliError::Io(err)\n    }\n}\n\nimpl From<csv::Error> for CliError {\n    fn from(err: csv::Error) -> CliError {\n        CliError::Csv(err)\n    }\n}\n```\n\nThe `From` impls are important because of how\n[`try!` is defined](#code-try-def). In particular, if an error occurs,\n`From::from` is called on the error, which in this case, will convert it to our\nown error type `CliError`.\n\nWith the `From` impls done, we only need to make two small tweaks to our\n`search` function: the return type and the “not found” error. Here it is in\nfull:\n\n```rust,ignore\nfn search<P: AsRef<Path>>\n         (file_path: &Option<P>, city: &str)\n         -> Result<Vec<PopulationCount>, CliError> {\n    let mut found = vec![];\n    let input: Box<io::Read> = match *file_path {\n        None => Box::new(io::stdin()),\n        Some(ref file_path) => Box::new(try!(File::open(file_path))),\n    };\n    let mut rdr = csv::Reader::from_reader(input);\n    for row in rdr.decode::<Row>() {\n        let row = try!(row);\n        match row.population {\n            None => { } // skip it\n            Some(count) => if row.city == city {\n                found.push(PopulationCount {\n                    city: row.city,\n                    country: row.country,\n                    count: count,\n                });\n            },\n        }\n    }\n    if found.is_empty() {\n        Err(CliError::NotFound)\n    } else {\n        Ok(found)\n    }\n}\n```\n\nNo other changes are necessary.\n\n## Adding functionality\n\nWriting generic code is great, because generalizing stuff is cool, and\nit can then be useful later. But sometimes, the juice isn't worth the\nsqueeze. Look at what we just did in the previous step:\n\n1. Defined a new error type.\n2. Added impls for `Error`, `Display` and two for `From`.\n\nThe big downside here is that our program didn't improve a whole lot.\nThere is quite a bit of overhead to representing errors with `enum`s,\nespecially in short programs like this.\n\n*One* useful aspect of using a custom error type like we've done here is that\nthe `main` function can now choose to handle errors differently. Previously,\nwith `Box<Error>`, it didn't have much of a choice: just print the message.\nWe're still doing that here, but what if we wanted to, say, add a `--quiet`\nflag? The `--quiet` flag should silence any verbose output.\n\nRight now, if the program doesn't find a match, it will output a message saying\nso. This can be a little clumsy, especially if you intend for the program to\nbe used in shell scripts.\n\nSo let's start by adding the flags. Like before, we need to tweak the usage\nstring and add a flag to the Option variable. Once we've done that, Getopts does the rest:\n\n```rust,ignore\n...\n    let mut opts = Options::new();\n    opts.optopt(\"f\", \"file\", \"Choose an input file, instead of using STDIN.\", \"NAME\");\n    opts.optflag(\"h\", \"help\", \"Show this usage message.\");\n    opts.optflag(\"q\", \"quiet\", \"Silences errors and warnings.\");\n...\n```\n\nNow we only need to implement our “quiet” functionality. This requires us to\ntweak the case analysis in `main`:\n\n```rust,ignore\nuse std::process;\n...\n    match search(&data_path, city) {\n        Err(CliError::NotFound) if matches.opt_present(\"q\") => process::exit(1),\n        Err(err) => panic!(\"{}\", err),\n        Ok(pops) => for pop in pops {\n            println!(\"{}, {}: {:?}\", pop.city, pop.country, pop.count);\n        }\n    }\n...\n```\n\nCertainly, we don't want to be quiet if there was an IO error or if the data\nfailed to parse. Therefore, we use case analysis to check if the error type is\n`NotFound` *and* if `--quiet` has been enabled. If the search failed, we still\nquit with an exit code (following `grep`'s convention).\n\nIf we had stuck with `Box<Error>`, then it would be pretty tricky to implement\nthe `--quiet` functionality.\n\nThis pretty much sums up our case study. From here, you should be ready to go\nout into the world and write your own programs and libraries with proper error\nhandling.\n\n# The Short Story\n\nSince this section is long, it is useful to have a quick summary for error\nhandling in Rust. These are some good “rules of thumb.\" They are emphatically\n*not* commandments. There are probably good reasons to break every one of these\nheuristics!\n\n* If you're writing short example code that would be overburdened by error\n  handling, it's probably fine to use `unwrap` (whether that's\n  [`Result::unwrap`](../std/result/enum.Result.html#method.unwrap),\n  [`Option::unwrap`](../std/option/enum.Option.html#method.unwrap)\n  or preferably\n  [`Option::expect`](../std/option/enum.Option.html#method.expect)).\n  Consumers of your code should know to use proper error handling. (If they\n  don't, send them here!)\n* If you're writing a quick 'n' dirty program, don't feel ashamed if you use\n  `unwrap`. Be warned: if it winds up in someone else's hands, don't be\n  surprised if they are agitated by poor error messages!\n* If you're writing a quick 'n' dirty program and feel ashamed about panicking\n  anyway, then use either a `String` or a `Box<Error>` for your\n  error type.\n* Otherwise, in a program, define your own error types with appropriate\n  [`From`](../std/convert/trait.From.html)\n  and\n  [`Error`](../std/error/trait.Error.html)\n  impls to make the [`try!`](../std/macro.try!.html)\n  macro more ergonomic.\n* If you're writing a library and your code can produce errors, define your own\n  error type and implement the\n  [`std::error::Error`](../std/error/trait.Error.html)\n  trait. Where appropriate, implement\n  [`From`](../std/convert/trait.From.html) to make both\n  your library code and the caller's code easier to write. (Because of Rust's\n  coherence rules, callers will not be able to impl `From` on your error type,\n  so your library should do it.)\n* Learn the combinators defined on\n  [`Option`](../std/option/enum.Option.html)\n  and\n  [`Result`](../std/result/enum.Result.html).\n  Using them exclusively can be a bit tiring at times, but I've personally\n  found a healthy mix of `try!` and combinators to be quite appealing.\n  `and_then`, `map` and `unwrap_or` are my favorites.\n\n[1]: ../book/patterns.html\n[2]: ../std/option/enum.Option.html#method.map\n[3]: ../std/option/enum.Option.html#method.unwrap_or\n[4]: ../std/option/enum.Option.html#method.unwrap_or_else\n[5]: ../std/option/enum.Option.html\n[6]: ../std/result/index.html\n[7]: ../std/result/enum.Result.html#method.unwrap\n[8]: ../std/fmt/trait.Debug.html\n[9]: ../std/primitive.str.html#method.parse\n[10]: ../book/associated-types.html\n[11]: https://github.com/petewarden/dstkdata\n[12]: http://burntsushi.net/stuff/worldcitiespop.csv.gz\n[13]: http://burntsushi.net/stuff/uscitiespop.csv.gz\n[14]: http://doc.crates.io/guide.html\n[15]: http://doc.rust-lang.org/getopts/getopts/index.html\n"
  },
  {
    "path": "trpl/ffi.md",
    "content": "% Foreign Function Interface\n\n# Introduction\n\nThis guide will use the [snappy](https://github.com/google/snappy)\ncompression/decompression library as an introduction to writing bindings for\nforeign code. Rust is currently unable to call directly into a C++ library, but\nsnappy includes a C interface (documented in\n[`snappy-c.h`](https://github.com/google/snappy/blob/master/snappy-c.h)).\n\n## A note about libc\n\nMany of these examples use [the `libc` crate][libc], which provides various\ntype definitions for C types, among other things. If you’re trying these\nexamples yourself, you’ll need to add `libc` to your `Cargo.toml`:\n\n```toml\n[dependencies]\nlibc = \"0.2.0\"\n```\n\n[libc]: https://crates.io/crates/libc\n\nand add `extern crate libc;` to your crate root.\n\n## Calling foreign functions\n\nThe following is a minimal example of calling a foreign function which will\ncompile if snappy is installed:\n\n```rust,no_run\n# #![feature(libc)]\nextern crate libc;\nuse libc::size_t;\n\n#[link(name = \"snappy\")]\nextern {\n    fn snappy_max_compressed_length(source_length: size_t) -> size_t;\n}\n\nfn main() {\n    let x = unsafe { snappy_max_compressed_length(100) };\n    println!(\"max compressed length of a 100 byte buffer: {}\", x);\n}\n```\n\nThe `extern` block is a list of function signatures in a foreign library, in\nthis case with the platform's C ABI. The `#[link(...)]` attribute is used to\ninstruct the linker to link against the snappy library so the symbols are\nresolved.\n\nForeign functions are assumed to be unsafe so calls to them need to be wrapped\nwith `unsafe {}` as a promise to the compiler that everything contained within\ntruly is safe. C libraries often expose interfaces that aren't thread-safe, and\nalmost any function that takes a pointer argument isn't valid for all possible\ninputs since the pointer could be dangling, and raw pointers fall outside of\nRust's safe memory model.\n\nWhen declaring the argument types to a foreign function, the Rust compiler can\nnot check if the declaration is correct, so specifying it correctly is part of\nkeeping the binding correct at runtime.\n\nThe `extern` block can be extended to cover the entire snappy API:\n\n```rust,no_run\n# #![feature(libc)]\nextern crate libc;\nuse libc::{c_int, size_t};\n\n#[link(name = \"snappy\")]\nextern {\n    fn snappy_compress(input: *const u8,\n                       input_length: size_t,\n                       compressed: *mut u8,\n                       compressed_length: *mut size_t) -> c_int;\n    fn snappy_uncompress(compressed: *const u8,\n                         compressed_length: size_t,\n                         uncompressed: *mut u8,\n                         uncompressed_length: *mut size_t) -> c_int;\n    fn snappy_max_compressed_length(source_length: size_t) -> size_t;\n    fn snappy_uncompressed_length(compressed: *const u8,\n                                  compressed_length: size_t,\n                                  result: *mut size_t) -> c_int;\n    fn snappy_validate_compressed_buffer(compressed: *const u8,\n                                         compressed_length: size_t) -> c_int;\n}\n# fn main() {}\n```\n\n# Creating a safe interface\n\nThe raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts\nlike vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe\ninternal details.\n\nWrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust\nvectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The\nlength is number of elements currently contained, and the capacity is the total size in elements of\nthe allocated memory. The length is less than or equal to the capacity.\n\n```rust\n# #![feature(libc)]\n# extern crate libc;\n# use libc::{c_int, size_t};\n# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 }\n# fn main() {}\npub fn validate_compressed_buffer(src: &[u8]) -> bool {\n    unsafe {\n        snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0\n    }\n}\n```\n\nThe `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the\nguarantee that calling it is safe for all inputs by leaving off `unsafe` from the function\nsignature.\n\nThe `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be\nallocated to hold the output too.\n\nThe `snappy_max_compressed_length` function can be used to allocate a vector with the maximum\nrequired capacity to hold the compressed output. The vector can then be passed to the\n`snappy_compress` function as an output parameter. An output parameter is also passed to retrieve\nthe true length after compression for setting the length.\n\n```rust\n# #![feature(libc)]\n# extern crate libc;\n# use libc::{size_t, c_int};\n# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8,\n#                           d: *mut size_t) -> c_int { 0 }\n# unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a }\n# fn main() {}\npub fn compress(src: &[u8]) -> Vec<u8> {\n    unsafe {\n        let srclen = src.len() as size_t;\n        let psrc = src.as_ptr();\n\n        let mut dstlen = snappy_max_compressed_length(srclen);\n        let mut dst = Vec::with_capacity(dstlen as usize);\n        let pdst = dst.as_mut_ptr();\n\n        snappy_compress(psrc, srclen, pdst, &mut dstlen);\n        dst.set_len(dstlen as usize);\n        dst\n    }\n}\n```\n\nDecompression is similar, because snappy stores the uncompressed size as part of the compression\nformat and `snappy_uncompressed_length` will retrieve the exact buffer size required.\n\n```rust\n# #![feature(libc)]\n# extern crate libc;\n# use libc::{size_t, c_int};\n# unsafe fn snappy_uncompress(compressed: *const u8,\n#                             compressed_length: size_t,\n#                             uncompressed: *mut u8,\n#                             uncompressed_length: *mut size_t) -> c_int { 0 }\n# unsafe fn snappy_uncompressed_length(compressed: *const u8,\n#                                      compressed_length: size_t,\n#                                      result: *mut size_t) -> c_int { 0 }\n# fn main() {}\npub fn uncompress(src: &[u8]) -> Option<Vec<u8>> {\n    unsafe {\n        let srclen = src.len() as size_t;\n        let psrc = src.as_ptr();\n\n        let mut dstlen: size_t = 0;\n        snappy_uncompressed_length(psrc, srclen, &mut dstlen);\n\n        let mut dst = Vec::with_capacity(dstlen as usize);\n        let pdst = dst.as_mut_ptr();\n\n        if snappy_uncompress(psrc, srclen, pdst, &mut dstlen) == 0 {\n            dst.set_len(dstlen as usize);\n            Some(dst)\n        } else {\n            None // SNAPPY_INVALID_INPUT\n        }\n    }\n}\n```\n\nThen, we can add some tests to show how to use them.\n\n```rust\n# #![feature(libc)]\n# extern crate libc;\n# use libc::{c_int, size_t};\n# unsafe fn snappy_compress(input: *const u8,\n#                           input_length: size_t,\n#                           compressed: *mut u8,\n#                           compressed_length: *mut size_t)\n#                           -> c_int { 0 }\n# unsafe fn snappy_uncompress(compressed: *const u8,\n#                             compressed_length: size_t,\n#                             uncompressed: *mut u8,\n#                             uncompressed_length: *mut size_t)\n#                             -> c_int { 0 }\n# unsafe fn snappy_max_compressed_length(source_length: size_t) -> size_t { 0 }\n# unsafe fn snappy_uncompressed_length(compressed: *const u8,\n#                                      compressed_length: size_t,\n#                                      result: *mut size_t)\n#                                      -> c_int { 0 }\n# unsafe fn snappy_validate_compressed_buffer(compressed: *const u8,\n#                                             compressed_length: size_t)\n#                                             -> c_int { 0 }\n# fn main() { }\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn valid() {\n        let d = vec![0xde, 0xad, 0xd0, 0x0d];\n        let c: &[u8] = &compress(&d);\n        assert!(validate_compressed_buffer(c));\n        assert!(uncompress(c) == Some(d));\n    }\n\n    #[test]\n    fn invalid() {\n        let d = vec![0, 0, 0, 0];\n        assert!(!validate_compressed_buffer(&d));\n        assert!(uncompress(&d).is_none());\n    }\n\n    #[test]\n    fn empty() {\n        let d = vec![];\n        assert!(!validate_compressed_buffer(&d));\n        assert!(uncompress(&d).is_none());\n        let c = compress(&d);\n        assert!(validate_compressed_buffer(&c));\n        assert!(uncompress(&c) == Some(d));\n    }\n}\n```\n\n# Destructors\n\nForeign libraries often hand off ownership of resources to the calling code.\nWhen this occurs, we must use Rust's destructors to provide safety and guarantee\nthe release of these resources (especially in the case of panic).\n\nFor more about destructors, see the [Drop trait](../std/ops/trait.Drop.html).\n\n# Callbacks from C code to Rust functions\n\nSome external libraries require the usage of callbacks to report back their\ncurrent state or intermediate data to the caller.\nIt is possible to pass functions defined in Rust to an external library.\nThe requirement for this is that the callback function is marked as `extern`\nwith the correct calling convention to make it callable from C code.\n\nThe callback function can then be sent through a registration call\nto the C library and afterwards be invoked from there.\n\nA basic example is:\n\nRust code:\n\n```rust,no_run\nextern fn callback(a: i32) {\n    println!(\"I'm called from C with value {0}\", a);\n}\n\n#[link(name = \"extlib\")]\nextern {\n   fn register_callback(cb: extern fn(i32)) -> i32;\n   fn trigger_callback();\n}\n\nfn main() {\n    unsafe {\n        register_callback(callback);\n        trigger_callback(); // Triggers the callback\n    }\n}\n```\n\nC code:\n\n```c\ntypedef void (*rust_callback)(int32_t);\nrust_callback cb;\n\nint32_t register_callback(rust_callback callback) {\n    cb = callback;\n    return 1;\n}\n\nvoid trigger_callback() {\n  cb(7); // Will call callback(7) in Rust\n}\n```\n\nIn this example Rust's `main()` will call `trigger_callback()` in C,\nwhich would, in turn, call back to `callback()` in Rust.\n\n\n## Targeting callbacks to Rust objects\n\nThe former example showed how a global function can be called from C code.\nHowever it is often desired that the callback is targeted to a special\nRust object. This could be the object that represents the wrapper for the\nrespective C object.\n\nThis can be achieved by passing an raw pointer to the object down to the\nC library. The C library can then include the pointer to the Rust object in\nthe notification. This will allow the callback to unsafely access the\nreferenced Rust object.\n\nRust code:\n\n```rust,no_run\n#[repr(C)]\nstruct RustObject {\n    a: i32,\n    // other members\n}\n\nextern \"C\" fn callback(target: *mut RustObject, a: i32) {\n    println!(\"I'm called from C with value {0}\", a);\n    unsafe {\n        // Update the value in RustObject with the value received from the callback\n        (*target).a = a;\n    }\n}\n\n#[link(name = \"extlib\")]\nextern {\n   fn register_callback(target: *mut RustObject,\n                        cb: extern fn(*mut RustObject, i32)) -> i32;\n   fn trigger_callback();\n}\n\nfn main() {\n    // Create the object that will be referenced in the callback\n    let mut rust_object = Box::new(RustObject { a: 5 });\n\n    unsafe {\n        register_callback(&mut *rust_object, callback);\n        trigger_callback();\n    }\n}\n```\n\nC code:\n\n```c\ntypedef void (*rust_callback)(void*, int32_t);\nvoid* cb_target;\nrust_callback cb;\n\nint32_t register_callback(void* callback_target, rust_callback callback) {\n    cb_target = callback_target;\n    cb = callback;\n    return 1;\n}\n\nvoid trigger_callback() {\n  cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust\n}\n```\n\n## Asynchronous callbacks\n\nIn the previously given examples the callbacks are invoked as a direct reaction\nto a function call to the external C library.\nThe control over the current thread is switched from Rust to C to Rust for the\nexecution of the callback, but in the end the callback is executed on the\nsame thread that called the function which triggered the callback.\n\nThings get more complicated when the external library spawns its own threads\nand invokes callbacks from there.\nIn these cases access to Rust data structures inside the callbacks is\nespecially unsafe and proper synchronization mechanisms must be used.\nBesides classical synchronization mechanisms like mutexes, one possibility in\nRust is to use channels (in `std::sync::mpsc`) to forward data from the C\nthread that invoked the callback into a Rust thread.\n\nIf an asynchronous callback targets a special object in the Rust address space\nit is also absolutely necessary that no more callbacks are performed by the\nC library after the respective Rust object gets destroyed.\nThis can be achieved by unregistering the callback in the object's\ndestructor and designing the library in a way that guarantees that no\ncallback will be performed after deregistration.\n\n# Linking\n\nThe `link` attribute on `extern` blocks provides the basic building block for\ninstructing rustc how it will link to native libraries. There are two accepted\nforms of the link attribute today:\n\n* `#[link(name = \"foo\")]`\n* `#[link(name = \"foo\", kind = \"bar\")]`\n\nIn both of these cases, `foo` is the name of the native library that we're\nlinking to, and in the second case `bar` is the type of native library that the\ncompiler is linking to. There are currently three known types of native\nlibraries:\n\n* Dynamic - `#[link(name = \"readline\")]`\n* Static - `#[link(name = \"my_build_dependency\", kind = \"static\")]`\n* Frameworks - `#[link(name = \"CoreFoundation\", kind = \"framework\")]`\n\nNote that frameworks are only available on OSX targets.\n\nThe different `kind` values are meant to differentiate how the native library\nparticipates in linkage. From a linkage perspective, the Rust compiler creates\ntwo flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary).\nNative dynamic library and framework dependencies are propagated to the final\nartifact boundary, while static library dependencies are not propagated at\nall, because the static libraries are integrated directly into the subsequent\nartifact.\n\nA few examples of how this model can be used are:\n\n* A native build dependency. Sometimes some C/C++ glue is needed when writing\n  some Rust code, but distribution of the C/C++ code in a library format is\n  a burden. In this case, the code will be archived into `libfoo.a` and then the\n  Rust crate would declare a dependency via `#[link(name = \"foo\", kind =\n  \"static\")]`.\n\n  Regardless of the flavor of output for the crate, the native static library\n  will be included in the output, meaning that distribution of the native static\n  library is not necessary.\n\n* A normal dynamic dependency. Common system libraries (like `readline`) are\n  available on a large number of systems, and often a static copy of these\n  libraries cannot be found. When this dependency is included in a Rust crate,\n  partial targets (like rlibs) will not link to the library, but when the rlib\n  is included in a final target (like a binary), the native library will be\n  linked in.\n\nOn OSX, frameworks behave with the same semantics as a dynamic library.\n\n# Unsafe blocks\n\nSome operations, like dereferencing raw pointers or calling functions that have been marked\nunsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to\nthe compiler that the unsafety does not leak out of the block.\n\nUnsafe functions, on the other hand, advertise it to the world. An unsafe function is written like\nthis:\n\n```rust\nunsafe fn kaboom(ptr: *const i32) -> i32 { *ptr }\n```\n\nThis function can only be called from an `unsafe` block or another `unsafe` function.\n\n# Accessing foreign globals\n\nForeign APIs often export a global variable which could do something like track\nglobal state. In order to access these variables, you declare them in `extern`\nblocks with the `static` keyword:\n\n```rust,no_run\n# #![feature(libc)]\nextern crate libc;\n\n#[link(name = \"readline\")]\nextern {\n    static rl_readline_version: libc::c_int;\n}\n\nfn main() {\n    println!(\"You have readline version {} installed.\",\n             rl_readline_version as i32);\n}\n```\n\nAlternatively, you may need to alter global state provided by a foreign\ninterface. To do this, statics can be declared with `mut` so we can mutate\nthem.\n\n```rust,no_run\n# #![feature(libc)]\nextern crate libc;\n\nuse std::ffi::CString;\nuse std::ptr;\n\n#[link(name = \"readline\")]\nextern {\n    static mut rl_prompt: *const libc::c_char;\n}\n\nfn main() {\n    let prompt = CString::new(\"[my-awesome-shell] $\").unwrap();\n    unsafe {\n        rl_prompt = prompt.as_ptr();\n\n        println!(\"{:?}\", rl_prompt);\n\n        rl_prompt = ptr::null();\n    }\n}\n```\n\nNote that all interaction with a `static mut` is unsafe, both reading and\nwriting. Dealing with global mutable state requires a great deal of care.\n\n# Foreign calling conventions\n\nMost foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when\ncalling foreign functions. Some foreign functions, most notably the Windows API, use other calling\nconventions. Rust provides a way to tell the compiler which convention to use:\n\n```rust\n# #![feature(libc)]\nextern crate libc;\n\n#[cfg(all(target_os = \"win32\", target_arch = \"x86\"))]\n#[link(name = \"kernel32\")]\n#[allow(non_snake_case)]\nextern \"stdcall\" {\n    fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int;\n}\n# fn main() { }\n```\n\nThis applies to the entire `extern` block. The list of supported ABI constraints\nare:\n\n* `stdcall`\n* `aapcs`\n* `cdecl`\n* `fastcall`\n* `vectorcall`\nThis is currently hidden behind the `abi_vectorcall` gate and is subject to change.\n* `Rust`\n* `rust-intrinsic`\n* `system`\n* `C`\n* `win64`\n\nMost of the abis in this list are self-explanatory, but the `system` abi may\nseem a little odd. This constraint selects whatever the appropriate ABI is for\ninteroperating with the target's libraries. For example, on win32 with a x86\narchitecture, this means that the abi used would be `stdcall`. On x86_64,\nhowever, windows uses the `C` calling convention, so `C` would be used. This\nmeans that in our previous example, we could have used `extern \"system\" { ... }`\nto define a block for all windows systems, not only x86 ones.\n\n# Interoperability with foreign code\n\nRust guarantees that the layout of a `struct` is compatible with the platform's\nrepresentation in C only if the `#[repr(C)]` attribute is applied to it.\n`#[repr(C, packed)]` can be used to lay out struct members without padding.\n`#[repr(C)]` can also be applied to an enum.\n\nRust's owned boxes (`Box<T>`) use non-nullable pointers as handles which point\nto the contained object. However, they should not be manually created because\nthey are managed by internal allocators. References can safely be assumed to be\nnon-nullable pointers directly to the type.  However, breaking the borrow\nchecking or mutability rules is not guaranteed to be safe, so prefer using raw\npointers (`*`) if that's needed because the compiler can't make as many\nassumptions about them.\n\nVectors and strings share the same basic memory layout, and utilities are\navailable in the `vec` and `str` modules for working with C APIs. However,\nstrings are not terminated with `\\0`. If you need a NUL-terminated string for\ninteroperability with C, you should use the `CString` type in the `std::ffi`\nmodule.\n\nThe [`libc` crate on crates.io][libc] includes type aliases and function\ndefinitions for the C standard library in the `libc` module, and Rust links\nagainst `libc` and `libm` by default.\n\n# The \"nullable pointer optimization\"\n\nCertain Rust types are defined to never be `null`. This includes references (`&T`,\n`&mut T`), boxes (`Box<T>`), and function pointers (`extern \"abi\" fn()`). When\ninterfacing with C, pointers that might be `null` are often used, which would seem to\nrequire some messy `transmute`s and/or unsafe code to handle conversions to/from Rust types.\nHowever, the language provides a workaround.\n\nAs a special case, an `enum` is eligible for the \"nullable pointer optimization\" if it contains\nexactly two variants, one of which contains no data and the other contains a field of one of the\nnon-nullable types listed above.  This means no extra space is required for a discriminant; rather,\nthe empty variant is represented by putting a `null` value into the non-nullable field. This is\ncalled an \"optimization\", but unlike other optimizations it is guaranteed to apply to eligible\ntypes.\n\nThe most common type that takes advantage of the nullable pointer optimization is `Option<T>`,\nwhere `None` corresponds to `null`. So `Option<extern \"C\" fn(c_int) -> c_int>` is a correct way\nto represent a nullable function pointer using the C ABI (corresponding to the C type\n`int (*)(int)`).\n\nHere is a contrived example. Let's say some C library has a facility for registering a\ncallback, which gets called in certain situations. The callback is passed a function pointer\nand an integer and it is supposed to run the function with the integer as a parameter. So\nwe have function pointers flying across the FFI boundary in both directions.\n\n```rust\n# #![feature(libc)]\nextern crate libc;\nuse libc::c_int;\n\n# #[cfg(hidden)]\nextern \"C\" {\n    /// Register the callback.\n    fn register(cb: Option<extern \"C\" fn(Option<extern \"C\" fn(c_int) -> c_int>, c_int) -> c_int>);\n}\n# unsafe fn register(_: Option<extern \"C\" fn(Option<extern \"C\" fn(c_int) -> c_int>,\n#                                            c_int) -> c_int>)\n# {}\n\n/// This fairly useless function receives a function pointer and an integer\n/// from C, and returns the result of calling the function with the integer.\n/// In case no function is provided, it squares the integer by default.\nextern \"C\" fn apply(process: Option<extern \"C\" fn(c_int) -> c_int>, int: c_int) -> c_int {\n    match process {\n        Some(f) => f(int),\n        None    => int * int\n    }\n}\n\nfn main() {\n    unsafe {\n        register(Some(apply));\n    }\n}\n```\n\nAnd the code on the C side looks like this:\n\n```c\nvoid register(void (*f)(void (*)(int), int)) {\n    ...\n}\n```\n\nNo `transmute` required!\n\n# Calling Rust code from C\n\nYou may wish to compile Rust code in a way so that it can be called from C. This is\nfairly easy, but requires a few things:\n\n```rust\n#[no_mangle]\npub extern fn hello_rust() -> *const u8 {\n    \"Hello, world!\\0\".as_ptr()\n}\n# fn main() {}\n```\n\nThe `extern` makes this function adhere to the C calling convention, as\ndiscussed above in \"[Foreign Calling\nConventions](ffi.html#foreign-calling-conventions)\". The `no_mangle`\nattribute turns off Rust's name mangling, so that it is easier to link to.\n\n# FFI and panics\n\nIt’s important to be mindful of `panic!`s when working with FFI. A `panic!`\nacross an FFI boundary is undefined behavior. If you’re writing code that may\npanic, you should run it in another thread, so that the panic doesn’t bubble up\nto C:\n\n```rust\nuse std::thread;\n\n#[no_mangle]\npub extern fn oh_no() -> i32 {\n    let h = thread::spawn(|| {\n        panic!(\"Oops!\");\n    });\n\n    match h.join() {\n        Ok(_) => 1,\n        Err(_) => 0,\n    }\n}\n# fn main() {}\n```\n\n# Representing opaque structs\n\nSometimes, a C library wants to provide a pointer to something, but not let you\nknow the internal details of the thing it wants. The simplest way is to use a\n`void *` argument:\n\n```c\nvoid foo(void *arg);\nvoid bar(void *arg);\n```\n\nWe can represent this in Rust with the `c_void` type:\n\n```rust\n# #![feature(libc)]\nextern crate libc;\n\nextern \"C\" {\n    pub fn foo(arg: *mut libc::c_void);\n    pub fn bar(arg: *mut libc::c_void);\n}\n# fn main() {}\n```\n\nThis is a perfectly valid way of handling the situation. However, we can do a bit\nbetter. To solve this, some C libraries will instead create a `struct`, where\nthe details and memory layout of the struct are private. This gives some amount\nof type safety. These structures are called ‘opaque’. Here’s an example, in C:\n\n```c\nstruct Foo; /* Foo is a structure, but its contents are not part of the public interface */\nstruct Bar;\nvoid foo(struct Foo *arg);\nvoid bar(struct Bar *arg);\n```\n\nTo do this in Rust, let’s create our own opaque types with `enum`:\n\n```rust\npub enum Foo {}\npub enum Bar {}\n\nextern \"C\" {\n    pub fn foo(arg: *mut Foo);\n    pub fn bar(arg: *mut Bar);\n}\n# fn main() {}\n```\n\nBy using an `enum` with no variants, we create an opaque type that we can’t\ninstantiate, as it has no variants. But because our `Foo` and `Bar` types are\ndifferent, we’ll get type safety between the two of them, so we cannot\naccidentally pass a pointer to `Foo` to `bar()`.\n"
  },
  {
    "path": "trpl/functions.md",
    "content": "% Functions\n\nEvery Rust program has at least one function, the `main` function:\n\n```rust\nfn main() {\n}\n```\n\nThis is the simplest possible function declaration. As we mentioned before,\n`fn` says ‘this is a function’, followed by the name, some parentheses because\nthis function takes no arguments, and then some curly braces to indicate the\nbody. Here’s a function named `foo`:\n\n```rust\nfn foo() {\n}\n```\n\nSo, what about taking arguments? Here’s a function that prints a number:\n\n```rust\nfn print_number(x: i32) {\n    println!(\"x is: {}\", x);\n}\n```\n\nHere’s a complete program that uses `print_number`:\n\n```rust\nfn main() {\n    print_number(5);\n}\n\nfn print_number(x: i32) {\n    println!(\"x is: {}\", x);\n}\n```\n\nAs you can see, function arguments work very similar to `let` declarations:\nyou add a type to the argument name, after a colon.\n\nHere’s a complete program that adds two numbers together and prints them:\n\n```rust\nfn main() {\n    print_sum(5, 6);\n}\n\nfn print_sum(x: i32, y: i32) {\n    println!(\"sum is: {}\", x + y);\n}\n```\n\nYou separate arguments with a comma, both when you call the function, as well\nas when you declare it.\n\nUnlike `let`, you _must_ declare the types of function arguments. This does\nnot work:\n\n```rust,ignore\nfn print_sum(x, y) {\n    println!(\"sum is: {}\", x + y);\n}\n```\n\nYou get this error:\n\n```text\nexpected one of `!`, `:`, or `@`, found `)`\nfn print_sum(x, y) {\n```\n\nThis is a deliberate design decision. While full-program inference is possible,\nlanguages which have it, like Haskell, often suggest that documenting your\ntypes explicitly is a best-practice. We agree that forcing functions to declare\ntypes while allowing for inference inside of function bodies is a wonderful\nsweet spot between full inference and no inference.\n\nWhat about returning a value? Here’s a function that adds one to an integer:\n\n```rust\nfn add_one(x: i32) -> i32 {\n    x + 1\n}\n```\n\nRust functions return exactly one value, and you declare the type after an\n‘arrow’, which is a dash (`-`) followed by a greater-than sign (`>`). The last\nline of a function determines what it returns. You’ll note the lack of a\nsemicolon here. If we added it in:\n\n```rust,ignore\nfn add_one(x: i32) -> i32 {\n    x + 1;\n}\n```\n\nWe would get an error:\n\n```text\nerror: not all control paths return a value\nfn add_one(x: i32) -> i32 {\n     x + 1;\n}\n\nhelp: consider removing this semicolon:\n     x + 1;\n          ^\n```\n\nThis reveals two interesting things about Rust: it is an expression-based\nlanguage, and semicolons are different from semicolons in other ‘curly brace\nand semicolon’-based languages. These two things are related.\n\n## Expressions vs. Statements\n\nRust is primarily an expression-based language. There are only two kinds of\nstatements, and everything else is an expression.\n\nSo what's the difference? Expressions return a value, and statements do not.\nThat’s why we end up with ‘not all control paths return a value’ here: the\nstatement `x + 1;` doesn’t return a value. There are two kinds of statements in\nRust: ‘declaration statements’ and ‘expression statements’. Everything else is\nan expression. Let’s talk about declaration statements first.\n\nIn some languages, variable bindings can be written as expressions, not\nstatements. Like Ruby:\n\n```ruby\nx = y = 5\n```\n\nIn Rust, however, using `let` to introduce a binding is _not_ an expression. The\nfollowing will produce a compile-time error:\n\n```rust,ignore\nlet x = (let y = 5); // expected identifier, found keyword `let`\n```\n\nThe compiler is telling us here that it was expecting to see the beginning of\nan expression, and a `let` can only begin a statement, not an expression.\n\nNote that assigning to an already-bound variable (e.g. `y = 5`) is still an\nexpression, although its value is not particularly useful. Unlike other\nlanguages where an assignment evaluates to the assigned value (e.g. `5` in the\nprevious example), in Rust the value of an assignment is an empty tuple `()`\nbecause the assigned value can have [only one owner](ownership.html), and any\nother returned value would be too surprising:\n\n```rust\nlet mut y = 5;\n\nlet x = (y = 6);  // x has the value `()`, not `6`\n```\n\nThe second kind of statement in Rust is the *expression statement*. Its\npurpose is to turn any expression into a statement. In practical terms, Rust's\ngrammar expects statements to follow other statements. This means that you use\nsemicolons to separate expressions from each other. This means that Rust\nlooks a lot like most other languages that require you to use semicolons\nat the end of every line, and you will see semicolons at the end of almost\nevery line of Rust code you see.\n\nWhat is this exception that makes us say \"almost\"? You saw it already, in this\ncode:\n\n```rust\nfn add_one(x: i32) -> i32 {\n    x + 1\n}\n```\n\nOur function claims to return an `i32`, but with a semicolon, it would return\n`()` instead. Rust realizes this probably isn’t what we want, and suggests\nremoving the semicolon in the error we saw before.\n\n## Early returns\n\nBut what about early returns? Rust does have a keyword for that, `return`:\n\n```rust\nfn foo(x: i32) -> i32 {\n    return x;\n\n    // we never run this code!\n    x + 1\n}\n```\n\nUsing a `return` as the last line of a function works, but is considered poor\nstyle:\n\n```rust\nfn foo(x: i32) -> i32 {\n    return x + 1;\n}\n```\n\nThe previous definition without `return` may look a bit strange if you haven’t\nworked in an expression-based language before, but it becomes intuitive over\ntime.\n\n## Diverging functions\n\nRust has some special syntax for ‘diverging functions’, which are functions that\ndo not return:\n\n```rust\nfn diverges() -> ! {\n    panic!(\"This function never returns!\");\n}\n```\n\n`panic!` is a macro, similar to `println!()` that we’ve already seen. Unlike\n`println!()`, `panic!()` causes the current thread of execution to crash with\nthe given message. Because this function will cause a crash, it will never\nreturn, and so it has the type ‘`!`’, which is read ‘diverges’.\n\nIf you add a main function that calls `diverges()` and run it, you’ll get\nsome output that looks like this:\n\n```text\nthread ‘main’ panicked at ‘This function never returns!’, hello.rs:2\n```\n\nIf you want more information, you can get a backtrace by setting the\n`RUST_BACKTRACE` environment variable:\n\n```text\n$ RUST_BACKTRACE=1 ./diverges\nthread 'main' panicked at 'This function never returns!', hello.rs:2\nstack backtrace:\n   1:     0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r\n   2:     0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w\n   3:     0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw\n   4:     0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650\n   5:     0x7f4027738809 - diverges::h2266b4c4b850236beaa\n   6:     0x7f40277389e5 - main::h19bb1149c2f00ecfBaa\n   7:     0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231\n   8:     0x7f402773d1d8 - __rust_try\n   9:     0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w\n  10:     0x7f4027738a19 - main\n  11:     0x7f402694ab44 - __libc_start_main\n  12:     0x7f40277386c8 - <unknown>\n  13:                0x0 - <unknown>\n```\n\nIf you need to override an already set `RUST_BACKTRACE`, \nin cases when you cannot just unset the variable, \nthen set it to `0` to avoid getting a backtrace. \nAny other value (even no value at all) turns on backtrace.\n\n```text\n$ export RUST_BACKTRACE=1\n...\n$ RUST_BACKTRACE=0 ./diverges \nthread 'main' panicked at 'This function never returns!', hello.rs:2\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n```\n\n`RUST_BACKTRACE` also works with Cargo’s `run` command:\n\n```text\n$ RUST_BACKTRACE=1 cargo run\n     Running `target/debug/diverges`\nthread 'main' panicked at 'This function never returns!', hello.rs:2\nstack backtrace:\n   1:     0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r\n   2:     0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w\n   3:     0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw\n   4:     0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650\n   5:     0x7f4027738809 - diverges::h2266b4c4b850236beaa\n   6:     0x7f40277389e5 - main::h19bb1149c2f00ecfBaa\n   7:     0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231\n   8:     0x7f402773d1d8 - __rust_try\n   9:     0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w\n  10:     0x7f4027738a19 - main\n  11:     0x7f402694ab44 - __libc_start_main\n  12:     0x7f40277386c8 - <unknown>\n  13:                0x0 - <unknown>\n```\n\nA diverging function can be used as any type:\n\n```rust,should_panic\n# fn diverges() -> ! {\n#    panic!(\"This function never returns!\");\n# }\nlet x: i32 = diverges();\nlet x: String = diverges();\n```\n\n## Function pointers\n\nWe can also create variable bindings which point to functions:\n\n```rust\nlet f: fn(i32) -> i32;\n```\n\n`f` is a variable binding which points to a function that takes an `i32` as\nan argument and returns an `i32`. For example:\n\n```rust\nfn plus_one(i: i32) -> i32 {\n    i + 1\n}\n\n// without type inference\nlet f: fn(i32) -> i32 = plus_one;\n\n// with type inference\nlet f = plus_one;\n```\n\nWe can then use `f` to call the function:\n\n```rust\n# fn plus_one(i: i32) -> i32 { i + 1 }\n# let f = plus_one;\nlet six = f(5);\n```\n"
  },
  {
    "path": "trpl/generics.md",
    "content": "% Generics\n\nSometimes, when writing a function or data type, we may want it to work for\nmultiple types of arguments. In Rust, we can do this with generics.\nGenerics are called ‘parametric polymorphism’ in type theory,\nwhich means that they are types or functions that have multiple forms (‘poly’\nis multiple, ‘morph’ is form) over a given parameter (‘parametric’).\n\nAnyway, enough type theory, let’s check out some generic code. Rust’s\nstandard library provides a type, `Option<T>`, that’s generic:\n\n```rust\nenum Option<T> {\n    Some(T),\n    None,\n}\n```\n\nThe `<T>` part, which you’ve seen a few times before, indicates that this is\na generic data type. Inside the declaration of our `enum`, wherever we see a `T`,\nwe substitute that type for the same type used in the generic. Here’s an\nexample of using `Option<T>`, with some extra type annotations:\n\n```rust\nlet x: Option<i32> = Some(5);\n```\n\nIn the type declaration, we say `Option<i32>`. Note how similar this looks to\n`Option<T>`. So, in this particular `Option`, `T` has the value of `i32`. On\nthe right-hand side of the binding, we make a `Some(T)`, where `T` is `5`.\nSince that’s an `i32`, the two sides match, and Rust is happy. If they didn’t\nmatch, we’d get an error:\n\n```rust,ignore\nlet x: Option<f64> = Some(5);\n// error: mismatched types: expected `core::option::Option<f64>`,\n// found `core::option::Option<_>` (expected f64 but found integral variable)\n```\n\nThat doesn’t mean we can’t make `Option<T>`s that hold an `f64`! They have\nto match up:\n\n```rust\nlet x: Option<i32> = Some(5);\nlet y: Option<f64> = Some(5.0f64);\n```\n\nThis is just fine. One definition, multiple uses.\n\nGenerics don’t have to only be generic over one type. Consider another type from Rust’s standard library that’s similar, `Result<T, E>`:\n\n```rust\nenum Result<T, E> {\n    Ok(T),\n    Err(E),\n}\n```\n\nThis type is generic over _two_ types: `T` and `E`. By the way, the capital letters\ncan be any letter you’d like. We could define `Result<T, E>` as:\n\n```rust\nenum Result<A, Z> {\n    Ok(A),\n    Err(Z),\n}\n```\n\nif we wanted to. Convention says that the first generic parameter should be\n`T`, for ‘type’, and that we use `E` for ‘error’. Rust doesn’t care, however.\n\nThe `Result<T, E>` type is intended to be used to return the result of a\ncomputation, and to have the ability to return an error if it didn’t work out.\n\n## Generic functions\n\nWe can write functions that take generic types with a similar syntax:\n\n```rust\nfn takes_anything<T>(x: T) {\n    // do something with x\n}\n```\n\nThe syntax has two parts: the `<T>` says “this function is generic over one\ntype, `T`”, and the `x: T` says “x has the type `T`.”\n\nMultiple arguments can have the same generic type:\n\n```rust\nfn takes_two_of_the_same_things<T>(x: T, y: T) {\n    // ...\n}\n```\n\nWe could write a version that takes multiple types:\n\n```rust\nfn takes_two_things<T, U>(x: T, y: U) {\n    // ...\n}\n```\n\n## Generic structs\n\nYou can store a generic type in a `struct` as well:\n\n```rust\nstruct Point<T> {\n    x: T,\n    y: T,\n}\n\nlet int_origin = Point { x: 0, y: 0 };\nlet float_origin = Point { x: 0.0, y: 0.0 };\n```\n\nSimilar to functions, the `<T>` is where we declare the generic parameters,\nand we then use `x: T` in the type declaration, too.\n\nWhen you want to add an implementation for the generic `struct`, you\ndeclare the type parameter after the `impl`:\n\n```rust\n# struct Point<T> {\n#     x: T,\n#     y: T,\n# }\n#\nimpl<T> Point<T> {\n    fn swap(&mut self) {\n        std::mem::swap(&mut self.x, &mut self.y);\n    }\n}\n```\n\nSo far you’ve seen generics that take absolutely any type. These are useful in\nmany cases: you’ve already seen `Option<T>`, and later you’ll meet universal\ncontainer types like [`Vec<T>`][Vec]. On the other hand, often you want to\ntrade that flexibility for increased expressive power. Read about [trait\nbounds][traits] to see why and how.\n\n[traits]: traits.html\n[Vec]: ../std/vec/struct.Vec.html\n"
  },
  {
    "path": "trpl/getting-started.md",
    "content": "% Getting Started\n\nThis first chapter of the book will get us going with Rust and its tooling.\nFirst, we’ll install Rust. Then, the classic ‘Hello World’ program. Finally,\nwe’ll talk about Cargo, Rust’s build system and package manager.\n\n# Installing Rust\n\nThe first step to using Rust is to install it. Generally speaking, you’ll need\nan Internet connection to run the commands in this section, as we’ll be\ndownloading Rust from the Internet.\n\nWe’ll be showing off a number of commands using a terminal, and those lines all\nstart with `$`. You don't need to type in the `$`s, they are there to indicate\nthe start of each command. We’ll see many tutorials and examples around the web\nthat follow this convention: `$` for commands run as our regular user, and `#`\nfor commands we should be running as an administrator.\n\n## Platform support\n\nThe Rust compiler runs on, and compiles to, a great number of platforms, though\nnot all platforms are equally supported. Rust's support levels are organized\ninto three tiers, each with a different set of guarantees.\n\nPlatforms are identified by their \"target triple\" which is the string to inform\nthe compiler what kind of output should be produced. The columns below indicate\nwhether the corresponding component works on the specified platform.\n\n### Tier 1\n\nTier 1 platforms can be thought of as \"guaranteed to build and work\".\nSpecifically they will each satisfy the following requirements:\n\n* Automated testing is set up to run tests for the platform.\n* Landing changes to the `rust-lang/rust` repository's master branch is gated on\n  tests passing.\n* Official release artifacts are provided for the platform.\n* Documentation for how to use and how to build the platform is available.\n\n|  Target                       | std |rustc|cargo| notes                      |\n|-------------------------------|-----|-----|-----|----------------------------|\n| `i686-apple-darwin`           |  ✓  |  ✓  |  ✓  | 32-bit OSX (10.7+, Lion+)  |\n| `i686-pc-windows-gnu`         |  ✓  |  ✓  |  ✓  | 32-bit MinGW (Windows 7+)  |\n| `i686-pc-windows-msvc`        |  ✓  |  ✓  |  ✓  | 32-bit MSVC (Windows 7+)   |\n| `i686-unknown-linux-gnu`      |  ✓  |  ✓  |  ✓  | 32-bit Linux (2.6.18+)     |\n| `x86_64-apple-darwin`         |  ✓  |  ✓  |  ✓  | 64-bit OSX (10.7+, Lion+)  |\n| `x86_64-pc-windows-gnu`       |  ✓  |  ✓  |  ✓  | 64-bit MinGW (Windows 7+)  |\n| `x86_64-pc-windows-msvc`      |  ✓  |  ✓  |  ✓  | 64-bit MSVC (Windows 7+)   |\n| `x86_64-unknown-linux-gnu`    |  ✓  |  ✓  |  ✓  | 64-bit Linux (2.6.18+)     |\n\n### Tier 2\n\nTier 2 platforms can be thought of as \"guaranteed to build\". Automated tests\nare not run so it's not guaranteed to produce a working build, but platforms\noften work to quite a good degree and patches are always welcome! Specifically,\nthese platforms are required to have each of the following:\n\n* Automated building is set up, but may not be running tests.\n* Landing changes to the `rust-lang/rust` repository's master branch is gated on\n  platforms **building**. Note that this means for some platforms only the\n  standard library is compiled, but for others the full bootstrap is run.\n* Official release artifacts are provided for the platform.\n\n|  Target                       | std |rustc|cargo| notes                      |\n|-------------------------------|-----|-----|-----|----------------------------|\n| `aarch64-apple-ios`           |  ✓  |     |     | ARM64 iOS                  |\n| `aarch64-unknown-linux-gnu`   |  ✓  |  ✓  |  ✓  | ARM64 Linux (2.6.18+)      |\n| `arm-linux-androideabi`       |  ✓  |     |     | ARM Android                |\n| `arm-unknown-linux-gnueabi`   |  ✓  |  ✓  |  ✓  | ARM Linux (2.6.18+)        |\n| `arm-unknown-linux-gnueabihf` |  ✓  |  ✓  |  ✓  | ARM Linux (2.6.18+)        |\n| `armv7-apple-ios`             |  ✓  |     |     | ARM iOS                    |\n|`armv7-unknown-linux-gnueabihf`|  ✓  |  ✓  |  ✓  | ARMv7 Linux (2.6.18+)      |\n| `armv7s-apple-ios`            |  ✓  |     |     | ARM iOS                    |\n| `i386-apple-ios`              |  ✓  |     |     | 32-bit x86 iOS             |\n| `i586-pc-windows-msvc`        |  ✓  |     |     | 32-bit Windows w/o SSE     |\n| `mips-unknown-linux-gnu`      |  ✓  |     |     | MIPS Linux (2.6.18+)       |\n| `mips-unknown-linux-musl`     |  ✓  |     |     | MIPS Linux with MUSL       |\n| `mipsel-unknown-linux-gnu`    |  ✓  |     |     | MIPS (LE) Linux (2.6.18+)  |\n| `mipsel-unknown-linux-musl`   |  ✓  |     |     | MIPS (LE) Linux with MUSL  |\n| `powerpc-unknown-linux-gnu`   |  ✓  |     |     | PowerPC Linux (2.6.18+)    |\n| `powerpc64-unknown-linux-gnu` |  ✓  |     |     | PPC64 Linux (2.6.18+)      |\n|`powerpc64le-unknown-linux-gnu`|  ✓  |     |     | PPC64LE Linux (2.6.18+)    |\n| `x86_64-apple-ios`            |  ✓  |     |     | 64-bit x86 iOS             |\n| `x86_64-rumprun-netbsd`       |  ✓  |     |     | 64-bit NetBSD Rump Kernel  |\n| `x86_64-unknown-freebsd`      |  ✓  |  ✓  |  ✓  | 64-bit FreeBSD             |\n| `x86_64-unknown-linux-musl`   |  ✓  |     |     | 64-bit Linux with MUSL     |\n| `x86_64-unknown-netbsd`       |  ✓  |  ✓  |  ✓  | 64-bit NetBSD              |\n\n### Tier 3\n\nTier 3 platforms are those which Rust has support for, but landing changes is\nnot gated on the platform either building or passing tests. Working builds for\nthese platforms may be spotty as their reliability is often defined in terms of\ncommunity contributions. Additionally, release artifacts and installers are not\nprovided, but there may be community infrastructure producing these in\nunofficial locations.\n\n|  Target                       | std |rustc|cargo| notes                      |\n|-------------------------------|-----|-----|-----|----------------------------|\n| `aarch64-linux-android`       |  ✓  |     |     | ARM64 Android              |\n| `armv7-linux-androideabi`     |  ✓  |     |     | ARM-v7a Android            |\n| `i686-linux-android`          |  ✓  |     |     | 32-bit x86 Android         |\n| `i686-pc-windows-msvc` (XP)   |  ✓  |     |     | Windows XP support         |\n| `i686-unknown-freebsd`        |  ✓  |  ✓  |  ✓  | 32-bit FreeBSD             |\n| `x86_64-pc-windows-msvc` (XP) |  ✓  |     |     | Windows XP support         |\n| `x86_64-sun-solaris`          |  ✓  |  ✓  |     | 64-bit Solaris/SunOS       |\n| `x86_64-unknown-bitrig`       |  ✓  |  ✓  |     | 64-bit Bitrig              |\n| `x86_64-unknown-dragonfly`    |  ✓  |  ✓  |     | 64-bit DragonFlyBSD        |\n| `x86_64-unknown-openbsd`      |  ✓  |  ✓  |     | 64-bit OpenBSD             |\n\nNote that this table can be expanded over time, this isn't the exhaustive set of\ntier 3 platforms that will ever be!\n\n## Installing on Linux or Mac\n\nIf we're on Linux or a Mac, all we need to do is open a terminal and type this:\n\n```bash\n$ curl -sSf https://static.rust-lang.org/rustup.sh | sh\n```\n\nThis will download a script, and start the installation. If it all goes well,\nyou’ll see this appear:\n\n```text\nRust is ready to roll.\n```\n\nFrom here, press `y` for ‘yes’, and then follow the rest of the prompts.\n\n## Installing on Windows\n\nIf you're on Windows, please download the appropriate [installer][install-page].\n\n[install-page]: https://www.rust-lang.org/install.html\n\n## Uninstalling\n\nUninstalling Rust is as easy as installing it. On Linux or Mac, run\nthe uninstall script:\n\n```bash\n$ sudo /usr/local/lib/rustlib/uninstall.sh\n```\n\nIf we used the Windows installer, we can re-run the `.msi` and it will give us\nan uninstall option.\n\n## Troubleshooting\n\nIf we've got Rust installed, we can open up a shell, and type this:\n\n```bash\n$ rustc --version\n```\n\nYou should see the version number, commit hash, and commit date.\n\nIf you do, Rust has been installed successfully! Congrats!\n\nIf you don't and you're on Windows, check that Rust is in your %PATH% system\nvariable: `$ echo %PATH%`. If it isn't, run the installer again, select \"Change\"\non the \"Change, repair, or remove installation\" page and ensure \"Add to PATH\" is\ninstalled on the local hard drive.  If you need to configure your path manually,\nyou can find the Rust executables in a directory like\n`\"C:\\Program Files\\Rust stable GNU 1.x\\bin\"`.\n\nRust does not do its own linking, and so you’ll need to have a linker\ninstalled. Doing so will depend on your specific system, consult its\ndocumentation for more details.\n\nIf not, there are a number of places where we can get help. The easiest is\n[the #rust-beginners IRC channel on irc.mozilla.org][irc-beginners] and for\ngeneral discussion [the #rust IRC channel on irc.mozilla.org][irc], which we\ncan access through [Mibbit][mibbit]. Then we'll be chatting with other\nRustaceans (a silly nickname we call ourselves) who can help us out. Other great\nresources include [the user’s forum][users] and [Stack Overflow][stackoverflow].\n\n[irc-beginners]: irc://irc.mozilla.org/#rust-beginners\n[irc]: irc://irc.mozilla.org/#rust\n[mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-beginners,%23rust\n[users]: https://users.rust-lang.org/\n[stackoverflow]: http://stackoverflow.com/questions/tagged/rust\n\nThis installer also installs a copy of the documentation locally, so we can\nread it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location.\nOn Windows, it's in a `share/doc` directory, inside the directory to which Rust\nwas installed.\n\n# Hello, world!\n\nNow that you have Rust installed, we'll help you write your first Rust program.\nIt's traditional when learning a new language to write a little program to\nprint the text “Hello, world!” to the screen, and in this section, we'll follow\nthat tradition.\n\nThe nice thing about starting with such a simple program is that you can\nquickly verify that your compiler is installed, and that it's working properly.\nPrinting information to the screen is also a pretty common thing to do, so\npracticing it early on is good.\n\n> Note: This book assumes basic familiarity with the command line. Rust itself\n> makes no specific demands about your editing, tooling, or where your code\n> lives, so if you prefer an IDE to the command line, that's an option. You may\n> want to check out [SolidOak], which was built specifically with Rust in mind.\n> There are a number of extensions in development by the community, and the\n> Rust team ships plugins for [various editors]. Configuring your editor or\n> IDE is out of the scope of this tutorial, so check the documentation for your\n> specific setup.\n\n[SolidOak]: https://github.com/oakes/SolidOak\n[various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md\n\n## Creating a Project File\n\nFirst, make a file to put your Rust code in. Rust doesn't care where your code\nlives, but for this book, I suggest making a *projects* directory in your home\ndirectory, and keeping all your projects there. Open a terminal and enter the\nfollowing commands to make a directory for this particular project:\n\n```bash\n$ mkdir ~/projects\n$ cd ~/projects\n$ mkdir hello_world\n$ cd hello_world\n```\n\n> Note: If you’re on Windows and not using PowerShell, the `~` may not work.\n> Consult the documentation for your shell for more details.\n\n## Writing and Running a Rust Program\n\nNext, make a new source file and call it *main.rs*. Rust files always end\nin a *.rs* extension. If you’re using more than one word in your filename, use\nan underscore to separate them; for example, you'd use *hello_world.rs* rather\nthan *helloworld.rs*.\n\nNow open the *main.rs* file you just created, and type the following code:\n\n```rust\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\nSave the file, and go back to your terminal window. On Linux or OSX, enter the\nfollowing commands:\n\n```bash\n$ rustc main.rs\n$ ./main\nHello, world!\n```\n\nIn Windows, replace `main` with `main.exe`. Regardless of your operating\nsystem, you should see the string `Hello, world!` print to the terminal. If you\ndid, then congratulations! You've officially written a Rust program. That makes\nyou a Rust programmer! Welcome.\n\n## Anatomy of a Rust Program\n\nNow, let’s go over what just happened in your \"Hello, world!\" program in\ndetail. Here's the first piece of the puzzle:\n\n```rust\nfn main() {\n\n}\n```\n\nThese lines define a *function* in Rust. The `main` function is special: it's\nthe beginning of every Rust program. The first line says, “I’m declaring a\nfunction named `main` that takes no arguments and returns nothing.” If there\nwere arguments, they would go inside the parentheses (`(` and `)`), and because\nwe aren’t returning anything from this function, we can omit the return type\nentirely.\n\nAlso note that the function body is wrapped in curly braces (`{` and `}`). Rust\nrequires these around all function bodies. It's considered good style to put\nthe opening curly brace on the same line as the function declaration, with one\nspace in between.\n\nInside the `main()` function:\n\n```rust\n    println!(\"Hello, world!\");\n```\n\nThis line does all of the work in this little program: it prints text to the\nscreen. There are a number of details that are important here. The first is\nthat it’s indented with four spaces, not tabs.\n\nThe second important part is the `println!()` line. This is calling a Rust\n*[macro]*, which is how metaprogramming is done in Rust. If it were calling a\nfunction instead, it would look like this: `println()` (without the !). We'll\ndiscuss Rust macros in more detail later, but for now you only need to\nknow that when you see a `!` that means that you’re calling a macro instead of\na normal function.\n\n\n[macro]: macros.html\n\nNext is `\"Hello, world!\"` which is a *string*. Strings are a surprisingly\ncomplicated topic in a systems programming language, and this is a *[statically\nallocated]* string. We pass this string as an argument to `println!`, which\nprints the string to the screen. Easy enough!\n\n[statically allocated]: the-stack-and-the-heap.html\n\nThe line ends with a semicolon (`;`). Rust is an *[expression-oriented\nlanguage]*, which means that most things are expressions, rather than\nstatements. The `;` indicates that this expression is over, and the next one is\nready to begin. Most lines of Rust code end with a `;`.\n\n[expression-oriented language]: glossary.html#expression-oriented-language\n\n## Compiling and Running Are Separate Steps\n\nIn \"Writing and Running a Rust Program\", we showed you how to run a newly\ncreated program. We'll break that process down and examine each step now.\n\nBefore running a Rust program, you have to compile it. You can use the Rust\ncompiler by entering the `rustc` command and passing it the name of your source\nfile, like this:\n\n```bash\n$ rustc main.rs\n```\n\nIf you come from a C or C++ background, you'll notice that this is similar to\n`gcc` or `clang`. After compiling successfully, Rust should output a binary\nexecutable, which you can see on Linux or OSX by entering the `ls` command in\nyour shell as follows:\n\n```bash\n$ ls\nmain  main.rs\n```\n\nOn Windows, you'd enter:\n\n```bash\n$ dir\nmain.exe\nmain.rs\n```\n\nThis shows we have two files: the source code, with an `.rs` extension, and the\nexecutable (`main.exe` on Windows, `main` everywhere else). All that's left to\ndo from here is run the `main` or `main.exe` file, like this:\n\n```bash\n$ ./main  # or .\\main.exe on Windows\n```\n\nIf *main.rs* were your \"Hello, world!\" program, this would print `Hello,\nworld!` to your terminal.\n\nIf you come from a dynamic language like Ruby, Python, or JavaScript, you may\nnot be used to compiling and running a program being separate steps. Rust is an\n*ahead-of-time compiled* language, which means that you can compile a program,\ngive it to someone else, and they can run it even without Rust installed. If\nyou give someone a `.rb` or `.py` or `.js` file, on the other hand, they need\nto have a Ruby, Python, or JavaScript implementation installed (respectively),\nbut you only need one command to both compile and run your program. Everything\nis a tradeoff in language design.\n\nJust compiling with `rustc` is fine for simple programs, but as your project\ngrows, you'll want to be able to manage all of the options your project has,\nand make it easy to share your code with other people and projects. Next, I'll\nintroduce you to a tool called Cargo, which will help you write real-world Rust\nprograms.\n\n# Hello, Cargo!\n\nCargo is Rust’s build system and package manager, and Rustaceans use Cargo to\nmanage their Rust projects. Cargo manages three things: building your code,\ndownloading the libraries your code depends on, and building those libraries.\nWe call libraries your code needs ‘dependencies’ since your code depends on\nthem.\n\nThe simplest Rust programs don’t have any dependencies, so right now, you'd\nonly use the first part of its functionality. As you write more complex Rust\nprograms, you’ll want to add dependencies, and if you start off using Cargo,\nthat will be a lot easier to do.\n\nAs the vast, vast majority of Rust projects use Cargo, we will assume that\nyou’re using it for the rest of the book. Cargo comes installed with Rust\nitself, if you used the official installers. If you installed Rust through some\nother means, you can check if you have Cargo installed by typing:\n\n```bash\n$ cargo --version\n```\n\nInto a terminal. If you see a version number, great! If you see an error like\n‘`command not found`’, then you should look at the documentation for the system\nin which you installed Rust, to determine if Cargo is separate.\n\n## Converting to Cargo\n\nLet’s convert the Hello World program to Cargo. To Cargo-fy a project, you need\nto do three things:\n\n1. Put your source file in the right directory.\n2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere\n   else).\n3. Make a Cargo configuration file.\n\nLet's get started!\n\n### Creating a Source Directory and Removing the Old Executable\n\nFirst, go back to your terminal, move to your *hello_world* directory, and\nenter the following commands:\n\n```bash\n$ mkdir src\n$ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows\n$ rm main  # or 'del main.exe' on Windows\n```\n\nCargo expects your source files to live inside a *src* directory, so do that\nfirst. This leaves the top-level project directory (in this case,\n*hello_world*) for READMEs, license information, and anything else not related\nto your code. In this way, using Cargo helps you keep your projects nice and\ntidy. There's a place for everything, and everything is in its place.\n\nNow, move *main.rs* into the *src* directory, and delete the compiled file you\ncreated with `rustc`. As usual, replace `main` with `main.exe` if you're on\nWindows.\n\nThis example retains `main.rs` as the source filename because it's creating an\nexecutable. If you wanted to make a library instead, you'd name the file\n`lib.rs`. This convention is used by Cargo to successfully compile your\nprojects, but it can be overridden if you wish.\n\n### Creating a Configuration File\n\nNext, create a new file inside your *hello_world* directory, and call it\n`Cargo.toml`.\n\nMake sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do\nwith the configuration file.\n\nThis file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is\nsimilar to INI, but has some extra goodies, and is used as Cargo’s\nconfiguration format.\n\n[TOML]: https://github.com/toml-lang/toml\n\nInside this file, type the following information:\n\n```toml\n[package]\n\nname = \"hello_world\"\nversion = \"0.0.1\"\nauthors = [ \"Your name <you@example.com>\" ]\n```\n\nThe first line, `[package]`, indicates that the following statements are\nconfiguring a package. As we add more information to this file, we’ll add other\nsections, but for now, we only have the package configuration.\n\nThe other three lines set the three bits of configuration that Cargo needs to\nknow to compile your program: its name, what version it is, and who wrote it.\n\nOnce you've added this information to the *Cargo.toml* file, save it to finish\ncreating the configuration file.\n\n## Building and Running a Cargo Project\n\nWith your *Cargo.toml* file in place in your project's root directory, you\nshould be ready to build and run your Hello World program! To do so, enter the\nfollowing commands:\n\n```bash\n$ cargo build\n   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)\n$ ./target/debug/hello_world\nHello, world!\n```\n\nBam! If all goes well, `Hello, world!` should print to the terminal once more.\n\nYou just built a project with `cargo build` and ran it with\n`./target/debug/hello_world`, but you can actually do both in one step with\n`cargo run` as follows:\n\n```bash\n$ cargo run\n     Running `target/debug/hello_world`\nHello, world!\n```\n\nNotice that this example didn’t re-build the project. Cargo figured out that\nthe file hasn’t changed, and so it just ran the binary. If you'd modified your\nsource code, Cargo would have rebuilt the project before running it, and you\nwould have seen something like this:\n\n```bash\n$ cargo run\n   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)\n     Running `target/debug/hello_world`\nHello, world!\n```\n\nCargo checks to see if any of your project’s files have been modified, and only\nrebuilds your project if they’ve changed since the last time you built it.\n\nWith simple projects, Cargo doesn't bring a whole lot over just using `rustc`,\nbut it will become useful in the future. This is especially true when you start\nusing crates; these are synonymous with a ‘library’ or ‘package’ in other\nprogramming languages. For complex projects composed of multiple crates, it’s\nmuch easier to let Cargo coordinate the build. Using Cargo, you can run `cargo\nbuild`, and it should work the right way.\n\n### Building for Release\n\nWhen your project is ready for release, you can use `cargo build\n--release` to compile your project with optimizations. These optimizations make\nyour Rust code run faster, but turning them on makes your program take longer\nto compile. This is why there are two different profiles, one for development,\nand one for building the final program you’ll give to a user.\n\n### What Is That `Cargo.lock`?\n\nRunning `cargo build` also causes Cargo to create a new file called\n*Cargo.lock*, which looks like this:\n\n```toml\n[root]\nname = \"hello_world\"\nversion = \"0.0.1\"\n```\n\nCargo uses the *Cargo.lock* file to keep track of dependencies in your\napplication. This is the Hello World project's *Cargo.lock* file. This project\ndoesn't have dependencies, so the file is a bit sparse. Realistically, you\nwon't ever need to touch this file yourself; just let Cargo handle it.\n\nThat’s it! If you've been following along, you should have successfully built\n`hello_world` with Cargo.\n\nEven though the project is simple, it now uses much of the real tooling you’ll\nuse for the rest of your Rust career. In fact, you can expect to start\nvirtually all Rust projects with some variation on the following commands:\n\n```bash\n$ git clone someurl.com/foo\n$ cd foo\n$ cargo build\n```\n\n## Making A New Cargo Project the Easy Way\n\nYou don’t have to go through that previous process every time you want to start\na new project! Cargo can quickly make a bare-bones project directory that you\ncan start developing in right away.\n\nTo start a new project with Cargo, enter `cargo new` at the command line:\n\n```bash\n$ cargo new hello_world --bin\n```\n\nThis command passes `--bin` because the goal is to get straight to making an\nexecutable application, as opposed to a library. Executables are often called\n*binaries* (as in `/usr/bin`, if you’re on a Unix system).\n\nCargo has generated two files and one directory for us: a `Cargo.toml` and a\n*src* directory with a *main.rs* file inside. These should look familiar,\nthey’re exactly what we created by hand, above.\n\nThis output is all you need to get started. First, open `Cargo.toml`. It should\nlook something like this:\n\n```toml\n[package]\n\nname = \"hello_world\"\nversion = \"0.1.0\"\nauthors = [\"Your Name <you@example.com>\"]\n\n[dependencies]\n```\n\nDo not worry about the `[dependencies]` line, we will come back to it later.\n\nCargo has populated *Cargo.toml* with reasonable defaults based on the arguments\nyou gave it and your `git` global configuration. You may notice that Cargo has\nalso initialized the `hello_world` directory as a `git` repository.\n\nHere’s what should be in `src/main.rs`:\n\n```rust\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\nCargo has generated a \"Hello World!\" for you, and you’re ready to start coding!\n\n> Note: If you want to look at Cargo in more detail, check out the official [Cargo\nguide], which covers all of its features.\n\n[Cargo guide]: http://doc.crates.io/guide.html\n\n# Closing Thoughts\n\nThis chapter covered the basics that will serve you well through the rest of\nthis book, and the rest of your time with Rust. Now that you’ve got the tools\ndown, we'll cover more about the Rust language itself.\n\nYou have two options: Dive into a project with ‘[Tutorial: Guessing Game][guessinggame]’, or\nstart from the bottom and work your way up with ‘[Syntax and\nSemantics][syntax]’. More experienced systems programmers will probably prefer\n‘Tutorial: Guessing Game’, while those from dynamic backgrounds may enjoy either. Different\npeople learn differently! Choose whatever’s right for you.\n\n[guessinggame]: guessing-game.html\n[syntax]: syntax-and-semantics.html\n"
  },
  {
    "path": "trpl/glossary.md",
    "content": "% Glossary\n\nNot every Rustacean has a background in systems programming, nor in computer\nscience, so we've added explanations of terms that might be unfamiliar.\n\n### Abstract Syntax Tree\n\nWhen a compiler is compiling your program, it does a number of different things.\nOne of the things that it does is turn the text of your program into an\n‘abstract syntax tree’, or ‘AST’. This tree is a representation of the structure\nof your program. For example, `2 + 3` can be turned into a tree:\n\n```text\n  +\n / \\\n2   3\n```\n\nAnd `2 + (3 * 4)` would look like this:\n\n```text\n  +\n / \\\n2   *\n   / \\\n  3   4\n```\n\n### Arity\n\nArity refers to the number of arguments a function or operation takes.\n\n```rust\nlet x = (2, 3);\nlet y = (4, 6);\nlet z = (8, 2, 6);\n```\n\nIn the example above `x` and `y` have arity 2. `z` has arity 3.\n\n### Bounds\n\nBounds are constraints on a type or [trait][traits]. For example, if a bound\nis placed on the argument a function takes, types passed to that function\nmust abide by that constraint.\n\n[traits]: traits.html\n\n### Combinators\n\nCombinators are higher-order functions that apply only functions and\nearlier defined combinators to provide a result from its arguments. \nThey can be used to manage control flow in a modular fashion.\n\n### DST (Dynamically Sized Type)\n\nA type without a statically known size or alignment. ([more info][link])\n\n[link]: ../nomicon/exotic-sizes.html#dynamically-sized-types-dsts\n\n### Expression\n\nIn computer programming, an expression is a combination of values, constants,\nvariables, operators and functions that evaluate to a single value. For example,\n`2 + (3 * 4)` is an expression that returns the value 14. It is worth noting\nthat expressions can have side-effects. For example, a function included in an\nexpression might perform actions other than simply returning a value.\n\n### Expression-Oriented Language\n\nIn early programming languages, [expressions][expression] and\n[statements][statement] were two separate syntactic categories: expressions had\na value and statements did things. However, later languages blurred this\ndistinction, allowing expressions to do things and statements to have a value.\nIn an expression-oriented language, (nearly) every statement is an expression\nand therefore returns a value. Consequently, these expression statements can\nthemselves form part of larger expressions.\n\n[expression]: glossary.html#expression\n[statement]: glossary.html#statement\n\n### Statement\n\nIn computer programming, a statement is the smallest standalone element of a\nprogramming language that commands a computer to perform an action.\n"
  },
  {
    "path": "trpl/guessing-game.md",
    "content": "% Guessing Game\n\nLet’s learn some Rust! For our first project, we’ll implement a classic\nbeginner programming problem: the guessing game. Here’s how it works: Our\nprogram will generate a random integer between one and a hundred. It will then\nprompt us to enter a guess. Upon entering our guess, it will tell us if we’re\ntoo low or too high. Once we guess correctly, it will congratulate us. Sounds\ngood?\n\nAlong the way, we’ll learn a little bit about Rust. The next chapter, ‘Syntax\nand Semantics’, will dive deeper into each part.\n\n# Set up\n\nLet’s set up a new project. Go to your projects directory. Remember how we had\nto create our directory structure and a `Cargo.toml` for `hello_world`? Cargo\nhas a command that does that for us. Let’s give it a shot:\n\n```bash\n$ cd ~/projects\n$ cargo new guessing_game --bin\n$ cd guessing_game\n```\n\nWe pass the name of our project to `cargo new`, and then the `--bin` flag,\nsince we’re making a binary, rather than a library.\n\nCheck out the generated `Cargo.toml`:\n\n```toml\n[package]\n\nname = \"guessing_game\"\nversion = \"0.1.0\"\nauthors = [\"Your Name <you@example.com>\"]\n```\n\nCargo gets this information from your environment. If it’s not correct, go ahead\nand fix that.\n\nFinally, Cargo generated a ‘Hello, world!’ for us. Check out `src/main.rs`:\n\n```rust\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\nLet’s try compiling what Cargo gave us:\n\n```{bash}\n$ cargo build\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n```\n\nExcellent! Open up your `src/main.rs` again. We’ll be writing all of\nour code in this file.\n\nBefore we move on, let me show you one more Cargo command: `run`. `cargo run`\nis kind of like `cargo build`, but it also then runs the produced executable.\nTry it out:\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/debug/guessing_game`\nHello, world!\n```\n\nGreat! The `run` command comes in handy when you need to rapidly iterate on a\nproject. Our game is such a project, we need to quickly test each\niteration before moving on to the next one.\n\n# Processing a Guess\n\nLet’s get to it! The first thing we need to do for our guessing game is\nallow our player to input a guess. Put this in your `src/main.rs`:\n\n```rust,no_run\nuse std::io;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    println!(\"Please input your guess.\");\n\n    let mut guess = String::new();\n\n    io::stdin().read_line(&mut guess)\n        .expect(\"Failed to read line\");\n\n    println!(\"You guessed: {}\", guess);\n}\n```\n\nThere’s a lot here! Let’s go over it, bit by bit.\n\n```rust,ignore\nuse std::io;\n```\n\nWe’ll need to take user input, and then print the result as output. As such, we\nneed the `io` library from the standard library. Rust only imports a few things\nby default into every program, [the ‘prelude’][prelude]. If it’s not in the\nprelude, you’ll have to `use` it directly. There is also a second ‘prelude’, the\n[`io` prelude][ioprelude], which serves a similar function: you import it, and it\nimports a number of useful, `io`-related things.\n\n[prelude]: ../std/prelude/index.html\n[ioprelude]: ../std/io/prelude/index.html\n\n```rust,ignore\nfn main() {\n```\n\nAs you’ve seen before, the `main()` function is the entry point into your\nprogram. The `fn` syntax declares a new function, the `()`s indicate that\nthere are no arguments, and `{` starts the body of the function. Because\nwe didn’t include a return type, it’s assumed to be `()`, an empty\n[tuple][tuples].\n\n[tuples]: primitive-types.html#tuples\n\n```rust,ignore\n    println!(\"Guess the number!\");\n\n    println!(\"Please input your guess.\");\n```\n\nWe previously learned that `println!()` is a [macro][macros] that\nprints a [string][strings] to the screen.\n\n[macros]: macros.html\n[strings]: strings.html\n\n```rust,ignore\n    let mut guess = String::new();\n```\n\nNow we’re getting interesting! There’s a lot going on in this little line.\nThe first thing to notice is that this is a [let statement][let], which is\nused to create ‘variable bindings’. They take this form:\n\n```rust,ignore\nlet foo = bar;\n```\n\n[let]: variable-bindings.html\n\nThis will create a new binding named `foo`, and bind it to the value `bar`. In\nmany languages, this is called a ‘variable’, but Rust’s variable bindings have\na few tricks up their sleeves.\n\nFor example, they’re [immutable][immutable] by default. That’s why our example\nuses `mut`: it makes a binding mutable, rather than immutable. `let` doesn’t\ntake a name on the left hand side of the assignment, it actually accepts a\n‘[pattern][patterns]’. We’ll use patterns later. It’s easy enough\nto use for now:\n\n```rust\nlet foo = 5; // immutable.\nlet mut bar = 5; // mutable\n```\n\n[immutable]: mutability.html\n[patterns]: patterns.html\n\nOh, and `//` will start a comment, until the end of the line. Rust ignores\neverything in [comments][comments].\n\n[comments]: comments.html\n\nSo now we know that `let mut guess` will introduce a mutable binding named\n`guess`, but we have to look at the other side of the `=` for what it’s\nbound to: `String::new()`.\n\n`String` is a string type, provided by the standard library. A\n[`String`][string] is a growable, UTF-8 encoded bit of text.\n\n[string]: ../std/string/struct.String.html\n\nThe `::new()` syntax uses `::` because this is an ‘associated function’ of\na particular type. That is to say, it’s associated with `String` itself,\nrather than a particular instance of a `String`. Some languages call this a\n‘static method’.\n\nThis function is named `new()`, because it creates a new, empty `String`.\nYou’ll find a `new()` function on many types, as it’s a common name for making\na new value of some kind.\n\nLet’s move forward:\n\n```rust,ignore\n    io::stdin().read_line(&mut guess)\n        .expect(\"Failed to read line\");\n```\n\nThat’s a lot more! Let’s go bit-by-bit. The first line has two parts. Here’s\nthe first:\n\n```rust,ignore\nio::stdin()\n```\n\nRemember how we `use`d `std::io` on the first line of the program? We’re now\ncalling an associated function on it. If we didn’t `use std::io`, we could\nhave written this line as `std::io::stdin()`.\n\nThis particular function returns a handle to the standard input for your\nterminal. More specifically, a [std::io::Stdin][iostdin].\n\n[iostdin]: ../std/io/struct.Stdin.html\n\nThe next part will use this handle to get input from the user:\n\n```rust,ignore\n.read_line(&mut guess)\n```\n\nHere, we call the [`read_line()`][read_line] method on our handle.\n[Methods][method] are like associated functions, but are only available on a\nparticular instance of a type, rather than the type itself. We’re also passing\none argument to `read_line()`: `&mut guess`.\n\n[read_line]: ../std/io/struct.Stdin.html#method.read_line\n[method]: method-syntax.html\n\nRemember how we bound `guess` above? We said it was mutable. However,\n`read_line` doesn’t take a `String` as an argument: it takes a `&mut String`.\nRust has a feature called ‘[references][references]’, which allows you to have\nmultiple references to one piece of data, which can reduce copying. References\nare a complex feature, as one of Rust’s major selling points is how safe and\neasy it is to use references. We don’t need to know a lot of those details to\nfinish our program right now, though. For now, all we need to know is that\nlike `let` bindings, references are immutable by default. Hence, we need to\nwrite `&mut guess`, rather than `&guess`.\n\nWhy does `read_line()` take a mutable reference to a string? Its job is\nto take what the user types into standard input, and place that into a\nstring. So it takes that string as an argument, and in order to add\nthe input, it needs to be mutable.\n\n[references]: references-and-borrowing.html\n\nBut we’re not quite done with this line of code, though. While it’s\na single line of text, it’s only the first part of the single logical line of\ncode:\n\n```rust,ignore\n        .expect(\"Failed to read line\");\n```\n\nWhen you call a method with the `.foo()` syntax, you may introduce a newline\nand other whitespace. This helps you split up long lines. We _could_ have\ndone:\n\n```rust,ignore\n    io::stdin().read_line(&mut guess).expect(\"failed to read line\");\n```\n\nBut that gets hard to read. So we’ve split it up, two lines for two method\ncalls. We already talked about `read_line()`, but what about `expect()`? Well,\nwe already mentioned that `read_line()` puts what the user types into the `&mut\nString` we pass it. But it also returns a value: in this case, an\n[`io::Result`][ioresult]. Rust has a number of types named `Result` in its\nstandard library: a generic [`Result`][result], and then specific versions for\nsub-libraries, like `io::Result`.\n\n[ioresult]: ../std/io/type.Result.html\n[result]: ../std/result/enum.Result.html\n\nThe purpose of these `Result` types is to encode error handling information.\nValues of the `Result` type, like any type, have methods defined on them. In\nthis case, `io::Result` has an [`expect()` method][expect] that takes a value\nit’s called on, and if it isn’t a successful one, [`panic!`][panic]s with a\nmessage you passed it. A `panic!` like this will cause our program to crash,\ndisplaying the message.\n\n[expect]: ../std/result/enum.Result.html#method.expect\n[panic]: error-handling.html\n\nIf we leave off calling this method, our program will compile, but\nwe’ll get a warning:\n\n```bash\n$ cargo build\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\nsrc/main.rs:10:5: 10:39 warning: unused result which must be used,\n#[warn(unused_must_use)] on by default\nsrc/main.rs:10     io::stdin().read_line(&mut guess);\n                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\n\nRust warns us that we haven’t used the `Result` value. This warning comes from\na special annotation that `io::Result` has. Rust is trying to tell you that\nyou haven’t handled a possible error. The right way to suppress the error is\nto actually write error handling. Luckily, if we want to crash if there’s\na problem, we can use `expect()`. If we can recover from the\nerror somehow, we’d do something else, but we’ll save that for a future\nproject.\n\nThere’s only one line of this first example left:\n\n```rust,ignore\n    println!(\"You guessed: {}\", guess);\n}\n```\n\nThis prints out the string we saved our input in. The `{}`s are a placeholder,\nand so we pass it `guess` as an argument. If we had multiple `{}`s, we would\npass multiple arguments:\n\n```rust\nlet x = 5;\nlet y = 10;\n\nprintln!(\"x and y: {} and {}\", x, y);\n```\n\nEasy.\n\nAnyway, that’s the tour. We can run what we have with `cargo run`:\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/debug/guessing_game`\nGuess the number!\nPlease input your guess.\n6\nYou guessed: 6\n```\n\nAll right! Our first part is done: we can get input from the keyboard,\nand then print it back out.\n\n# Generating a secret number\n\nNext, we need to generate a secret number. Rust does not yet include random\nnumber functionality in its standard library. The Rust team does, however,\nprovide a [`rand` crate][randcrate]. A ‘crate’ is a package of Rust code.\nWe’ve been building a ‘binary crate’, which is an executable. `rand` is a\n‘library crate’, which contains code that’s intended to be used with other\nprograms.\n\n[randcrate]: https://crates.io/crates/rand\n\nUsing external crates is where Cargo really shines. Before we can write\nthe code using `rand`, we need to modify our `Cargo.toml`. Open it up, and\nadd these few lines at the bottom:\n\n```toml\n[dependencies]\n\nrand=\"0.3.0\"\n```\n\nThe `[dependencies]` section of `Cargo.toml` is like the `[package]` section:\neverything that follows it is part of it, until the next section starts.\nCargo uses the dependencies section to know what dependencies on external\ncrates you have, and what versions you require. In this case, we’ve specified version `0.3.0`,\nwhich Cargo understands to be any release that’s compatible with this specific version.\nCargo understands [Semantic Versioning][semver], which is a standard for writing version\nnumbers. A bare number like above is actually shorthand for `^0.3.0`,\nmeaning \"anything compatible with 0.3.0\".\nIf we wanted to use only `0.3.0` exactly, we could say `rand=\"=0.3.0\"`\n(note the two equal signs).\nAnd if we wanted to use the latest version we could use `rand=\"*\"`.\nWe could also use a range of versions.\n[Cargo’s documentation][cargodoc] contains more details.\n\n[semver]: http://semver.org\n[cargodoc]: http://doc.crates.io/specifying-dependencies.html\n\nNow, without changing any of our code, let’s build our project:\n\n```bash\n$ cargo build\n    Updating registry `https://github.com/rust-lang/crates.io-index`\n Downloading rand v0.3.8\n Downloading libc v0.1.6\n   Compiling libc v0.1.6\n   Compiling rand v0.3.8\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n```\n\n(You may see different versions, of course.)\n\nLots of new output! Now that we have an external dependency, Cargo fetches the\nlatest versions of everything from the registry, which is a copy of data from\n[Crates.io][cratesio]. Crates.io is where people in the Rust ecosystem\npost their open source Rust projects for others to use.\n\n[cratesio]: https://crates.io\n\nAfter updating the registry, Cargo checks our `[dependencies]` and downloads\nany we don’t have yet. In this case, while we only said we wanted to depend on\n`rand`, we’ve also grabbed a copy of `libc`. This is because `rand` depends on\n`libc` to work. After downloading them, it compiles them, and then compiles\nour project.\n\nIf we run `cargo build` again, we’ll get different output:\n\n```bash\n$ cargo build\n```\n\nThat’s right, no output! Cargo knows that our project has been built, and that\nall of its dependencies are built, and so there’s no reason to do all that\nstuff. With nothing to do, it simply exits. If we open up `src/main.rs` again,\nmake a trivial change, and then save it again, we’ll only see one line:\n\n```bash\n$ cargo build\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n```\n\nSo, we told Cargo we wanted any `0.3.x` version of `rand`, and so it fetched the latest\nversion at the time this was written, `v0.3.8`. But what happens when next\nweek, version `v0.3.9` comes out, with an important bugfix? While getting\nbugfixes is important, what if `0.3.9` contains a regression that breaks our\ncode?\n\nThe answer to this problem is the `Cargo.lock` file you’ll now find in your\nproject directory. When you build your project for the first time, Cargo\nfigures out all of the versions that fit your criteria, and then writes them\nto the `Cargo.lock` file. When you build your project in the future, Cargo\nwill see that the `Cargo.lock` file exists, and then use that specific version\nrather than do all the work of figuring out versions again. This lets you\nhave a repeatable build automatically. In other words, we’ll stay at `0.3.8`\nuntil we explicitly upgrade, and so will anyone who we share our code with,\nthanks to the lock file.\n\nWhat about when we _do_ want to use `v0.3.9`? Cargo has another command,\n`update`, which says ‘ignore the lock, figure out all the latest versions that\nfit what we’ve specified. If that works, write those versions out to the lock\nfile’. But, by default, Cargo will only look for versions larger than `0.3.0`\nand smaller than `0.4.0`. If we want to move to `0.4.x`, we’d have to update\nthe `Cargo.toml` directly. When we do, the next time we `cargo build`, Cargo\nwill update the index and re-evaluate our `rand` requirements.\n\nThere’s a lot more to say about [Cargo][doccargo] and [its\necosystem][doccratesio], but for now, that’s all we need to know. Cargo makes\nit really easy to re-use libraries, and so Rustaceans tend to write smaller\nprojects which are assembled out of a number of sub-packages.\n\n[doccargo]: http://doc.crates.io\n[doccratesio]: http://doc.crates.io/crates-io.html\n\nLet’s get on to actually _using_ `rand`. Here’s our next step:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    println!(\"Please input your guess.\");\n\n    let mut guess = String::new();\n\n    io::stdin().read_line(&mut guess)\n        .expect(\"failed to read line\");\n\n    println!(\"You guessed: {}\", guess);\n}\n```\n\nThe first thing we’ve done is change the first line. It now says\n`extern crate rand`. Because we declared `rand` in our `[dependencies]`, we\ncan use `extern crate` to let Rust know we’ll be making use of it. This also\ndoes the equivalent of a `use rand;` as well, so we can make use of anything\nin the `rand` crate by prefixing it with `rand::`.\n\nNext, we added another `use` line: `use rand::Rng`. We’re going to use a\nmethod in a moment, and it requires that `Rng` be in scope to work. The basic\nidea is this: methods are defined on something called ‘traits’, and for the\nmethod to work, it needs the trait to be in scope. For more about the\ndetails, read the [traits][traits] section.\n\n[traits]: traits.html\n\nThere are two other lines we added, in the middle:\n\n```rust,ignore\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n```\n\nWe use the `rand::thread_rng()` function to get a copy of the random number\ngenerator, which is local to the particular [thread][concurrency] of execution\nwe’re in. Because we `use rand::Rng`’d above, it has a `gen_range()` method\navailable. This method takes two arguments, and generates a number between\nthem. It’s inclusive on the lower bound, but exclusive on the upper bound,\nso we need `1` and `101` to get a number ranging from one to a hundred.\n\n[concurrency]: concurrency.html\n\nThe second line prints out the secret number. This is useful while\nwe’re developing our program, so we can easily test it out. But we’ll be\ndeleting it for the final version. It’s not much of a game if it prints out\nthe answer when you start it up!\n\nTry running our new program a few times:\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 7\nPlease input your guess.\n4\nYou guessed: 4\n$ cargo run\n     Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 83\nPlease input your guess.\n5\nYou guessed: 5\n```\n\nGreat! Next up: comparing our guess to the secret number.\n\n# Comparing guesses\n\nNow that we’ve got user input, let’s compare our guess to the secret number.\nHere’s our next step, though it doesn’t quite compile yet:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    println!(\"Please input your guess.\");\n\n    let mut guess = String::new();\n\n    io::stdin().read_line(&mut guess)\n        .expect(\"failed to read line\");\n\n    println!(\"You guessed: {}\", guess);\n\n    match guess.cmp(&secret_number) {\n        Ordering::Less    => println!(\"Too small!\"),\n        Ordering::Greater => println!(\"Too big!\"),\n        Ordering::Equal   => println!(\"You win!\"),\n    }\n}\n```\n\nA few new bits here. The first is another `use`. We bring a type called\n`std::cmp::Ordering` into scope. Then, five new lines at the bottom that use\nit:\n\n```rust,ignore\nmatch guess.cmp(&secret_number) {\n    Ordering::Less    => println!(\"Too small!\"),\n    Ordering::Greater => println!(\"Too big!\"),\n    Ordering::Equal   => println!(\"You win!\"),\n}\n```\n\nThe `cmp()` method can be called on anything that can be compared, and it\ntakes a reference to the thing you want to compare it to. It returns the\n`Ordering` type we `use`d earlier. We use a [`match`][match] statement to\ndetermine exactly what kind of `Ordering` it is. `Ordering` is an\n[`enum`][enum], short for ‘enumeration’, which looks like this:\n\n```rust\nenum Foo {\n    Bar,\n    Baz,\n}\n```\n\n[match]: match.html\n[enum]: enums.html\n\nWith this definition, anything of type `Foo` can be either a\n`Foo::Bar` or a `Foo::Baz`. We use the `::` to indicate the\nnamespace for a particular `enum` variant.\n\nThe [`Ordering`][ordering] `enum` has three possible variants: `Less`, `Equal`,\nand `Greater`. The `match` statement takes a value of a type, and lets you\ncreate an ‘arm’ for each possible value. Since we have three types of\n`Ordering`, we have three arms:\n\n```rust,ignore\nmatch guess.cmp(&secret_number) {\n    Ordering::Less    => println!(\"Too small!\"),\n    Ordering::Greater => println!(\"Too big!\"),\n    Ordering::Equal   => println!(\"You win!\"),\n}\n```\n\n[ordering]: ../std/cmp/enum.Ordering.html\n\nIf it’s `Less`, we print `Too small!`, if it’s `Greater`, `Too big!`, and if\n`Equal`, `You win!`. `match` is really useful, and is used often in Rust.\n\nI did mention that this won’t quite compile yet, though. Let’s try it:\n\n```bash\n$ cargo build\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\nsrc/main.rs:28:21: 28:35 error: mismatched types:\n expected `&collections::string::String`,\n    found `&_`\n(expected struct `collections::string::String`,\n    found integral variable) [E0308]\nsrc/main.rs:28     match guess.cmp(&secret_number) {\n                                   ^~~~~~~~~~~~~~\nerror: aborting due to previous error\nCould not compile `guessing_game`.\n```\n\nWhew! This is a big error. The core of it is that we have ‘mismatched types’.\nRust has a strong, static type system. However, it also has type inference.\nWhen we wrote `let guess = String::new()`, Rust was able to infer that `guess`\nshould be a `String`, and so it doesn’t make us write out the type. And with\nour `secret_number`, there are a number of types which can have a value\nbetween one and a hundred: `i32`, a thirty-two-bit number, or `u32`, an\nunsigned thirty-two-bit number, or `i64`, a sixty-four-bit number or others.\nSo far, that hasn’t mattered, and so Rust defaults to an `i32`. However, here,\nRust doesn’t know how to compare the `guess` and the `secret_number`. They\nneed to be the same type. Ultimately, we want to convert the `String` we\nread as input into a real number type, for comparison. We can do that\nwith two more lines. Here’s our new program:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    println!(\"Please input your guess.\");\n\n    let mut guess = String::new();\n\n    io::stdin().read_line(&mut guess)\n        .expect(\"failed to read line\");\n\n    let guess: u32 = guess.trim().parse()\n        .expect(\"Please type a number!\");\n\n    println!(\"You guessed: {}\", guess);\n\n    match guess.cmp(&secret_number) {\n        Ordering::Less    => println!(\"Too small!\"),\n        Ordering::Greater => println!(\"Too big!\"),\n        Ordering::Equal   => println!(\"You win!\"),\n    }\n}\n```\n\nThe new two lines:\n\n```rust,ignore\n    let guess: u32 = guess.trim().parse()\n        .expect(\"Please type a number!\");\n```\n\nWait a minute, I thought we already had a `guess`? We do, but Rust allows us\nto ‘shadow’ the previous `guess` with a new one. This is often used in this\nexact situation, where `guess` starts as a `String`, but we want to convert it\nto an `u32`. Shadowing lets us re-use the `guess` name, rather than forcing us\nto come up with two unique names like `guess_str` and `guess`, or something\nelse.\n\nWe bind `guess` to an expression that looks like something we wrote earlier:\n\n```rust,ignore\nguess.trim().parse()\n```\n\nHere, `guess` refers to the old `guess`, the one that was a `String` with our\ninput in it. The `trim()` method on `String`s will eliminate any white space at\nthe beginning and end of our string. This is important, as we had to press the\n‘return’ key to satisfy `read_line()`. This means that if we type `5` and hit\nreturn, `guess` looks like this: `5\\n`. The `\\n` represents ‘newline’, the\nenter key. `trim()` gets rid of this, leaving our string with only the `5`. The\n[`parse()` method on strings][parse] parses a string into some kind of number.\nSince it can parse a variety of numbers, we need to give Rust a hint as to the\nexact type of number we want. Hence, `let guess: u32`. The colon (`:`) after\n`guess` tells Rust we’re going to annotate its type. `u32` is an unsigned,\nthirty-two bit integer. Rust has [a number of built-in number types][number],\nbut we’ve chosen `u32`. It’s a good default choice for a small positive number.\n\n[parse]: ../std/primitive.str.html#method.parse\n[number]: primitive-types.html#numeric-types\n\nJust like `read_line()`, our call to `parse()` could cause an error. What if\nour string contained `A👍%`? There’d be no way to convert that to a number. As\nsuch, we’ll do the same thing we did with `read_line()`: use the `expect()`\nmethod to crash if there’s an error.\n\nLet’s try our program out!\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/guessing_game`\nGuess the number!\nThe secret number is: 58\nPlease input your guess.\n  76\nYou guessed: 76\nToo big!\n```\n\nNice! You can see I even added spaces before my guess, and it still figured\nout that I guessed 76. Run the program a few times, and verify that guessing\nthe number works, as well as guessing a number too small.\n\nNow we’ve got most of the game working, but we can only make one guess. Let’s\nchange that by adding loops!\n\n# Looping\n\nThe `loop` keyword gives us an infinite loop. Let’s add that in:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    loop {\n        println!(\"Please input your guess.\");\n\n        let mut guess = String::new();\n\n        io::stdin().read_line(&mut guess)\n            .expect(\"failed to read line\");\n\n        let guess: u32 = guess.trim().parse()\n            .expect(\"Please type a number!\");\n\n        println!(\"You guessed: {}\", guess);\n\n        match guess.cmp(&secret_number) {\n            Ordering::Less    => println!(\"Too small!\"),\n            Ordering::Greater => println!(\"Too big!\"),\n            Ordering::Equal   => println!(\"You win!\"),\n        }\n    }\n}\n```\n\nAnd try it out. But wait, didn’t we just add an infinite loop? Yup. Remember\nour discussion about `parse()`? If we give a non-number answer, we’ll `panic!`\nand quit. Observe:\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/guessing_game`\nGuess the number!\nThe secret number is: 59\nPlease input your guess.\n45\nYou guessed: 45\nToo small!\nPlease input your guess.\n60\nYou guessed: 60\nToo big!\nPlease input your guess.\n59\nYou guessed: 59\nYou win!\nPlease input your guess.\nquit\nthread 'main' panicked at 'Please type a number!'\n```\n\nHa! `quit` actually quits. As does any other non-number input. Well, this is\nsuboptimal to say the least. First, let’s actually quit when you win the game:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    loop {\n        println!(\"Please input your guess.\");\n\n        let mut guess = String::new();\n\n        io::stdin().read_line(&mut guess)\n            .expect(\"failed to read line\");\n\n        let guess: u32 = guess.trim().parse()\n            .expect(\"Please type a number!\");\n\n        println!(\"You guessed: {}\", guess);\n\n        match guess.cmp(&secret_number) {\n            Ordering::Less    => println!(\"Too small!\"),\n            Ordering::Greater => println!(\"Too big!\"),\n            Ordering::Equal   => {\n                println!(\"You win!\");\n                break;\n            }\n        }\n    }\n}\n```\n\nBy adding the `break` line after the `You win!`, we’ll exit the loop when we\nwin. Exiting the loop also means exiting the program, since it’s the last\nthing in `main()`. We have only one more tweak to make: when someone inputs a\nnon-number, we don’t want to quit, we want to ignore it. We can do that\nlike this:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    println!(\"The secret number is: {}\", secret_number);\n\n    loop {\n        println!(\"Please input your guess.\");\n\n        let mut guess = String::new();\n\n        io::stdin().read_line(&mut guess)\n            .expect(\"failed to read line\");\n\n        let guess: u32 = match guess.trim().parse() {\n            Ok(num) => num,\n            Err(_) => continue,\n        };\n\n        println!(\"You guessed: {}\", guess);\n\n        match guess.cmp(&secret_number) {\n            Ordering::Less    => println!(\"Too small!\"),\n            Ordering::Greater => println!(\"Too big!\"),\n            Ordering::Equal   => {\n                println!(\"You win!\");\n                break;\n            }\n        }\n    }\n}\n```\n\nThese are the lines that changed:\n\n```rust,ignore\nlet guess: u32 = match guess.trim().parse() {\n    Ok(num) => num,\n    Err(_) => continue,\n};\n```\nThis is how you generally move from ‘crash on error’ to ‘actually handle the\nerror’, by switching from `expect()` to a `match` statement. A `Result` is\nreturned by `parse()`, this is an `enum`  like `Ordering`, but in this case,\neach variant has some data associated with it: `Ok` is a success, and `Err` is a\nfailure. Each contains more information: the successfully parsed integer, or an\nerror type. In this case, we `match` on `Ok(num)`, which sets the name `num` to\nthe unwrapped `Ok` value (the integer), and then we  return it on the\nright-hand side. In the `Err` case, we don’t care what kind of error it is, so\nwe just use the catch all `_` instead of a name. This catches everything that\nisn't `Ok`, and `continue` lets us move to the next iteration of the loop; in\neffect, this enables us to ignore all errors and continue with our program.\n\nNow we should be good! Let’s try:\n\n```bash\n$ cargo run\n   Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)\n     Running `target/guessing_game`\nGuess the number!\nThe secret number is: 61\nPlease input your guess.\n10\nYou guessed: 10\nToo small!\nPlease input your guess.\n99\nYou guessed: 99\nToo big!\nPlease input your guess.\nfoo\nPlease input your guess.\n61\nYou guessed: 61\nYou win!\n```\n\nAwesome! With one tiny last tweak, we have finished the guessing game. Can you\nthink of what it is? That’s right, we don’t want to print out the secret\nnumber. It was good for testing, but it kind of ruins the game. Here’s our\nfinal source:\n\n```rust,ignore\nextern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1, 101);\n\n    loop {\n        println!(\"Please input your guess.\");\n\n        let mut guess = String::new();\n\n        io::stdin().read_line(&mut guess)\n            .expect(\"failed to read line\");\n\n        let guess: u32 = match guess.trim().parse() {\n            Ok(num) => num,\n            Err(_) => continue,\n        };\n\n        println!(\"You guessed: {}\", guess);\n\n        match guess.cmp(&secret_number) {\n            Ordering::Less    => println!(\"Too small!\"),\n            Ordering::Greater => println!(\"Too big!\"),\n            Ordering::Equal   => {\n                println!(\"You win!\");\n                break;\n            }\n        }\n    }\n}\n```\n\n# Complete!\n\nThis project showed you a lot: `let`, `match`, methods, associated\nfunctions, using external crates, and more.\n\nAt this point, you have successfully built the Guessing Game! Congratulations!\n"
  },
  {
    "path": "trpl/if-let.md",
    "content": "% if let\n\n`if let` allows you to combine `if` and `let` together to reduce the overhead\nof certain kinds of pattern matches.\n\nFor example, let’s say we have some sort of `Option<T>`. We want to call a function\non it if it’s `Some<T>`, but do nothing if it’s `None`. That looks like this:\n\n```rust\n# let option = Some(5);\n# fn foo(x: i32) { }\nmatch option {\n    Some(x) => { foo(x) },\n    None => {},\n}\n```\n\nWe don’t have to use `match` here, for example, we could use `if`:\n\n```rust\n# let option = Some(5);\n# fn foo(x: i32) { }\nif option.is_some() {\n    let x = option.unwrap();\n    foo(x);\n}\n```\n\nNeither of these options is particularly appealing. We can use `if let` to\ndo the same thing in a nicer way:\n\n```rust\n# let option = Some(5);\n# fn foo(x: i32) { }\nif let Some(x) = option {\n    foo(x);\n}\n```\n\nIf a [pattern][patterns] matches successfully, it binds any appropriate parts of\nthe value to the identifiers in the pattern, then evaluates the expression. If\nthe pattern doesn’t match, nothing happens.\n\nIf you want to do something else when the pattern does not match, you can\nuse `else`:\n\n```rust\n# let option = Some(5);\n# fn foo(x: i32) { }\n# fn bar() { }\nif let Some(x) = option {\n    foo(x);\n} else {\n    bar();\n}\n```\n\n## `while let`\n\nIn a similar fashion, `while let` can be used when you want to conditionally\nloop  as long as a value matches a certain pattern. It turns code like this:\n\n```rust\nlet mut v = vec![1, 3, 5, 7, 11];\nloop {\n    match v.pop() {\n        Some(x) =>  println!(\"{}\", x),\n        None => break,\n    }\n}\n```\n\nInto code like this:\n\n```rust\nlet mut v = vec![1, 3, 5, 7, 11];\nwhile let Some(x) = v.pop() {\n    println!(\"{}\", x);\n}\n```\n\n[patterns]: patterns.html\n"
  },
  {
    "path": "trpl/if.md",
    "content": "% if\n\nRust’s take on `if` is not particularly complex, but it’s much more like the\n`if` you’ll find in a dynamically typed language than in a more traditional\nsystems language. So let’s talk about it, to make sure you grasp the nuances.\n\n`if` is a specific form of a more general concept, the ‘branch’, whose name comes\nfrom a branch in a tree: a decision point, where depending on a choice,\nmultiple paths can be taken.\n\nIn the case of `if`, there is one choice that leads down two paths:\n\n```rust\nlet x = 5;\n\nif x == 5 {\n    println!(\"x is five!\");\n}\n```\n\nIf we changed the value of `x` to something else, this line would not print.\nMore specifically, if the expression after the `if` evaluates to `true`, then\nthe block is executed. If it’s `false`, then it is not.\n\nIf you want something to happen in the `false` case, use an `else`:\n\n```rust\nlet x = 5;\n\nif x == 5 {\n    println!(\"x is five!\");\n} else {\n    println!(\"x is not five :(\");\n}\n```\n\nIf there is more than one case, use an `else if`:\n\n```rust\nlet x = 5;\n\nif x == 5 {\n    println!(\"x is five!\");\n} else if x == 6 {\n    println!(\"x is six!\");\n} else {\n    println!(\"x is not five or six :(\");\n}\n```\n\nThis is all pretty standard. However, you can also do this:\n\n```rust\nlet x = 5;\n\nlet y = if x == 5 {\n    10\n} else {\n    15\n}; // y: i32\n```\n\nWhich we can (and probably should) write like this:\n\n```rust\nlet x = 5;\n\nlet y = if x == 5 { 10 } else { 15 }; // y: i32\n```\n\nThis works because `if` is an expression. The value of the expression is the\nvalue of the last expression in whichever branch was chosen. An `if` without an\n`else` always results in `()` as the value.\n"
  },
  {
    "path": "trpl/inline-assembly.md",
    "content": "% Inline Assembly\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `asm!` macro.\n\n```rust,ignore\nasm!(assembly template\n   : output operands\n   : input operands\n   : clobbers\n   : options\n   );\n```\n\nAny use of `asm` is feature gated (requires `#![feature(asm)]` on the\ncrate to allow) and of course requires an `unsafe` block.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but\n> all platforms are supported.\n\n## Assembly template\n\nThe `assembly template` is the only required parameter and must be a\nliteral string (i.e. `\"\"`)\n\n```rust\n#![feature(asm)]\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn foo() {\n    unsafe {\n        asm!(\"NOP\");\n    }\n}\n\n// other platforms\n#[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\nfn foo() { /* ... */ }\n\nfn main() {\n    // ...\n    foo();\n    // ...\n}\n```\n\n(The `feature(asm)` and `#[cfg]`s are omitted from now on.)\n\nOutput operands, input operands, clobbers and options are all optional\nbut you must add the right number of `:` if you skip them:\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nasm!(\"xor %eax, %eax\"\n    :\n    :\n    : \"eax\"\n   );\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nWhitespace also doesn't matter:\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nasm!(\"xor %eax, %eax\" ::: \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## Operands\n\nInput and output operands follow the same format: `:\n\"constraints1\"(expr1), \"constraints2\"(expr2), ...\"`. Output operand\nexpressions must be mutable lvalues, or not yet assigned:\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn add(a: i32, b: i32) -> i32 {\n    let c: i32;\n    unsafe {\n        asm!(\"add $2, $0\"\n             : \"=r\"(c)\n             : \"0\"(a), \"r\"(b)\n             );\n    }\n    c\n}\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn add(a: i32, b: i32) -> i32 { a + b }\n\nfn main() {\n    assert_eq!(add(3, 14159), 14162)\n}\n```\n\nIf you would like to use real operands in this position, however,\nyou are required to put curly braces `{}` around the register that\nyou want, and you are required to put the specific size of the\noperand. This is useful for very low level programming, where\nwhich register you use is important:\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# unsafe fn read_byte_in(port: u16) -> u8 {\nlet result: u8;\nasm!(\"in %dx, %al\" : \"={al}\"(result) : \"{dx}\"(port));\nresult\n# }\n```\n\n## Clobbers\n\nSome instructions modify registers which might otherwise have held\ndifferent values so we use the clobbers list to indicate to the\ncompiler not to assume any values loaded into those registers will\nstay valid.\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\n// Put the value 0x200 in eax\nasm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nInput and output registers need not be listed since that information\nis already communicated by the given constraints. Otherwise, any other\nregisters used either implicitly or explicitly should be listed.\n\nIf the assembly changes the condition code register `cc` should be\nspecified as one of the clobbers. Similarly, if the assembly modifies\nmemory, `memory` should also be specified.\n\n## Options\n\nThe last section, `options` is specific to Rust. The format is comma\nseparated literal strings (i.e. `:\"foo\", \"bar\", \"baz\"`). It's used to\nspecify some extra info about the inline assembly:\n\nCurrent valid options are:\n\n1. *volatile* - specifying this is analogous to\n   `__asm__ __volatile__ (...)` in gcc/clang.\n2. *alignstack* - certain instructions expect the stack to be\n   aligned a certain way (i.e. SSE) and specifying this indicates to\n   the compiler to insert its usual stack alignment code\n3. *intel* - use intel syntax instead of the default AT&T.\n\n```rust\n# #![feature(asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() {\nlet result: i32;\nunsafe {\n   asm!(\"mov eax, 2\" : \"={eax}\"(result) : : : \"intel\")\n}\nprintln!(\"eax is currently {}\", result);\n# }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## More Information\n\nThe current implementation of the `asm!` macro is a direct binding to [LLVM's\ninline assembler expressions][llvm-docs], so be sure to check out [their\ndocumentation as well][llvm-docs] for more information about clobbers,\nconstraints, etc.\n\n[llvm-docs]: http://llvm.org/docs/LangRef.html#inline-assembler-expressions\n"
  },
  {
    "path": "trpl/intrinsics.md",
    "content": "% Intrinsics\n\n> **Note**: intrinsics will forever have an unstable interface, it is\n> recommended to use the stable interfaces of libcore rather than intrinsics\n> directly.\n\nThese are imported as if they were FFI functions, with the special\n`rust-intrinsic` ABI. For example, if one was in a freestanding\ncontext, but wished to be able to `transmute` between types, and\nperform efficient pointer arithmetic, one would import those functions\nvia a declaration like\n\n```rust\n#![feature(intrinsics)]\n# fn main() {}\n\nextern \"rust-intrinsic\" {\n    fn transmute<T, U>(x: T) -> U;\n\n    fn offset<T>(dst: *const T, offset: isize) -> *const T;\n}\n```\n\nAs with any other FFI functions, these are always `unsafe` to call.\n\n"
  },
  {
    "path": "trpl/iterators.md",
    "content": "% Iterators\n\nLet's talk about loops.\n\nRemember Rust's `for` loop? Here's an example:\n\n```rust\nfor x in 0..10 {\n    println!(\"{}\", x);\n}\n```\n\nNow that you know more Rust, we can talk in detail about how this works.\nRanges (the `0..10`) are 'iterators'. An iterator is something that we can\ncall the `.next()` method on repeatedly, and it gives us a sequence of things.\n\n(By the way, a range with two dots like `0..10` is inclusive on the left (so it\nstarts at 0) and exclusive on the right (so it ends at 9). A mathematician\nwould write \"[0, 10)\". To get a range that goes all the way up to 10 you can\nwrite `0...10`.)\n\nLike this:\n\n```rust\nlet mut range = 0..10;\n\nloop {\n    match range.next() {\n        Some(x) => {\n            println!(\"{}\", x);\n        },\n        None => { break }\n    }\n}\n```\n\nWe make a mutable binding to the range, which is our iterator. We then `loop`,\nwith an inner `match`. This `match` is used on the result of `range.next()`,\nwhich gives us a reference to the next value of the iterator. `next` returns an\n`Option<i32>`, in this case, which will be `Some(i32)` when we have a value and\n`None` once we run out. If we get `Some(i32)`, we print it out, and if we get\n`None`, we `break` out of the loop.\n\nThis code sample is basically the same as our `for` loop version. The `for`\nloop is a handy way to write this `loop`/`match`/`break` construct.\n\n`for` loops aren't the only thing that uses iterators, however. Writing your\nown iterator involves implementing the `Iterator` trait. While doing that is\noutside of the scope of this guide, Rust provides a number of useful iterators\nto accomplish various tasks. But first, a few notes about limitations of ranges.\n\nRanges are very primitive, and we often can use better alternatives. Consider the\nfollowing Rust anti-pattern: using ranges to emulate a C-style `for` loop. Let’s\nsuppose you needed to iterate over the contents of a vector. You may be tempted\nto write this:\n\n```rust\nlet nums = vec![1, 2, 3];\n\nfor i in 0..nums.len() {\n    println!(\"{}\", nums[i]);\n}\n```\n\nThis is strictly worse than using an actual iterator. You can iterate over vectors\ndirectly, so write this:\n\n```rust\nlet nums = vec![1, 2, 3];\n\nfor num in &nums {\n    println!(\"{}\", num);\n}\n```\n\nThere are two reasons for this. First, this more directly expresses what we\nmean. We iterate through the entire vector, rather than iterating through\nindexes, and then indexing the vector. Second, this version is more efficient:\nthe first version will have extra bounds checking because it used indexing,\n`nums[i]`. But since we yield a reference to each element of the vector in turn\nwith the iterator, there's no bounds checking in the second example. This is\nvery common with iterators: we can ignore unnecessary bounds checks, but still\nknow that we're safe.\n\nThere's another detail here that's not 100% clear because of how `println!`\nworks. `num` is actually of type `&i32`. That is, it's a reference to an `i32`,\nnot an `i32` itself. `println!` handles the dereferencing for us, so we don't\nsee it. This code works fine too:\n\n```rust\nlet nums = vec![1, 2, 3];\n\nfor num in &nums {\n    println!(\"{}\", *num);\n}\n```\n\nNow we're explicitly dereferencing `num`. Why does `&nums` give us\nreferences?  Firstly, because we explicitly asked it to with\n`&`. Secondly, if it gave us the data itself, we would have to be its\nowner, which would involve making a copy of the data and giving us the\ncopy. With references, we're only borrowing a reference to the data,\nand so it's only passing a reference, without needing to do the move.\n\nSo, now that we've established that ranges are often not what you want, let's\ntalk about what you do want instead.\n\nThere are three broad classes of things that are relevant here: iterators,\n*iterator adaptors*, and *consumers*. Here's some definitions:\n\n* *iterators* give you a sequence of values.\n* *iterator adaptors* operate on an iterator, producing a new iterator with a\n  different output sequence.\n* *consumers* operate on an iterator, producing some final set of values.\n\nLet's talk about consumers first, since you've already seen an iterator, ranges.\n\n## Consumers\n\nA *consumer* operates on an iterator, returning some kind of value or values.\nThe most common consumer is `collect()`. This code doesn't quite compile,\nbut it shows the intention:\n\n```rust,ignore\nlet one_to_one_hundred = (1..101).collect();\n```\n\nAs you can see, we call `collect()` on our iterator. `collect()` takes\nas many values as the iterator will give it, and returns a collection\nof the results. So why won't this compile? Rust can't determine what\ntype of things you want to collect, and so you need to let it know.\nHere's the version that does compile:\n\n```rust\nlet one_to_one_hundred = (1..101).collect::<Vec<i32>>();\n```\n\nIf you remember, the `::<>` syntax allows us to give a type hint,\nand so we tell it that we want a vector of integers. You don't always\nneed to use the whole type, though. Using a `_` will let you provide\na partial hint:\n\n```rust\nlet one_to_one_hundred = (1..101).collect::<Vec<_>>();\n```\n\nThis says \"Collect into a `Vec<T>`, please, but infer what the `T` is for me.\"\n`_` is sometimes called a \"type placeholder\" for this reason.\n\n`collect()` is the most common consumer, but there are others too. `find()`\nis one:\n\n```rust\nlet greater_than_forty_two = (0..100)\n                             .find(|x| *x > 42);\n\nmatch greater_than_forty_two {\n    Some(_) => println!(\"Found a match!\"),\n    None => println!(\"No match found :(\"),\n}\n```\n\n`find` takes a closure, and works on a reference to each element of an\niterator. This closure returns `true` if the element is the element we're\nlooking for, and `false` otherwise. `find` returns the first element satisfying\nthe specified predicate. Because we might not find a matching element, `find`\nreturns an `Option` rather than the element itself.\n\nAnother important consumer is `fold`. Here's what it looks like:\n\n```rust\nlet sum = (1..4).fold(0, |sum, x| sum + x);\n```\n\n`fold()` is a consumer that looks like this:\n`fold(base, |accumulator, element| ...)`. It takes two arguments: the first\nis an element called the *base*. The second is a closure that itself takes two\narguments: the first is called the *accumulator*, and the second is an\n*element*. Upon each iteration, the closure is called, and the result is the\nvalue of the accumulator on the next iteration. On the first iteration, the\nbase is the value of the accumulator.\n\nOkay, that's a bit confusing. Let's examine the values of all of these things\nin this iterator:\n\n| base | accumulator | element | closure result |\n|------|-------------|---------|----------------|\n| 0    | 0           | 1       | 1              |\n| 0    | 1           | 2       | 3              |\n| 0    | 3           | 3       | 6              |\n\nWe called `fold()` with these arguments:\n\n```rust\n# (1..4)\n.fold(0, |sum, x| sum + x);\n```\n\nSo, `0` is our base, `sum` is our accumulator, and `x` is our element.  On the\nfirst iteration, we set `sum` to `0`, and `x` is the first element of `nums`,\n`1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second\niteration, that value becomes our accumulator, `sum`, and the element is\nthe second element of the array, `2`. `1 + 2 = 3`, and so that becomes\nthe value of the accumulator for the last iteration. On that iteration,\n`x` is the last element, `3`, and `3 + 3 = 6`, which is our final\nresult for our sum. `1 + 2 + 3 = 6`, and that's the result we got.\n\nWhew. `fold` can be a bit strange the first few times you see it, but once it\nclicks, you can use it all over the place. Any time you have a list of things,\nand you want a single result, `fold` is appropriate.\n\nConsumers are important due to one additional property of iterators we haven't\ntalked about yet: laziness. Let's talk some more about iterators, and you'll\nsee why consumers matter.\n\n## Iterators\n\nAs we've said before, an iterator is something that we can call the\n`.next()` method on repeatedly, and it gives us a sequence of things.\nBecause you need to call the method, this means that iterators\ncan be *lazy* and not generate all of the values upfront. This code,\nfor example, does not actually generate the numbers `1-99`, instead\ncreating a value that merely represents the sequence:\n\n```rust\nlet nums = 1..100;\n```\n\nSince we didn't do anything with the range, it didn't generate the sequence.\nLet's add the consumer:\n\n```rust\nlet nums = (1..100).collect::<Vec<i32>>();\n```\n\nNow, `collect()` will require that the range gives it some numbers, and so\nit will do the work of generating the sequence.\n\nRanges are one of two basic iterators that you'll see. The other is `iter()`.\n`iter()` can turn a vector into a simple iterator that gives you each element\nin turn:\n\n```rust\nlet nums = vec![1, 2, 3];\n\nfor num in nums.iter() {\n   println!(\"{}\", num);\n}\n```\n\nThese two basic iterators should serve you well. There are some more\nadvanced iterators, including ones that are infinite.\n\nThat's enough about iterators. Iterator adaptors are the last concept\nwe need to talk about with regards to iterators. Let's get to it!\n\n## Iterator adaptors\n\n*Iterator adaptors* take an iterator and modify it somehow, producing\na new iterator. The simplest one is called `map`:\n\n```rust,ignore\n(1..100).map(|x| x + 1);\n```\n\n`map` is called upon another iterator, and produces a new iterator where each\nelement reference has the closure it's been given as an argument called on it.\nSo this would give us the numbers from `2-100`. Well, almost! If you\ncompile the example, you'll get a warning:\n\n```text\nwarning: unused result which must be used: iterator adaptors are lazy and\n         do nothing unless consumed, #[warn(unused_must_use)] on by default\n(1..100).map(|x| x + 1);\n ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\n\nLaziness strikes again! That closure will never execute. This example\ndoesn't print any numbers:\n\n```rust,ignore\n(1..100).map(|x| println!(\"{}\", x));\n```\n\nIf you are trying to execute a closure on an iterator for its side effects,\nuse `for` instead.\n\nThere are tons of interesting iterator adaptors. `take(n)` will return an\niterator over the next `n` elements of the original iterator. Let's try it out\nwith an infinite iterator:\n\n```rust\nfor i in (1..).take(5) {\n    println!(\"{}\", i);\n}\n```\n\nThis will print\n\n```text\n1\n2\n3\n4\n5\n```\n\n`filter()` is an adapter that takes a closure as an argument. This closure\nreturns `true` or `false`. The new iterator `filter()` produces\nonly the elements that the closure returns `true` for:\n\n```rust\nfor i in (1..100).filter(|&x| x % 2 == 0) {\n    println!(\"{}\", i);\n}\n```\n\nThis will print all of the even numbers between one and a hundred.\n(Note that, unlike `map`, the closure passed to `filter` is passed a reference\nto the element instead of the element itself. The filter predicate here uses\nthe `&x` pattern to extract the integer. The filter closure is passed a\nreference because it returns `true` or `false` instead of the element,\nso the `filter` implementation must retain ownership to put the elements\ninto the newly constructed iterator.)\n\nYou can chain all three things together: start with an iterator, adapt it\na few times, and then consume the result. Check it out:\n\n```rust\n(1..)\n    .filter(|&x| x % 2 == 0)\n    .filter(|&x| x % 3 == 0)\n    .take(5)\n    .collect::<Vec<i32>>();\n```\n\nThis will give you a vector containing `6`, `12`, `18`, `24`, and `30`.\n\nThis is just a small taste of what iterators, iterator adaptors, and consumers\ncan help you with. There are a number of really useful iterators, and you can\nwrite your own as well. Iterators provide a safe, efficient way to manipulate\nall kinds of lists. They're a little unusual at first, but if you play with\nthem, you'll get hooked. For a full list of the different iterators and\nconsumers, check out the [iterator module documentation](../std/iter/index.html).\n"
  },
  {
    "path": "trpl/lang-items.md",
    "content": "% Lang items\n\n> **Note**: lang items are often provided by crates in the Rust distribution,\n> and lang items themselves have an unstable interface. It is recommended to use\n> officially distributed crates instead of defining your own lang items.\n\nThe `rustc` compiler has certain pluggable operations, that is,\nfunctionality that isn't hard-coded into the language, but is\nimplemented in libraries, with a special marker to tell the compiler\nit exists. The marker is the attribute `#[lang = \"...\"]` and there are\nvarious different values of `...`, i.e. various different 'lang\nitems'.\n\nFor example, `Box` pointers require two lang items, one for allocation\nand one for deallocation. A freestanding program that uses the `Box`\nsugar for dynamic allocations via `malloc` and `free`:\n\n```rust,ignore\n#![feature(lang_items, box_syntax, start, libc)]\n#![no_std]\n\nextern crate libc;\n\nextern {\n    fn abort() -> !;\n}\n\n#[lang = \"owned_box\"]\npub struct Box<T>(*mut T);\n\n#[lang = \"exchange_malloc\"]\nunsafe fn allocate(size: usize, _align: usize) -> *mut u8 {\n    let p = libc::malloc(size as libc::size_t) as *mut u8;\n\n    // malloc failed\n    if p as usize == 0 {\n        abort();\n    }\n\n    p\n}\n\n#[lang = \"exchange_free\"]\nunsafe fn deallocate(ptr: *mut u8, _size: usize, _align: usize) {\n    libc::free(ptr as *mut libc::c_void)\n}\n\n#[lang = \"box_free\"]\nunsafe fn box_free<T>(ptr: *mut T) {\n    deallocate(ptr as *mut u8, ::core::mem::size_of::<T>(), ::core::mem::align_of::<T>());\n}\n\n#[start]\nfn main(argc: isize, argv: *const *const u8) -> isize {\n    let x = box 1;\n\n    0\n}\n\n#[lang = \"eh_personality\"] extern fn eh_personality() {}\n#[lang = \"panic_fmt\"] fn panic_fmt() -> ! { loop {} }\n# #[lang = \"eh_unwind_resume\"] extern fn rust_eh_unwind_resume() {}\n# #[no_mangle] pub extern fn rust_eh_register_frames () {}\n# #[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nNote the use of `abort`: the `exchange_malloc` lang item is assumed to\nreturn a valid pointer, and so needs to do the check internally.\n\nOther features provided by lang items include:\n\n- overloadable operators via traits: the traits corresponding to the\n  `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all\n  marked with lang items; those specific four are `eq`, `ord`,\n  `deref`, and `add` respectively.\n- stack unwinding and general failure; the `eh_personality`, `fail`\n  and `fail_bounds_checks` lang items.\n- the traits in `std::marker` used to indicate types of\n  various kinds; lang items `send`, `sync` and `copy`.\n- the marker types and variance indicators found in\n  `std::marker`; lang items `covariant_type`,\n  `contravariant_lifetime`, etc.\n\nLang items are loaded lazily by the compiler; e.g. if one never uses\n`Box` then there is no need to define functions for `exchange_malloc`\nand `exchange_free`. `rustc` will emit an error when an item is needed\nbut not found in the current crate or any that it depends on.\n"
  },
  {
    "path": "trpl/lifetimes.md",
    "content": "% Lifetimes\n\nThis is the last of three sections presenting Rust’s ownership system. This is one of\nRust’s most distinct and compelling features, with which Rust developers should\nbecome quite acquainted. Ownership is how Rust achieves its largest goal,\nmemory safety. There are a few distinct concepts, each with its own chapter:\n\n* [ownership][ownership], the key concept\n* [borrowing][borrowing], and their associated feature ‘references’\n* lifetimes, which you’re reading now\n\nThese three chapters are related, and in order. You’ll need all three to fully\nunderstand the ownership system.\n\n[ownership]: ownership.html\n[borrowing]: references-and-borrowing.html\n\n# Meta\n\nBefore we get to the details, two important notes about the ownership system.\n\nRust has a focus on safety and speed. It accomplishes these goals through many\n‘zero-cost abstractions’, which means that in Rust, abstractions cost as little\nas possible in order to make them work. The ownership system is a prime example\nof a zero-cost abstraction. All of the analysis we’ll talk about in this guide\nis _done at compile time_. You do not pay any run-time cost for any of these\nfeatures.\n\nHowever, this system does have a certain cost: learning curve. Many new users\nto Rust experience something we like to call ‘fighting with the borrow\nchecker’, where the Rust compiler refuses to compile a program that the author\nthinks is valid. This often happens because the programmer’s mental model of\nhow ownership should work doesn’t match the actual rules that Rust implements.\nYou probably will experience similar things at first. There is good news,\nhowever: more experienced Rust developers report that once they work with the\nrules of the ownership system for a period of time, they fight the borrow\nchecker less and less.\n\nWith that in mind, let’s learn about lifetimes.\n\n# Lifetimes\n\nLending out a reference to a resource that someone else owns can be\ncomplicated. For example, imagine this set of operations:\n\n1. I acquire a handle to some kind of resource.\n2. I lend you a reference to the resource.\n3. I decide I’m done with the resource, and deallocate it, while you still have\n  your reference.\n4. You decide to use the resource.\n\nUh oh! Your reference is pointing to an invalid resource. This is called a\ndangling pointer or ‘use after free’, when the resource is memory.\n\nTo fix this, we have to make sure that step four never happens after step\nthree. The ownership system in Rust does this through a concept called\nlifetimes, which describe the scope that a reference is valid for.\n\nWhen we have a function that takes an argument by reference, we can be\nimplicit or explicit about the lifetime of the reference:\n\n```rust\n// implicit\nfn foo(x: &i32) {\n}\n\n// explicit\nfn bar<'a>(x: &'a i32) {\n}\n```\n\nThe `'a` reads ‘the lifetime a’. Technically, every reference has some lifetime\nassociated with it, but the compiler lets you elide (i.e. omit, see\n[\"Lifetime Elision\"][lifetime-elision] below) them in common cases.\nBefore we get to that, though, let’s break the explicit example down:\n\n[lifetime-elision]: #lifetime-elision\n\n```rust,ignore\nfn bar<'a>(...)\n```\n\nWe previously talked a little about [function syntax][functions], but we didn’t\ndiscuss the `<>`s after a function’s name. A function can have ‘generic\nparameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss\nother kinds of generics [later in the book][generics], but for now, let’s\nfocus on the lifetimes aspect.\n\n[functions]: functions.html\n[generics]: generics.html\n\nWe use `<>` to declare our lifetimes. This says that `bar` has one lifetime,\n`'a`. If we had two reference parameters, it would look like this:\n\n\n```rust,ignore\nfn bar<'a, 'b>(...)\n```\n\nThen in our parameter list, we use the lifetimes we’ve named:\n\n```rust,ignore\n...(x: &'a i32)\n```\n\nIf we wanted a `&mut` reference, we’d do this:\n\n```rust,ignore\n...(x: &'a mut i32)\n```\n\nIf you compare `&mut i32` to `&'a mut i32`, they’re the same, it’s that\nthe lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut\ni32` as ‘a mutable reference to an `i32`’ and `&'a mut i32` as ‘a mutable\nreference to an `i32` with the lifetime `'a`’.\n\n# In `struct`s\n\nYou’ll also need explicit lifetimes when working with [`struct`][structs]s that\ncontain references:\n\n```rust\nstruct Foo<'a> {\n    x: &'a i32,\n}\n\nfn main() {\n    let y = &5; // this is the same as `let _y = 5; let y = &_y;`\n    let f = Foo { x: y };\n\n    println!(\"{}\", f.x);\n}\n```\n\n[structs]: structs.html\n\nAs you can see, `struct`s can also have lifetimes. In a similar way to functions,\n\n```rust\nstruct Foo<'a> {\n# x: &'a i32,\n# }\n```\n\ndeclares a lifetime, and\n\n```rust\n# struct Foo<'a> {\nx: &'a i32,\n# }\n```\n\nuses it. So why do we need a lifetime here? We need to ensure that any reference\nto a `Foo` cannot outlive the reference to an `i32` it contains.\n\n## `impl` blocks\n\nLet’s implement a method on `Foo`:\n\n```rust\nstruct Foo<'a> {\n    x: &'a i32,\n}\n\nimpl<'a> Foo<'a> {\n    fn x(&self) -> &'a i32 { self.x }\n}\n\nfn main() {\n    let y = &5; // this is the same as `let _y = 5; let y = &_y;`\n    let f = Foo { x: y };\n\n    println!(\"x is: {}\", f.x());\n}\n```\n\nAs you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat\n`'a` twice, like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>`\nuses it.\n\n## Multiple lifetimes\n\nIf you have multiple references, you can use the same lifetime multiple times:\n\n```rust\nfn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str {\n#    x\n# }\n```\n\nThis says that `x` and `y` both are alive for the same scope, and that the\nreturn value is also alive for that scope. If you wanted `x` and `y` to have\ndifferent lifetimes, you can use multiple lifetime parameters:\n\n```rust\nfn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {\n#    x\n# }\n```\n\nIn this example, `x` and `y` have different valid scopes, but the return value\nhas the same lifetime as `x`.\n\n## Thinking in scopes\n\nA way to think about lifetimes is to visualize the scope that a reference is\nvalid for. For example:\n\n```rust\nfn main() {\n    let y = &5;     // -+ y goes into scope\n                    //  |\n    // stuff        //  |\n                    //  |\n}                   // -+ y goes out of scope\n```\n\nAdding in our `Foo`:\n\n```rust\nstruct Foo<'a> {\n    x: &'a i32,\n}\n\nfn main() {\n    let y = &5;           // -+ y goes into scope\n    let f = Foo { x: y }; // -+ f goes into scope\n    // stuff              //  |\n                          //  |\n}                         // -+ f and y go out of scope\n```\n\nOur `f` lives within the scope of `y`, so everything works. What if it didn’t?\nThis code won’t work:\n\n```rust,ignore\nstruct Foo<'a> {\n    x: &'a i32,\n}\n\nfn main() {\n    let x;                    // -+ x goes into scope\n                              //  |\n    {                         //  |\n        let y = &5;           // ---+ y goes into scope\n        let f = Foo { x: y }; // ---+ f goes into scope\n        x = &f.x;             //  | | error here\n    }                         // ---+ f and y go out of scope\n                              //  |\n    println!(\"{}\", x);        //  |\n}                             // -+ x goes out of scope\n```\n\nWhew! As you can see here, the scopes of `f` and `y` are smaller than the scope\nof `x`. But when we do `x = &f.x`, we make `x` a reference to something that’s\nabout to go out of scope.\n\nNamed lifetimes are a way of giving these scopes a name. Giving something a\nname is the first step towards being able to talk about it.\n\n## 'static\n\nThe lifetime named ‘static’ is a special lifetime. It signals that something\nhas the lifetime of the entire program. Most Rust programmers first come across\n`'static` when dealing with strings:\n\n```rust\nlet x: &'static str = \"Hello, world.\";\n```\n\nString literals have the type `&'static str` because the reference is always\nalive: they are baked into the data segment of the final binary. Another\nexample are globals:\n\n```rust\nstatic FOO: i32 = 5;\nlet x: &'static i32 = &FOO;\n```\n\nThis adds an `i32` to the data segment of the binary, and `x` is a reference\nto it.\n\n## Lifetime Elision\n\nRust supports powerful local type inference in the bodies of functions but not in their item signatures. \nIt's forbidden to allow reasoning about types based on the item signature alone. \nHowever, for ergonomic reasons, a very restricted secondary inference algorithm called \n“lifetime elision” does apply when judging lifetimes. Lifetime elision is concerned solely to infer \nlifetime parameters using three easily memorizable and unambiguous rules. This means lifetime elision \nacts as a shorthand for writing an item signature, while not hiding\naway the actual types involved as full local inference would if applied to it.\n\nWhen talking about lifetime elision, we use the terms *input lifetime* and\n*output lifetime*. An *input lifetime* is a lifetime associated with a parameter\nof a function, and an *output lifetime* is a lifetime associated with the return\nvalue of a function. For example, this function has an input lifetime:\n\n```rust,ignore\nfn foo<'a>(bar: &'a str)\n```\n\nThis one has an output lifetime:\n\n```rust,ignore\nfn foo<'a>() -> &'a str\n```\n\nThis one has a lifetime in both positions:\n\n```rust,ignore\nfn foo<'a>(bar: &'a str) -> &'a str\n```\n\nHere are the three rules:\n\n* Each elided lifetime in a function’s arguments becomes a distinct lifetime\n  parameter.\n\n* If there is exactly one input lifetime, elided or not, that lifetime is\n  assigned to all elided lifetimes in the return values of that function.\n\n* If there are multiple input lifetimes, but one of them is `&self` or `&mut\n  self`, the lifetime of `self` is assigned to all elided output lifetimes.\n\nOtherwise, it is an error to elide an output lifetime.\n\n### Examples\n\nHere are some examples of functions with elided lifetimes.  We’ve paired each\nexample of an elided lifetime with its expanded form.\n\n```rust,ignore\nfn print(s: &str); // elided\nfn print<'a>(s: &'a str); // expanded\n\nfn debug(lvl: u32, s: &str); // elided\nfn debug<'a>(lvl: u32, s: &'a str); // expanded\n```\n\nIn the preceding example, `lvl` doesn’t need a lifetime because it’s not a\nreference (`&`). Only things relating to references (such as a `struct`\nwhich contains a reference) need lifetimes.\n\n```rust,ignore\nfn substr(s: &str, until: u32) -> &str; // elided\nfn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded\n\nfn get_str() -> &str; // ILLEGAL, no inputs\n\nfn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs\nfn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous\n\nfn get_mut(&mut self) -> &mut T; // elided\nfn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded\n\nfn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided\nfn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded\n\nfn new(buf: &mut [u8]) -> BufWriter; // elided\nfn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded\n```\n"
  },
  {
    "path": "trpl/loops.md",
    "content": "% Loops\n\nRust currently provides three approaches to performing some kind of iterative activity. They are: `loop`, `while` and `for`. Each approach has its own set of uses.\n\n## loop\n\nThe infinite `loop` is the simplest form of loop available in Rust. Using the keyword `loop`, Rust provides a way to loop indefinitely until some terminating statement is reached. Rust's infinite `loop`s look like this:\n\n```rust,ignore\nloop {\n    println!(\"Loop forever!\");\n}\n```\n\n## while\n\nRust also has a `while` loop. It looks like this:\n\n```rust\nlet mut x = 5; // mut x: i32\nlet mut done = false; // mut done: bool\n\nwhile !done {\n    x += x - 3;\n\n    println!(\"{}\", x);\n\n    if x % 5 == 0 {\n        done = true;\n    }\n}\n```\n\n`while` loops are the correct choice when you’re not sure how many times\nyou need to loop.\n\nIf you need an infinite loop, you may be tempted to write this:\n\n```rust,ignore\nwhile true {\n```\n\nHowever, `loop` is far better suited to handle this case:\n\n```rust,ignore\nloop {\n```\n\nRust’s control-flow analysis treats this construct differently than a `while\ntrue`, since we know that it will always loop. In general, the more information\nwe can give to the compiler, the better it can do with safety and code\ngeneration, so you should always prefer `loop` when you plan to loop\ninfinitely.\n\n## for\n\nThe `for` loop is used to loop a particular number of times. Rust’s `for` loops\nwork a bit differently than in other systems languages, however. Rust’s `for`\nloop doesn’t look like this “C-style” `for` loop:\n\n```c\nfor (x = 0; x < 10; x++) {\n    printf( \"%d\\n\", x );\n}\n```\n\nInstead, it looks like this:\n\n```rust\nfor x in 0..10 {\n    println!(\"{}\", x); // x: i32\n}\n```\n\nIn slightly more abstract terms,\n\n```rust,ignore\nfor var in expression {\n    code\n}\n```\n\nThe expression is an item that can be converted into an [iterator] using\n[`IntoIterator`]. The iterator gives back a series of elements. Each element is\none iteration of the loop. That value is then bound to the name `var`, which is\nvalid for the loop body. Once the body is over, the next value is fetched from\nthe iterator, and we loop another time. When there are no more values, the `for`\nloop is over.\n\n[iterator]: iterators.html\n[`IntoIterator`]: ../std/iter/trait.IntoIterator.html\n\nIn our example, `0..10` is an expression that takes a start and an end position,\nand gives an iterator over those values. The upper bound is exclusive, though,\nso our loop will print `0` through `9`, not `10`.\n\nRust does not have the “C-style” `for` loop on purpose. Manually controlling\neach element of the loop is complicated and error prone, even for experienced C\ndevelopers.\n\n### Enumerate\n\nWhen you need to keep track of how many times you already looped, you can use the `.enumerate()` function.\n\n#### On ranges:\n\n```rust\nfor (index, value) in (5..10).enumerate() {\n    println!(\"index = {} and value = {}\", index, value);\n}\n```\n\nOutputs:\n\n```text\nindex = 0 and value = 5\nindex = 1 and value = 6\nindex = 2 and value = 7\nindex = 3 and value = 8\nindex = 4 and value = 9\n```\n\nDon't forget to add the parentheses around the range.\n\n#### On iterators:\n\n```rust\nlet lines = \"hello\\nworld\".lines();\n\nfor (linenumber, line) in lines.enumerate() {\n    println!(\"{}: {}\", linenumber, line);\n}\n```\n\nOutputs:\n\n```text\n0: hello\n1: world\n```\n\n## Ending iteration early\n\nLet’s take a look at that `while` loop we had earlier:\n\n```rust\nlet mut x = 5;\nlet mut done = false;\n\nwhile !done {\n    x += x - 3;\n\n    println!(\"{}\", x);\n\n    if x % 5 == 0 {\n        done = true;\n    }\n}\n```\n\nWe had to keep a dedicated `mut` boolean variable binding, `done`, to know\nwhen we should exit out of the loop. Rust has two keywords to help us with\nmodifying iteration: `break` and `continue`.\n\nIn this case, we can write the loop in a better way with `break`:\n\n```rust\nlet mut x = 5;\n\nloop {\n    x += x - 3;\n\n    println!(\"{}\", x);\n\n    if x % 5 == 0 { break; }\n}\n```\n\nWe now loop forever with `loop` and use `break` to break out early. Issuing an explicit `return` statement will also serve to terminate the loop early.\n\n`continue` is similar, but instead of ending the loop, it goes to the next\niteration. This will only print the odd numbers:\n\n```rust\nfor x in 0..10 {\n    if x % 2 == 0 { continue; }\n\n    println!(\"{}\", x);\n}\n```\n\n## Loop labels\n\nYou may also encounter situations where you have nested loops and need to\nspecify which one your `break` or `continue` statement is for. Like most\nother languages, by default a `break` or `continue` will apply to innermost\nloop. In a situation where you would like to `break` or `continue` for one\nof the outer loops, you can use labels to specify which loop the `break` or\n `continue` statement applies to. This will only print when both `x` and `y` are\n odd:\n\n```rust\n'outer: for x in 0..10 {\n    'inner: for y in 0..10 {\n        if x % 2 == 0 { continue 'outer; } // continues the loop over x\n        if y % 2 == 0 { continue 'inner; } // continues the loop over y\n        println!(\"x: {}, y: {}\", x, y);\n    }\n}\n```\n"
  },
  {
    "path": "trpl/macros.md",
    "content": "% Macros\n\nBy now you’ve learned about many of the tools Rust provides for abstracting and\nreusing code. These units of code reuse have a rich semantic structure. For\nexample, functions have a type signature, type parameters have trait bounds,\nand overloaded functions must belong to a particular trait.\n\nThis structure means that Rust’s core abstractions have powerful compile-time\ncorrectness checking. But this comes at the price of reduced flexibility. If\nyou visually identify a pattern of repeated code, you may find it’s difficult\nor cumbersome to express that pattern as a generic function, a trait, or\nanything else within Rust’s semantics.\n\nMacros allow us to abstract at a syntactic level. A macro invocation is\nshorthand for an \"expanded\" syntactic form. This expansion happens early in\ncompilation, before any static checking. As a result, macros can capture many\npatterns of code reuse that Rust’s core abstractions cannot.\n\nThe drawback is that macro-based code can be harder to understand, because\nfewer of the built-in rules apply. Like an ordinary function, a well-behaved\nmacro can be used without understanding its implementation. However, it can be\ndifficult to design a well-behaved macro!  Additionally, compiler errors in\nmacro code are harder to interpret, because they describe problems in the\nexpanded code, not the source-level form that developers use.\n\nThese drawbacks make macros something of a \"feature of last resort\". That’s not\nto say that macros are bad; they are part of Rust because sometimes they’re\nneeded for truly concise, well-abstracted code. Just keep this tradeoff in\nmind.\n\n# Defining a macro\n\nYou may have seen the `vec!` macro, used to initialize a [vector][vector] with\nany number of elements.\n\n[vector]: vectors.html\n\n```rust\nlet x: Vec<u32> = vec![1, 2, 3];\n# assert_eq!(x, [1, 2, 3]);\n```\n\nThis can’t be an ordinary function, because it takes any number of arguments.\nBut we can imagine it as syntactic shorthand for\n\n```rust\nlet x: Vec<u32> = {\n    let mut temp_vec = Vec::new();\n    temp_vec.push(1);\n    temp_vec.push(2);\n    temp_vec.push(3);\n    temp_vec\n};\n# assert_eq!(x, [1, 2, 3]);\n```\n\nWe can implement this shorthand, using a macro: [^actual]\n\n[^actual]: The actual definition of `vec!` in libcollections differs from the\n           one presented here, for reasons of efficiency and reusability.\n\n```rust\nmacro_rules! vec {\n    ( $( $x:expr ),* ) => {\n        {\n            let mut temp_vec = Vec::new();\n            $(\n                temp_vec.push($x);\n            )*\n            temp_vec\n        }\n    };\n}\n# fn main() {\n#     assert_eq!(vec![1,2,3], [1, 2, 3]);\n# }\n```\n\nWhoa, that’s a lot of new syntax! Let’s break it down.\n\n```rust,ignore\nmacro_rules! vec { ... }\n```\n\nThis says we’re defining a macro named `vec`, much as `fn vec` would define a\nfunction named `vec`. In prose, we informally write a macro’s name with an\nexclamation point, e.g. `vec!`. The exclamation point is part of the invocation\nsyntax and serves to distinguish a macro from an ordinary function.\n\n## Matching\n\nThe macro is defined through a series of rules, which are pattern-matching\ncases. Above, we had\n\n```rust,ignore\n( $( $x:expr ),* ) => { ... };\n```\n\nThis is like a `match` expression arm, but the matching happens on Rust syntax\ntrees, at compile time. The semicolon is optional on the last (here, only)\ncase. The \"pattern\" on the left-hand side of `=>` is known as a ‘matcher’.\nThese have [their own little grammar] within the language.\n\n[their own little grammar]: ../reference.html#macros\n\nThe matcher `$x:expr` will match any Rust expression, binding that syntax tree\nto the ‘metavariable’ `$x`. The identifier `expr` is a ‘fragment specifier’;\nthe full possibilities are enumerated later in this chapter.\nSurrounding the matcher with `$(...),*` will match zero or more expressions,\nseparated by commas.\n\nAside from the special matcher syntax, any Rust tokens that appear in a matcher\nmust match exactly. For example,\n\n```rust,ignore\nmacro_rules! foo {\n    (x => $e:expr) => (println!(\"mode X: {}\", $e));\n    (y => $e:expr) => (println!(\"mode Y: {}\", $e));\n}\n\nfn main() {\n    foo!(y => 3);\n}\n```\n\nwill print\n\n```text\nmode Y: 3\n```\n\nWith\n\n```rust,ignore\nfoo!(z => 3);\n```\n\nwe get the compiler error\n\n```text\nerror: no rules expected the token `z`\n```\n\n## Expansion\n\nThe right-hand side of a macro rule is ordinary Rust syntax, for the most part.\nBut we can splice in bits of syntax captured by the matcher. From the original\nexample:\n\n```rust,ignore\n$(\n    temp_vec.push($x);\n)*\n```\n\nEach matched expression `$x` will produce a single `push` statement in the\nmacro expansion. The repetition in the expansion proceeds in \"lockstep\" with\nrepetition in the matcher (more on this in a moment).\n\nBecause `$x` was already declared as matching an expression, we don’t repeat\n`:expr` on the right-hand side. Also, we don’t include a separating comma as\npart of the repetition operator. Instead, we have a terminating semicolon\nwithin the repeated block.\n\nAnother detail: the `vec!` macro has *two* pairs of braces on the right-hand\nside. They are often combined like so:\n\n```rust,ignore\nmacro_rules! foo {\n    () => {{\n        ...\n    }}\n}\n```\n\nThe outer braces are part of the syntax of `macro_rules!`. In fact, you can use\n`()` or `[]` instead. They simply delimit the right-hand side as a whole.\n\nThe inner braces are part of the expanded syntax. Remember, the `vec!` macro is\nused in an expression context. To write an expression with multiple statements,\nincluding `let`-bindings, we use a block. If your macro expands to a single\nexpression, you don’t need this extra layer of braces.\n\nNote that we never *declared* that the macro produces an expression. In fact,\nthis is not determined until we use the macro as an expression. With care, you\ncan write a macro whose expansion works in several contexts. For example,\nshorthand for a data type could be valid as either an expression or a pattern.\n\n## Repetition\n\nThe repetition operator follows two principal rules:\n\n1. `$(...)*` walks through one \"layer\" of repetitions, for all of the `$name`s\n   it contains, in lockstep, and\n2. each `$name` must be under at least as many `$(...)*`s as it was matched\n   against. If it is under more, it’ll be duplicated, as appropriate.\n\nThis baroque macro illustrates the duplication of variables from outer\nrepetition levels.\n\n```rust\nmacro_rules! o_O {\n    (\n        $(\n            $x:expr; [ $( $y:expr ),* ]\n        );*\n    ) => {\n        &[ $($( $x + $y ),*),* ]\n    }\n}\n\nfn main() {\n    let a: &[i32]\n        = o_O!(10; [1, 2, 3];\n               20; [4, 5, 6]);\n\n    assert_eq!(a, [11, 12, 13, 24, 25, 26]);\n}\n```\n\nThat’s most of the matcher syntax. These examples use `$(...)*`, which is a\n\"zero or more\" match. Alternatively you can write `$(...)+` for a \"one or\nmore\" match. Both forms optionally include a separator, which can be any token\nexcept `+` or `*`.\n\nThis system is based on\n\"[Macro-by-Example](https://www.cs.indiana.edu/ftp/techreports/TR206.pdf)\"\n(PDF link).\n\n# Hygiene\n\nSome languages implement macros using simple text substitution, which leads to\nvarious problems. For example, this C program prints `13` instead of the\nexpected `25`.\n\n```text\n#define FIVE_TIMES(x) 5 * x\n\nint main() {\n    printf(\"%d\\n\", FIVE_TIMES(2 + 3));\n    return 0;\n}\n```\n\nAfter expansion we have `5 * 2 + 3`, and multiplication has greater precedence\nthan addition. If you’ve used C macros a lot, you probably know the standard\nidioms for avoiding this problem, as well as five or six others. In Rust, we\ndon’t have to worry about it.\n\n```rust\nmacro_rules! five_times {\n    ($x:expr) => (5 * $x);\n}\n\nfn main() {\n    assert_eq!(25, five_times!(2 + 3));\n}\n```\n\nThe metavariable `$x` is parsed as a single expression node, and keeps its\nplace in the syntax tree even after substitution.\n\nAnother common problem in macro systems is ‘variable capture’. Here’s a C\nmacro, using [a GNU C extension] to emulate Rust’s expression blocks.\n\n[a GNU C extension]: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html\n\n```text\n#define LOG(msg) ({ \\\n    int state = get_log_state(); \\\n    if (state > 0) { \\\n        printf(\"log(%d): %s\\n\", state, msg); \\\n    } \\\n})\n```\n\nHere’s a simple use case that goes terribly wrong:\n\n```text\nconst char *state = \"reticulating splines\";\nLOG(state)\n```\n\nThis expands to\n\n```text\nconst char *state = \"reticulating splines\";\n{\n    int state = get_log_state();\n    if (state > 0) {\n        printf(\"log(%d): %s\\n\", state, state);\n    }\n}\n```\n\nThe second variable named `state` shadows the first one.  This is a problem\nbecause the print statement should refer to both of them.\n\nThe equivalent Rust macro has the desired behavior.\n\n```rust\n# fn get_log_state() -> i32 { 3 }\nmacro_rules! log {\n    ($msg:expr) => {{\n        let state: i32 = get_log_state();\n        if state > 0 {\n            println!(\"log({}): {}\", state, $msg);\n        }\n    }};\n}\n\nfn main() {\n    let state: &str = \"reticulating splines\";\n    log!(state);\n}\n```\n\nThis works because Rust has a [hygienic macro system]. Each macro expansion\nhappens in a distinct ‘syntax context’, and each variable is tagged with the\nsyntax context where it was introduced. It’s as though the variable `state`\ninside `main` is painted a different \"color\" from the variable `state` inside\nthe macro, and therefore they don’t conflict.\n\n[hygienic macro system]: https://en.wikipedia.org/wiki/Hygienic_macro\n\nThis also restricts the ability of macros to introduce new bindings at the\ninvocation site. Code such as the following will not work:\n\n```rust,ignore\nmacro_rules! foo {\n    () => (let x = 3;);\n}\n\nfn main() {\n    foo!();\n    println!(\"{}\", x);\n}\n```\n\nInstead you need to pass the variable name into the invocation, so that it’s\ntagged with the right syntax context.\n\n```rust\nmacro_rules! foo {\n    ($v:ident) => (let $v = 3;);\n}\n\nfn main() {\n    foo!(x);\n    println!(\"{}\", x);\n}\n```\n\nThis holds for `let` bindings and loop labels, but not for [items][items].\nSo the following code does compile:\n\n```rust\nmacro_rules! foo {\n    () => (fn x() { });\n}\n\nfn main() {\n    foo!();\n    x();\n}\n```\n\n[items]: ../reference.html#items\n\n# Recursive macros\n\nA macro’s expansion can include more macro invocations, including invocations\nof the very same macro being expanded.  These recursive macros are useful for\nprocessing tree-structured input, as illustrated by this (simplistic) HTML\nshorthand:\n\n```rust\n# #![allow(unused_must_use)]\nmacro_rules! write_html {\n    ($w:expr, ) => (());\n\n    ($w:expr, $e:tt) => (write!($w, \"{}\", $e));\n\n    ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{\n        write!($w, \"<{}>\", stringify!($tag));\n        write_html!($w, $($inner)*);\n        write!($w, \"</{}>\", stringify!($tag));\n        write_html!($w, $($rest)*);\n    }};\n}\n\nfn main() {\n#   // FIXME(#21826)\n    use std::fmt::Write;\n    let mut out = String::new();\n\n    write_html!(&mut out,\n        html[\n            head[title[\"Macros guide\"]]\n            body[h1[\"Macros are the best!\"]]\n        ]);\n\n    assert_eq!(out,\n        \"<html><head><title>Macros guide</title></head>\\\n         <body><h1>Macros are the best!</h1></body></html>\");\n}\n```\n\n# Debugging macro code\n\nTo see the results of expanding macros, run `rustc --pretty expanded`. The\noutput represents a whole crate, so you can also feed it back in to `rustc`,\nwhich will sometimes produce better error messages than the original\ncompilation. Note that the `--pretty expanded` output may have a different\nmeaning if multiple variables of the same name (but different syntax contexts)\nare in play in the same scope. In this case `--pretty expanded,hygiene` will\ntell you about the syntax contexts.\n\n`rustc` provides two syntax extensions that help with macro debugging. For now,\nthey are unstable and require feature gates.\n\n* `log_syntax!(...)` will print its arguments to standard output, at compile\n  time, and \"expand\" to nothing.\n\n* `trace_macros!(true)` will enable a compiler message every time a macro is\n  expanded. Use `trace_macros!(false)` later in expansion to turn it off.\n\n# Syntactic requirements\n\nEven when Rust code contains un-expanded macros, it can be parsed as a full\n[syntax tree][ast]. This property can be very useful for editors and other\ntools that process code. It also has a few consequences for the design of\nRust’s macro system.\n\n[ast]: glossary.html#abstract-syntax-tree\n\nOne consequence is that Rust must determine, when it parses a macro invocation,\nwhether the macro stands in for\n\n* zero or more items,\n* zero or more methods,\n* an expression,\n* a statement, or\n* a pattern.\n\nA macro invocation within a block could stand for some items, or for an\nexpression / statement. Rust uses a simple rule to resolve this ambiguity. A\nmacro invocation that stands for items must be either\n\n* delimited by curly braces, e.g. `foo! { ... }`, or\n* terminated by a semicolon, e.g. `foo!(...);`\n\nAnother consequence of pre-expansion parsing is that the macro invocation must\nconsist of valid Rust tokens. Furthermore, parentheses, brackets, and braces\nmust be balanced within a macro invocation. For example, `foo!([)` is\nforbidden. This allows Rust to know where the macro invocation ends.\n\nMore formally, the macro invocation body must be a sequence of ‘token trees’.\nA token tree is defined recursively as either\n\n* a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or\n* any other single token.\n\nWithin a matcher, each metavariable has a ‘fragment specifier’, identifying\nwhich syntactic form it matches.\n\n* `ident`: an identifier. Examples: `x`; `foo`.\n* `path`: a qualified name. Example: `T::SpecialA`.\n* `expr`: an expression. Examples: `2 + 2`; `if true { 1 } else { 2 }`; `f(42)`.\n* `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`.\n* `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`.\n* `stmt`: a single statement. Example: `let x = 3`.\n* `block`: a brace-delimited sequence of statements and optionally an expression. Example:\n  `{ log(error, \"hi\"); return 12; }`.\n* `item`: an [item][item]. Examples: `fn foo() { }`; `struct Bar;`.\n* `meta`: a \"meta item\", as found in attributes. Example: `cfg(target_os = \"windows\")`.\n* `tt`: a single token tree.\n\nThere are additional rules regarding the next token after a metavariable:\n\n* `expr` and `stmt` variables may only be followed by one of: `=> , ;`\n* `ty` and `path` variables may only be followed by one of: `=> , = | ; : > [ { as where`\n* `pat` variables may only be followed by one of: `=> , = | if in`\n* Other variables may be followed by any token.\n\nThese rules provide some flexibility for Rust’s syntax to evolve without\nbreaking existing macros.\n\nThe macro system does not deal with parse ambiguity at all. For example, the\ngrammar `$($i:ident)* $e:expr` will always fail to parse, because the parser would\nbe forced to choose between parsing `$i` and parsing `$e`. Changing the\ninvocation syntax to put a distinctive token in front can solve the problem. In\nthis case, you can write `$(I $i:ident)* E $e:expr`.\n\n[item]: ../reference.html#items\n\n# Scoping and macro import/export\n\nMacros are expanded at an early stage in compilation, before name resolution.\nOne downside is that scoping works differently for macros, compared to other\nconstructs in the language.\n\nDefinition and expansion of macros both happen in a single depth-first,\nlexical-order traversal of a crate’s source. So a macro defined at module scope\nis visible to any subsequent code in the same module, which includes the body\nof any subsequent child `mod` items.\n\nA macro defined within the body of a single `fn`, or anywhere else not at\nmodule scope, is visible only within that item.\n\nIf a module has the `macro_use` attribute, its macros are also visible in its\nparent module after the child’s `mod` item. If the parent also has `macro_use`\nthen the macros will be visible in the grandparent after the parent’s `mod`\nitem, and so forth.\n\nThe `macro_use` attribute can also appear on `extern crate`. In this context\nit controls which macros are loaded from the external crate, e.g.\n\n```rust,ignore\n#[macro_use(foo, bar)]\nextern crate baz;\n```\n\nIf the attribute is given simply as `#[macro_use]`, all macros are loaded. If\nthere is no `#[macro_use]` attribute then no macros are loaded. Only macros\ndefined with the `#[macro_export]` attribute may be loaded.\n\nTo load a crate’s macros without linking it into the output, use `#[no_link]`\nas well.\n\nAn example:\n\n```rust\nmacro_rules! m1 { () => (()) }\n\n// visible here: m1\n\nmod foo {\n    // visible here: m1\n\n    #[macro_export]\n    macro_rules! m2 { () => (()) }\n\n    // visible here: m1, m2\n}\n\n// visible here: m1\n\nmacro_rules! m3 { () => (()) }\n\n// visible here: m1, m3\n\n#[macro_use]\nmod bar {\n    // visible here: m1, m3\n\n    macro_rules! m4 { () => (()) }\n\n    // visible here: m1, m3, m4\n}\n\n// visible here: m1, m3, m4\n# fn main() { }\n```\n\nWhen this library is loaded with `#[macro_use] extern crate`, only `m2` will\nbe imported.\n\nThe Rust Reference has a [listing of macro-related\nattributes](../reference.html#macro-related-attributes).\n\n# The variable `$crate`\n\nA further difficulty occurs when a macro is used in multiple crates. Say that\n`mylib` defines\n\n```rust\npub fn increment(x: u32) -> u32 {\n    x + 1\n}\n\n#[macro_export]\nmacro_rules! inc_a {\n    ($x:expr) => ( ::increment($x) )\n}\n\n#[macro_export]\nmacro_rules! inc_b {\n    ($x:expr) => ( ::mylib::increment($x) )\n}\n# fn main() { }\n```\n\n`inc_a` only works within `mylib`, while `inc_b` only works outside the\nlibrary. Furthermore, `inc_b` will break if the user imports `mylib` under\nanother name.\n\nRust does not (yet) have a hygiene system for crate references, but it does\nprovide a simple workaround for this problem. Within a macro imported from a\ncrate named `foo`, the special macro variable `$crate` will expand to `::foo`.\nBy contrast, when a macro is defined and then used in the same crate, `$crate`\nwill expand to nothing. This means we can write\n\n```rust\n#[macro_export]\nmacro_rules! inc {\n    ($x:expr) => ( $crate::increment($x) )\n}\n# fn main() { }\n```\n\nto define a single macro that works both inside and outside our library. The\nfunction name will expand to either `::increment` or `::mylib::increment`.\n\nTo keep this system simple and correct, `#[macro_use] extern crate ...` may\nonly appear at the root of your crate, not inside `mod`.\n\n# The deep end\n\nThe introductory chapter mentioned recursive macros, but it did not give the\nfull story. Recursive macros are useful for another reason: Each recursive\ninvocation gives you another opportunity to pattern-match the macro’s\narguments.\n\nAs an extreme example, it is possible, though hardly advisable, to implement\nthe [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton\nwithin Rust’s macro system.\n\n```rust\nmacro_rules! bct {\n    // cmd 0:  d ... => ...\n    (0, $($ps:tt),* ; $_d:tt)\n        => (bct!($($ps),*, 0 ; ));\n    (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)\n        => (bct!($($ps),*, 0 ; $($ds),*));\n\n    // cmd 1p:  1 ... => 1 ... p\n    (1, $p:tt, $($ps:tt),* ; 1)\n        => (bct!($($ps),*, 1, $p ; 1, $p));\n    (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)\n        => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));\n\n    // cmd 1p:  0 ... => 0 ...\n    (1, $p:tt, $($ps:tt),* ; $($ds:tt),*)\n        => (bct!($($ps),*, 1, $p ; $($ds),*));\n\n    // halt on empty data string\n    ( $($ps:tt),* ; )\n        => (());\n}\n```\n\nExercise: use macros to reduce duplication in the above definition of the\n`bct!` macro.\n\n# Common macros\n\nHere are some common macros you’ll see in Rust code.\n\n## panic!\n\nThis macro causes the current thread to panic. You can give it a message\nto panic with:\n\n```rust,no_run\npanic!(\"oh no!\");\n```\n\n## vec!\n\nThe `vec!` macro is used throughout the book, so you’ve probably seen it\nalready. It creates `Vec<T>`s with ease:\n\n```rust\nlet v = vec![1, 2, 3, 4, 5];\n```\n\nIt also lets you make vectors with repeating values. For example, a hundred\nzeroes:\n\n```rust\nlet v = vec![0; 100];\n```\n\n## assert! and assert_eq!\n\nThese two macros are used in tests. `assert!` takes a boolean. `assert_eq!`\ntakes two values and checks them for equality. `true` passes, `false` `panic!`s.\nLike this:\n\n```rust,no_run\n// A-ok!\n\nassert!(true);\nassert_eq!(5, 3 + 2);\n\n// nope :(\n\nassert!(5 < 3);\nassert_eq!(5, 3);\n```\n\n## try!\n\n`try!` is used for error handling. It takes something that can return a\n`Result<T, E>`, and gives `T` if it’s a `Ok<T>`, and `return`s with the\n`Err(E)` if it’s that. Like this:\n\n```rust,no_run\nuse std::fs::File;\n\nfn foo() -> std::io::Result<()> {\n    let f = try!(File::create(\"foo.txt\"));\n\n    Ok(())\n}\n```\n\nThis is cleaner than doing this:\n\n```rust,no_run\nuse std::fs::File;\n\nfn foo() -> std::io::Result<()> {\n    let f = File::create(\"foo.txt\");\n\n    let f = match f {\n        Ok(t) => t,\n        Err(e) => return Err(e),\n    };\n\n    Ok(())\n}\n```\n\n## unreachable!\n\nThis macro is used when you think some code should never execute:\n\n```rust\nif false {\n    unreachable!();\n}\n```\n\nSometimes, the compiler may make you have a different branch that you know\nwill never, ever run. In these cases, use this macro, so that if you end\nup wrong, you’ll get a `panic!` about it.\n\n```rust\nlet x: Option<i32> = None;\n\nmatch x {\n    Some(_) => unreachable!(),\n    None => println!(\"I know x is None!\"),\n}\n```\n\n## unimplemented!\n\nThe `unimplemented!` macro can be used when you’re trying to get your functions\nto typecheck, and don’t want to worry about writing out the body of the\nfunction. One example of this situation is implementing a trait with multiple\nrequired methods, where you want to tackle one at a time. Define the others\nas `unimplemented!` until you’re ready to write them.\n\n# Procedural macros\n\nIf Rust’s macro system can’t do what you need, you may want to write a\n[compiler plugin](compiler-plugins.html) instead. Compared to `macro_rules!`\nmacros, this is significantly more work, the interfaces are much less stable,\nand bugs can be much harder to track down. In exchange you get the\nflexibility of running arbitrary Rust code within the compiler. Syntax\nextension plugins are sometimes called ‘procedural macros’ for this reason.\n"
  },
  {
    "path": "trpl/match.md",
    "content": "% Match\n\nOften, a simple [`if`][if]/`else` isn’t enough, because you have more than two\npossible options. Also, conditions can get quite complex. Rust\nhas a keyword, `match`, that allows you to replace complicated `if`/`else`\ngroupings with something more powerful. Check it out:\n\n```rust\nlet x = 5;\n\nmatch x {\n    1 => println!(\"one\"),\n    2 => println!(\"two\"),\n    3 => println!(\"three\"),\n    4 => println!(\"four\"),\n    5 => println!(\"five\"),\n    _ => println!(\"something else\"),\n}\n```\n\n[if]: if.html\n\n`match` takes an expression and then branches based on its value. Each ‘arm’ of\nthe branch is of the form `val => expression`. When the value matches, that arm’s\nexpression will be evaluated. It’s called `match` because of the term ‘pattern\nmatching’, which `match` is an implementation of. There’s a [separate section on\npatterns][patterns] that covers all the patterns that are possible here.\n\n[patterns]: patterns.html\n\nOne of the many advantages of `match` is it enforces ‘exhaustiveness checking’.\nFor example if we remove the last arm with the underscore `_`, the compiler will\ngive us an error:\n\n```text\nerror: non-exhaustive patterns: `_` not covered\n```\n\nRust is telling us that we forgot some value. The compiler infers from `x` that it\ncan have any 32bit integer value; for example -2,147,483,648 to 2,147,483,647. The `_` acts \nas a 'catch-all', and will catch all possible values that *aren't* specified in \nan arm of `match`. As you can see in the previous example, we provide `match` \narms for integers 1-5, if `x` is 6 or any other value, then it is caught by `_`.\n\n`match` is also an expression, which means we can use it on the right-hand\nside of a `let` binding or directly where an expression is used:\n\n```rust\nlet x = 5;\n\nlet number = match x {\n    1 => \"one\",\n    2 => \"two\",\n    3 => \"three\",\n    4 => \"four\",\n    5 => \"five\",\n    _ => \"something else\",\n};\n```\n\nSometimes it’s a nice way of converting something from one type to another; in\nthis example the integers are converted to `String`.\n\n# Matching on enums\n\nAnother important use of the `match` keyword is to process the possible\nvariants of an enum:\n\n```rust\nenum Message {\n    Quit,\n    ChangeColor(i32, i32, i32),\n    Move { x: i32, y: i32 },\n    Write(String),\n}\n\nfn quit() { /* ... */ }\nfn change_color(r: i32, g: i32, b: i32) { /* ... */ }\nfn move_cursor(x: i32, y: i32) { /* ... */ }\n\nfn process_message(msg: Message) {\n    match msg {\n        Message::Quit => quit(),\n        Message::ChangeColor(r, g, b) => change_color(r, g, b),\n        Message::Move { x: x, y: y } => move_cursor(x, y),\n        Message::Write(s) => println!(\"{}\", s),\n    };\n}\n```\n\nAgain, the Rust compiler checks exhaustiveness, so it demands that you\nhave a match arm for every variant of the enum. If you leave one off, it\nwill give you a compile-time error unless you use `_` or provide all possible\narms.\n\nUnlike the previous uses of `match`, you can’t use the normal `if`\nstatement to do this. You can use the [`if let`][if-let] statement,\nwhich can be seen as an abbreviated form of `match`.\n\n[if-let]: if-let.html\n"
  },
  {
    "path": "trpl/method-syntax.md",
    "content": "% Method Syntax\n\nFunctions are great, but if you want to call a bunch of them on some data, it\ncan be awkward. Consider this code:\n\n```rust,ignore\nbaz(bar(foo));\n```\n\nWe would read this left-to-right, and so we see ‘baz bar foo’. But this isn’t the\norder that the functions would get called in, that’s inside-out: ‘foo bar baz’.\nWouldn’t it be nice if we could do this instead?\n\n```rust,ignore\nfoo.bar().baz();\n```\n\nLuckily, as you may have guessed with the leading question, you can! Rust provides\nthe ability to use this ‘method call syntax’ via the `impl` keyword.\n\n# Method calls\n\nHere’s how it works:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n}\n\nfn main() {\n    let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };\n    println!(\"{}\", c.area());\n}\n```\n\nThis will print `12.566371`.\n\nWe’ve made a `struct` that represents a circle. We then write an `impl` block,\nand inside it, define a method, `area`.\n\nMethods take a special first parameter, of which there are three variants:\n`self`, `&self`, and `&mut self`. You can think of this first parameter as\nbeing the `foo` in `foo.bar()`. The three variants correspond to the three\nkinds of things `foo` could be: `self` if it’s a value on the stack,\n`&self` if it’s a reference, and `&mut self` if it’s a mutable reference.\nBecause we took the `&self` parameter to `area`, we can use it like any\nother parameter. Because we know it’s a `Circle`, we can access the `radius`\nlike we would with any other `struct`.\n\nWe should default to using `&self`, as you should prefer borrowing over taking\nownership, as well as taking immutable references over mutable ones. Here’s an\nexample of all three variants:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn reference(&self) {\n       println!(\"taking self by reference!\");\n    }\n\n    fn mutable_reference(&mut self) {\n       println!(\"taking self by mutable reference!\");\n    }\n\n    fn takes_ownership(self) {\n       println!(\"taking ownership of self!\");\n    }\n}\n```\n\nYou can use as many `impl` blocks as you’d like. The previous example could\nhave also been written like this:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn reference(&self) {\n       println!(\"taking self by reference!\");\n    }\n}\n\nimpl Circle {\n    fn mutable_reference(&mut self) {\n       println!(\"taking self by mutable reference!\");\n    }\n}\n\nimpl Circle {\n    fn takes_ownership(self) {\n       println!(\"taking ownership of self!\");\n    }\n}\n```\n\n# Chaining method calls\n\nSo, now we know how to call a method, such as `foo.bar()`. But what about our\noriginal example, `foo.bar().baz()`? This is called ‘method chaining’. Let’s\nlook at an example:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n\n    fn grow(&self, increment: f64) -> Circle {\n        Circle { x: self.x, y: self.y, radius: self.radius + increment }\n    }\n}\n\nfn main() {\n    let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };\n    println!(\"{}\", c.area());\n\n    let d = c.grow(2.0).area();\n    println!(\"{}\", d);\n}\n```\n\nCheck the return type:\n\n```rust\n# struct Circle;\n# impl Circle {\nfn grow(&self, increment: f64) -> Circle {\n# Circle } }\n```\n\nWe say we’re returning a `Circle`. With this method, we can grow a new\n`Circle` to any arbitrary size.\n\n# Associated functions\n\nYou can also define associated functions that do not take a `self` parameter.\nHere’s a pattern that’s very common in Rust code:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn new(x: f64, y: f64, radius: f64) -> Circle {\n        Circle {\n            x: x,\n            y: y,\n            radius: radius,\n        }\n    }\n}\n\nfn main() {\n    let c = Circle::new(0.0, 0.0, 2.0);\n}\n```\n\nThis ‘associated function’ builds a new `Circle` for us. Note that associated\nfunctions are called with the `Struct::function()` syntax, rather than the\n`ref.method()` syntax. Some other languages call associated functions ‘static\nmethods’.\n\n# Builder Pattern\n\nLet’s say that we want our users to be able to create `Circle`s, but we will\nallow them to only set the properties they care about. Otherwise, the `x`\nand `y` attributes will be `0.0`, and the `radius` will be `1.0`. Rust doesn’t\nhave method overloading, named arguments, or variable arguments. We employ\nthe builder pattern instead. It looks like this:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n}\n\nstruct CircleBuilder {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl CircleBuilder {\n    fn new() -> CircleBuilder {\n        CircleBuilder { x: 0.0, y: 0.0, radius: 1.0, }\n    }\n\n    fn x(&mut self, coordinate: f64) -> &mut CircleBuilder {\n        self.x = coordinate;\n        self\n    }\n\n    fn y(&mut self, coordinate: f64) -> &mut CircleBuilder {\n        self.y = coordinate;\n        self\n    }\n\n    fn radius(&mut self, radius: f64) -> &mut CircleBuilder {\n        self.radius = radius;\n        self\n    }\n\n    fn finalize(&self) -> Circle {\n        Circle { x: self.x, y: self.y, radius: self.radius }\n    }\n}\n\nfn main() {\n    let c = CircleBuilder::new()\n                .x(1.0)\n                .y(2.0)\n                .radius(2.0)\n                .finalize();\n\n    println!(\"area: {}\", c.area());\n    println!(\"x: {}\", c.x);\n    println!(\"y: {}\", c.y);\n}\n```\n\nWhat we’ve done here is make another `struct`, `CircleBuilder`. We’ve defined our\nbuilder methods on it. We’ve also defined our `area()` method on `Circle`. We\nalso made one more method on `CircleBuilder`: `finalize()`. This method creates\nour final `Circle` from the builder. Now, we’ve used the type system to enforce\nour concerns: we can use the methods on `CircleBuilder` to constrain making\n`Circle`s in any way we choose.\n"
  },
  {
    "path": "trpl/mutability.md",
    "content": "% Mutability\n\nMutability, the ability to change something, works a bit differently in Rust\nthan in other languages. The first aspect of mutability is its non-default\nstatus:\n\n```rust,ignore\nlet x = 5;\nx = 6; // error!\n```\n\nWe can introduce mutability with the `mut` keyword:\n\n```rust\nlet mut x = 5;\n\nx = 6; // no problem!\n```\n\nThis is a mutable [variable binding][vb]. When a binding is mutable, it means\nyou’re allowed to change what the binding points to. So in the above example,\nit’s not so much that the value at `x` is changing, but that the binding\nchanged from one `i32` to another.\n\n[vb]: variable-bindings.html\n\nYou can also create a [reference][ref] to it, using `&x`, but if you want to use the reference to change it, you will need a mutable reference:\n\n```rust\nlet mut x = 5;\nlet y = &mut x;\n```\n\n[ref]: references-and-borrowing.html\n\n`y` is an immutable binding to a mutable reference, which means that you can’t bind 'y' to something else (`y = &mut z`), but `y` can be used to bind `x` to something else (`*y = 5`). A subtle distinction.\n\nOf course, if you need both:\n\n```rust\nlet mut x = 5;\nlet mut y = &mut x;\n```\n\nNow `y` can be bound to another value, and the value it’s referencing can be\nchanged.\n\nIt’s important to note that `mut` is part of a [pattern][pattern], so you\ncan do things like this:\n\n```rust\nlet (mut x, y) = (5, 6);\n\nfn foo(mut x: i32) {\n# }\n```\n\nNote that here, the `x` is mutable, but not the `y`.\n\n[pattern]: patterns.html\n\n# Interior vs. Exterior Mutability\n\nHowever, when we say something is ‘immutable’ in Rust, that doesn’t mean that\nit’s not able to be changed: we are referring to its ‘exterior mutability’ that\nin this case is immutable. Consider, for example, [`Arc<T>`][arc]:\n\n```rust\nuse std::sync::Arc;\n\nlet x = Arc::new(5);\nlet y = x.clone();\n```\n\n[arc]: ../std/sync/struct.Arc.html\n\nWhen we call `clone()`, the `Arc<T>` needs to update the reference count. Yet\nwe’ve not used any `mut`s here, `x` is an immutable binding, and we didn’t take\n`&mut 5` or anything. So what gives?\n\nTo understand this, we have to go back to the core of Rust’s guiding\nphilosophy, memory safety, and the mechanism by which Rust guarantees it, the\n[ownership][ownership] system, and more specifically, [borrowing][borrowing]:\n\n> You may have one or the other of these two kinds of borrows, but not both at\n> the same time:\n>\n> * one or more references (`&T`) to a resource,\n> * exactly one mutable reference (`&mut T`).\n\n[ownership]: ownership.html\n[borrowing]: references-and-borrowing.html#borrowing\n\nSo, that’s the real definition of ‘immutability’: is this safe to have two\npointers to? In `Arc<T>`’s case, yes: the mutation is entirely contained inside\nthe structure itself. It’s not user facing. For this reason, it hands out `&T`\nwith `clone()`. If it handed out `&mut T`s, though, that would be a problem.\n\nOther types, like the ones in the [`std::cell`][stdcell] module, have the\nopposite: interior mutability. For example:\n\n```rust\nuse std::cell::RefCell;\n\nlet x = RefCell::new(42);\n\nlet y = x.borrow_mut();\n```\n\n[stdcell]: ../std/cell/index.html\n\nRefCell hands out `&mut` references to what’s inside of it with the\n`borrow_mut()` method. Isn’t that dangerous? What if we do:\n\n```rust,ignore\nuse std::cell::RefCell;\n\nlet x = RefCell::new(42);\n\nlet y = x.borrow_mut();\nlet z = x.borrow_mut();\n# (y, z);\n```\n\nThis will in fact panic, at runtime. This is what `RefCell` does: it enforces\nRust’s borrowing rules at runtime, and `panic!`s if they’re violated. This\nallows us to get around another aspect of Rust’s mutability rules. Let’s talk\nabout it first.\n\n## Field-level mutability\n\nMutability is a property of either a borrow (`&mut`) or a binding (`let mut`).\nThis means that, for example, you cannot have a [`struct`][struct] with\nsome fields mutable and some immutable:\n\n```rust,ignore\nstruct Point {\n    x: i32,\n    mut y: i32, // nope\n}\n```\n\nThe mutability of a struct is in its binding:\n\n```rust,ignore\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nlet mut a = Point { x: 5, y: 6 };\n\na.x = 10;\n\nlet b = Point { x: 5, y: 6};\n\nb.x = 10; // error: cannot assign to immutable field `b.x`\n```\n\n[struct]: structs.html\n\nHowever, by using [`Cell<T>`][cell], you can emulate field-level mutability:\n\n```rust\nuse std::cell::Cell;\n\nstruct Point {\n    x: i32,\n    y: Cell<i32>,\n}\n\nlet point = Point { x: 5, y: Cell::new(6) };\n\npoint.y.set(7);\n\nprintln!(\"y: {:?}\", point.y);\n```\n\n[cell]: ../std/cell/struct.Cell.html\n\nThis will print `y: Cell { value: 7 }`. We’ve successfully updated `y`.\n"
  },
  {
    "path": "trpl/nightly-rust.md",
    "content": "% Nightly Rust\n\nRust provides three distribution channels for Rust: nightly, beta, and stable.\nUnstable features are only available on nightly Rust. For more details on this\nprocess, see ‘[Stability as a deliverable][stability]’.\n\n[stability]: http://blog.rust-lang.org/2014/10/30/Stability.html\n\nTo install nightly Rust, you can use `rustup.sh`:\n\n```bash\n$ curl -s https://static.rust-lang.org/rustup.sh | sh -s -- --channel=nightly\n```\n\nIf you're concerned about the [potential insecurity][insecurity] of using `curl\n| sh`, please keep reading and see our disclaimer below. And feel free to\nuse a two-step version of the installation and examine our installation script:\n\n```bash\n$ curl -f -L https://static.rust-lang.org/rustup.sh -O\n$ sh rustup.sh --channel=nightly\n```\n\n[insecurity]: http://curlpipesh.tumblr.com\n\nIf you're on Windows, please download either the [32-bit installer][win32] or\nthe [64-bit installer][win64] and run it.\n\n[win32]: https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.msi\n[win64]: https://static.rust-lang.org/dist/rust-nightly-x86_64-pc-windows-gnu.msi\n\n## Uninstalling\n\nIf you decide you don't want Rust anymore, we'll be a bit sad, but that's okay.\nNot every programming language is great for everyone. Just run the uninstall\nscript:\n\n```bash\n$ sudo /usr/local/lib/rustlib/uninstall.sh\n```\n\nIf you used the Windows installer, re-run the `.msi` and it will give you\nan uninstall option.\n\nSome people, and somewhat rightfully so, get very upset when we tell you to\n`curl | sh`. Basically, when you do this, you are trusting that the good\npeople who maintain Rust aren't going to hack your computer and do bad things.\nThat's a good instinct! If you're one of those people, please check out the\ndocumentation on [building Rust from Source][from-source], or [the official\nbinary downloads][install-page].\n\n[from-source]: https://github.com/rust-lang/rust#building-from-source\n[install-page]: https://www.rust-lang.org/install.html\n\nOh, we should also mention the officially supported platforms:\n\n* Windows (7, 8, Server 2008 R2)\n* Linux (2.6.18 or later, various distributions), x86 and x86-64\n* OSX 10.7 (Lion) or greater, x86 and x86-64\n\nWe extensively test Rust on these platforms, and a few others, too, like\nAndroid. But these are the ones most likely to work, as they have the most\ntesting.\n\nFinally, a comment about Windows. Rust considers Windows to be a first-class\nplatform upon release, but if we're honest, the Windows experience isn't as\nintegrated as the Linux/OS X experience is. We're working on it! If anything\ndoes not work, it is a bug. Please let us know if that happens. Each and every\ncommit is tested against Windows like any other platform.\n\nIf you've got Rust installed, you can open up a shell, and type this:\n\n```bash\n$ rustc --version\n```\n\nYou should see the version number, commit hash, commit date and build date:\n\n```bash\nrustc 1.0.0-nightly (f11f3e7ba 2015-01-04) (built 2015-01-06)\n```\n\nIf you did, Rust has been installed successfully! Congrats!\n\nThis installer also installs a copy of the documentation locally, so you can\nread it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location.\nOn Windows, it's in a `share/doc` directory, inside wherever you installed Rust\nto.\n\nIf not, there are a number of places where you can get help. The easiest is\n[the #rust IRC channel on irc.mozilla.org][irc], which you can access through\n[Mibbit][mibbit]. Click that link, and you'll be chatting with other Rustaceans\n(a silly nickname we call ourselves), and we can help you out. Other great\nresources include [the user’s forum][users], and [Stack Overflow][stackoverflow].\n\n[irc]: irc://irc.mozilla.org/#rust\n[mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust\n[users]: https://users.rust-lang.org/\n[stackoverflow]: http://stackoverflow.com/questions/tagged/rust\n"
  },
  {
    "path": "trpl/no-stdlib.md",
    "content": "% No stdlib\n\nRust’s standard library provides a lot of useful functionality, but assumes\nsupport for various features of its host system: threads, networking, heap\nallocation, and others. There are systems that do not have these features,\nhowever, and Rust can work with those too! To do so, we tell Rust that we\ndon’t want to use the standard library via an attribute: `#![no_std]`.\n\n> Note: This feature is technically stable, but there are some caveats. For\n> one, you can build a `#![no_std]` _library_ on stable, but not a _binary_.\n> For details on libraries without the standard library, see [the chapter on\n> `#![no_std]`](using-rust-without-the-standard-library.html)\n\nObviously there's more to life than just libraries: one can use\n`#[no_std]` with an executable.\n\n### Using libc\n\nIn order to build a `#[no_std]` executable we will need libc as a dependency. We can specify\nthis using our `Cargo.toml` file:\n\n```toml\n[dependencies]\nlibc = { version = \"0.2.14\", default-features = false }\n```\n\nNote that the default features have been disabled. This is a critical step -\n**the default features of libc include the standard library and so must be\ndisabled.**\n\n### Writing an executable without stdlib\n\nControlling the entry point is possible in two ways: the `#[start]` attribute,\nor overriding the default shim for the C `main` function with your own.\n\nThe function marked `#[start]` is passed the command line parameters\nin the same format as C:\n\n```rust,ignore\n#![feature(lang_items)]\n#![feature(start)]\n#![no_std]\n\n// Pull in the system libc library for what crt0.o likely requires\nextern crate libc;\n\n// Entry point for this program\n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n    0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn eh_personality() {\n}\n\n#[lang = \"panic_fmt\"]\n#[no_mangle]\npub extern fn rust_begin_panic(_msg: core::fmt::Arguments,\n                               _file: &'static str,\n                               _line: u32) -> ! {\n    loop {}\n}\n```\n\nTo override the compiler-inserted `main` shim, one has to disable it\nwith `#![no_main]` and then create the appropriate symbol with the\ncorrect ABI and the correct name, which requires overriding the\ncompiler's name mangling too:\n\n```rust,ignore\n#![feature(lang_items)]\n#![feature(start)]\n#![no_std]\n#![no_main]\n\n// Pull in the system libc library for what crt0.o likely requires\nextern crate libc;\n\n// Entry point for this program\n#[no_mangle] // ensure that this symbol is called `main` in the output\npub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {\n    0\n}\n\n// These functions and traits are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn eh_personality() {\n}\n\n#[lang = \"panic_fmt\"]\n#[no_mangle]\npub extern fn rust_begin_panic(_msg: core::fmt::Arguments,\n                               _file: &'static str,\n                               _line: u32) -> ! {\n    loop {}\n}\n```\n\n## More about the langauge items\n\nThe compiler currently makes a few assumptions about symbols which are\navailable in the executable to call. Normally these functions are provided by\nthe standard library, but without it you must define your own. These symbols\nare called \"language items\", and they each have an internal name, and then a\nsignature that an implementation must conform to.\n\nThe first of these two functions, `eh_personality`, is used by the failure\nmechanisms of the compiler. This is often mapped to GCC's personality function\n(see the [libstd implementation][unwind] for more information), but crates\nwhich do not trigger a panic can be assured that this function is never\ncalled. Both the language item and the symbol name are `eh_personality`.\n \n[unwind]: https://github.com/rust-lang/rust/blob/master/src/libpanic_unwind/gcc.rs\n\nThe second function, `panic_fmt`, is also used by the failure mechanisms of the\ncompiler. When a panic happens, this controls the message that's displayed on\nthe screen. While the language item's name is `panic_fmt`, the symbol name is\n`rust_begin_panic`.\n"
  },
  {
    "path": "trpl/operators-and-overloading.md",
    "content": "% Operators and Overloading\n\nRust allows for a limited form of operator overloading. There are certain\noperators that are able to be overloaded. To support a particular operator\nbetween types, there’s a specific trait that you can implement, which then\noverloads the operator.\n\nFor example, the `+` operator can be overloaded with the `Add` trait:\n\n```rust\nuse std::ops::Add;\n\n#[derive(Debug)]\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nimpl Add for Point {\n    type Output = Point;\n\n    fn add(self, other: Point) -> Point {\n        Point { x: self.x + other.x, y: self.y + other.y }\n    }\n}\n\nfn main() {\n    let p1 = Point { x: 1, y: 0 };\n    let p2 = Point { x: 2, y: 3 };\n\n    let p3 = p1 + p2;\n\n    println!(\"{:?}\", p3);\n}\n```\n\nIn `main`, we can use `+` on our two `Point`s, since we’ve implemented\n`Add<Output=Point>` for `Point`.\n\nThere are a number of operators that can be overloaded this way, and all of\ntheir associated traits live in the [`std::ops`][stdops] module. Check out its\ndocumentation for the full list.\n\n[stdops]: ../std/ops/index.html\n\nImplementing these traits follows a pattern. Let’s look at [`Add`][add] in more\ndetail:\n\n```rust\n# mod foo {\npub trait Add<RHS = Self> {\n    type Output;\n\n    fn add(self, rhs: RHS) -> Self::Output;\n}\n# }\n```\n\n[add]: ../std/ops/trait.Add.html\n\nThere’s three types in total involved here: the type you `impl Add` for, `RHS`,\nwhich defaults to `Self`, and `Output`. For an expression `let z = x + y`, `x`\nis the `Self` type, `y` is the RHS, and `z` is the `Self::Output` type.\n\n```rust\n# struct Point;\n# use std::ops::Add;\nimpl Add<i32> for Point {\n    type Output = f64;\n\n    fn add(self, rhs: i32) -> f64 {\n        // add an i32 to a Point and get an f64\n# 1.0\n    }\n}\n```\n\nwill let you do this:\n\n```rust,ignore\nlet p: Point = // ...\nlet x: f64 = p + 2i32;\n```\n\n# Using operator traits in generic structs\n\nNow that we know how operator traits are defined, we can define our `HasArea`\ntrait and `Square` struct from the [traits chapter][traits] more generically:\n\n[traits]: traits.html\n\n```rust\nuse std::ops::Mul;\n\ntrait HasArea<T> {\n    fn area(&self) -> T;\n}\n\nstruct Square<T> {\n    x: T,\n    y: T,\n    side: T,\n}\n\nimpl<T> HasArea<T> for Square<T>\n        where T: Mul<Output=T> + Copy {\n    fn area(&self) -> T {\n        self.side * self.side\n    }\n}\n\nfn main() {\n    let s = Square {\n        x: 0.0f64,\n        y: 0.0f64,\n        side: 12.0f64,\n    };\n\n    println!(\"Area of s: {}\", s.area());\n}\n```\n\nFor `HasArea` and `Square`, we declare a type parameter `T` and replace\n`f64` with it. The `impl` needs more involved modifications:\n\n```rust,ignore\nimpl<T> HasArea<T> for Square<T>\n        where T: Mul<Output=T> + Copy { ... }\n```\n\nThe `area` method requires that we can multiply the sides, so we declare that\ntype `T` must implement `std::ops::Mul`. Like `Add`, mentioned above, `Mul`\nitself takes an `Output` parameter: since we know that numbers don't change\ntype when multiplied, we also set it to `T`. `T` must also support copying, so\nRust doesn't try to move `self.side` into the return value.\n"
  },
  {
    "path": "trpl/ownership.md",
    "content": "% Ownership\n\nThis is the first of three sections presenting Rust’s ownership system. This is one of\nRust’s most distinct and compelling features, with which Rust developers should\nbecome quite acquainted. Ownership is how Rust achieves its largest goal,\nmemory safety. There are a few distinct concepts, each with its own\nchapter:\n\n* ownership, which you’re reading now\n* [borrowing][borrowing], and their associated feature ‘references’\n* [lifetimes][lifetimes], an advanced concept of borrowing\n\nThese three chapters are related, and in order. You’ll need all three to fully\nunderstand the ownership system.\n\n[borrowing]: references-and-borrowing.html\n[lifetimes]: lifetimes.html\n\n# Meta\n\nBefore we get to the details, two important notes about the ownership system.\n\nRust has a focus on safety and speed. It accomplishes these goals through many\n‘zero-cost abstractions’, which means that in Rust, abstractions cost as little\nas possible in order to make them work. The ownership system is a prime example\nof a zero-cost abstraction. All of the analysis we’ll talk about in this guide\nis _done at compile time_. You do not pay any run-time cost for any of these\nfeatures.\n\nHowever, this system does have a certain cost: learning curve. Many new users\nto Rust experience something we like to call ‘fighting with the borrow\nchecker’, where the Rust compiler refuses to compile a program that the author\nthinks is valid. This often happens because the programmer’s mental model of\nhow ownership should work doesn’t match the actual rules that Rust implements.\nYou probably will experience similar things at first. There is good news,\nhowever: more experienced Rust developers report that once they work with the\nrules of the ownership system for a period of time, they fight the borrow\nchecker less and less.\n\nWith that in mind, let’s learn about ownership.\n\n# Ownership\n\n[Variable bindings][bindings] have a property in Rust: they ‘have ownership’\nof what they’re bound to. This means that when a binding goes out of scope,\nRust will free the bound resources. For example:\n\n```rust\nfn foo() {\n    let v = vec![1, 2, 3];\n}\n```\n\nWhen `v` comes into scope, a new [vector][vectors] is created on [the stack][stack],\nand it allocates space on [the heap][heap] for its elements. When `v` goes out\nof scope at the end of `foo()`, Rust will clean up everything related to the\nvector, even the heap-allocated memory. This happens deterministically, at the\nend of the scope.\n\nWe'll cover [vectors] in detail later in this chapter; we only use them\nhere as an example of a type that allocates space on the heap at runtime. They\nbehave like [arrays], except their size may change by `push()`ing more\nelements onto them.\n\nVectors have a [generic type][generics] `Vec<T>`, so in this example `v` will have type\n`Vec<i32>`. We'll cover generics in detail later in this chapter.\n\n[arrays]: primitive-types.html#arrays\n[vectors]: vectors.html\n[heap]: the-stack-and-the-heap.html#the-heap\n[stack]: the-stack-and-the-heap.html#the-stack\n[bindings]: variable-bindings.html\n[generics]: generics.html\n\n# Move semantics\n\nThere’s some more subtlety here, though: Rust ensures that there is _exactly\none_ binding to any given resource. For example, if we have a vector, we can\nassign it to another binding:\n\n```rust\nlet v = vec![1, 2, 3];\n\nlet v2 = v;\n```\n\nBut, if we try to use `v` afterwards, we get an error:\n\n```rust,ignore\nlet v = vec![1, 2, 3];\n\nlet v2 = v;\n\nprintln!(\"v[0] is: {}\", v[0]);\n```\n\nIt looks like this:\n\n```text\nerror: use of moved value: `v`\nprintln!(\"v[0] is: {}\", v[0]);\n                        ^\n```\n\nA similar thing happens if we define a function which takes ownership, and\ntry to use something after we’ve passed it as an argument:\n\n```rust,ignore\nfn take(v: Vec<i32>) {\n    // what happens here isn’t important.\n}\n\nlet v = vec![1, 2, 3];\n\ntake(v);\n\nprintln!(\"v[0] is: {}\", v[0]);\n```\n\nSame error: ‘use of moved value’. When we transfer ownership to something else,\nwe say that we’ve ‘moved’ the thing we refer to. You don’t need some sort of\nspecial annotation here, it’s the default thing that Rust does.\n\n## The details\n\nThe reason that we cannot use a binding after we’ve moved it is subtle, but\nimportant.\n\nWhen we write code like this:\n\n```rust\nlet x = 10;\n```\n\nRust allocates memory for an integer [i32] on the [stack][sh], copies the bit\npattern representing the value of 10 to the allocated memory and binds the\nvariable name x to this memory region for future reference.\n\n[i32]: primitive-types.html#numeric-types\n\nNow consider the following code fragment:\n\n```rust\nlet v = vec![1, 2, 3];\n\nlet mut v2 = v;\n```\n\nThe first line allocates memory for the vector object `v` on the stack like\nit does for `x` above. But in addition to that it also allocates some memory\non the [heap][sh] for the actual data (`[1, 2, 3]`). Rust copies the address\nof this heap allocation to an internal pointer, which is part of the vector\nobject placed on the stack (let's call it the data pointer).\n\nIt is worth pointing out (even at the risk of stating the obvious) that the\nvector object and its data live in separate memory regions instead of being a\nsingle contiguous memory allocation (due to reasons we will not go into at\nthis point of time). These two parts of the vector (the one on the stack and\none on the heap) must agree with each other at all times with regards to\nthings like the length, capacity, etc.\n\nWhen we move `v` to `v2`, Rust actually does a bitwise copy of the vector\nobject `v` into the stack allocation represented by `v2`. This shallow copy\ndoes not create a copy of the heap allocation containing the actual data.\nWhich means that there would be two pointers to the contents of the vector\nboth pointing to the same memory allocation on the heap. It would violate\nRust’s safety guarantees by introducing a data race if one could access both\n`v` and `v2` at the same time.\n\nFor example if we truncated the vector to just two elements through `v2`:\n\n```rust\n# let v = vec![1, 2, 3];\n# let mut v2 = v;\nv2.truncate(2);\n```\n\nand `v` were still accessible we'd end up with an invalid vector since `v`\nwould not know that the heap data has been truncated. Now, the part of the\nvector `v` on the stack does not agree with the corresponding part on the\nheap. `v` still thinks there are three elements in the vector and will\nhappily let us access the non existent element `v[2]` but as you might\nalready know this is a recipe for disaster. Especially because it might lead\nto a segmentation fault or worse allow an unauthorized user to read from\nmemory to which they don't have access.\n\nThis is why Rust forbids using `v` after we’ve done the move.\n\n[sh]: the-stack-and-the-heap.html\n\nIt’s also important to note that optimizations may remove the actual copy of\nthe bytes on the stack, depending on circumstances. So it may not be as\ninefficient as it initially seems.\n\n## `Copy` types\n\nWe’ve established that when ownership is transferred to another binding, you\ncannot use the original binding. However, there’s a [trait][traits] that changes this\nbehavior, and it’s called `Copy`. We haven’t discussed traits yet, but for now,\nyou can think of them as an annotation to a particular type that adds extra\nbehavior. For example:\n\n```rust\nlet v = 1;\n\nlet v2 = v;\n\nprintln!(\"v is: {}\", v);\n```\n\nIn this case, `v` is an `i32`, which implements the `Copy` trait. This means\nthat, just like a move, when we assign `v` to `v2`, a copy of the data is made.\nBut, unlike a move, we can still use `v` afterward. This is because an `i32`\nhas no pointers to data somewhere else, copying it is a full copy.\n\nAll primitive types implement the `Copy` trait and their ownership is\ntherefore not moved like one would assume, following the ‘ownership rules’.\nTo give an example, the two following snippets of code only compile because the\n`i32` and `bool` types implement the `Copy` trait.\n\n```rust\nfn main() {\n    let a = 5;\n\n    let _y = double(a);\n    println!(\"{}\", a);\n}\n\nfn double(x: i32) -> i32 {\n    x * 2\n}\n```\n\n```rust\nfn main() {\n    let a = true;\n\n    let _y = change_truth(a);\n    println!(\"{}\", a);\n}\n\nfn change_truth(x: bool) -> bool {\n    !x\n}\n```\n\nIf we had used types that do not implement the `Copy` trait,\nwe would have gotten a compile error because we tried to use a moved value.\n\n```text\nerror: use of moved value: `a`\nprintln!(\"{}\", a);\n               ^\n```\n\nWe will discuss how to make your own types `Copy` in the [traits][traits]\nsection.\n\n[traits]: traits.html\n\n# More than ownership\n\nOf course, if we had to hand ownership back with every function we wrote:\n\n```rust\nfn foo(v: Vec<i32>) -> Vec<i32> {\n    // do stuff with v\n\n    // hand back ownership\n    v\n}\n```\n\nThis would get very tedious. It gets worse the more things we want to take ownership of:\n\n```rust\nfn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {\n    // do stuff with v1 and v2\n\n    // hand back ownership, and the result of our function\n    (v1, v2, 42)\n}\n\nlet v1 = vec![1, 2, 3];\nlet v2 = vec![1, 2, 3];\n\nlet (v1, v2, answer) = foo(v1, v2);\n```\n\nUgh! The return type, return line, and calling the function gets way more\ncomplicated.\n\nLuckily, Rust offers a feature which helps us solve this problem.\nIt’s called borrowing and is the topic of the next section!\n\n"
  },
  {
    "path": "trpl/patterns.md",
    "content": "% Patterns\n\nPatterns are quite common in Rust. We use them in [variable\nbindings][bindings], [match expressions][match], and other places, too. Let’s go\non a whirlwind tour of all of the things patterns can do!\n\n[bindings]: variable-bindings.html\n[match]: match.html\n\nA quick refresher: you can match against literals directly, and `_` acts as an\n‘any’ case:\n\n```rust\nlet x = 1;\n\nmatch x {\n    1 => println!(\"one\"),\n    2 => println!(\"two\"),\n    3 => println!(\"three\"),\n    _ => println!(\"anything\"),\n}\n```\n\nThis prints `one`.\n\nThere’s one pitfall with patterns: like anything that introduces a new binding,\nthey introduce shadowing. For example:\n\n```rust\nlet x = 1;\nlet c = 'c';\n\nmatch c {\n    x => println!(\"x: {} c: {}\", x, c),\n}\n\nprintln!(\"x: {}\", x)\n```\n\nThis prints:\n\n```text\nx: c c: c\nx: 1\n```\n\nIn other words, `x =>` matches the pattern and introduces a new binding named\n`x`. This new binding is in scope for the match arm and takes on the value of\n`c`. Notice that the value of `x` outside the scope of the match has no bearing\non the value of `x` within it. Because we already have a binding named `x`, this\nnew `x` shadows it.\n\n# Multiple patterns\n\nYou can match multiple patterns with `|`:\n\n```rust\nlet x = 1;\n\nmatch x {\n    1 | 2 => println!(\"one or two\"),\n    3 => println!(\"three\"),\n    _ => println!(\"anything\"),\n}\n```\n\nThis prints `one or two`.\n\n# Destructuring\n\nIf you have a compound data type, like a [`struct`][struct], you can destructure it\ninside of a pattern:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nlet origin = Point { x: 0, y: 0 };\n\nmatch origin {\n    Point { x, y } => println!(\"({},{})\", x, y),\n}\n```\n\n[struct]: structs.html\n\nWe can use `:` to give a value a different name.\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nlet origin = Point { x: 0, y: 0 };\n\nmatch origin {\n    Point { x: x1, y: y1 } => println!(\"({},{})\", x1, y1),\n}\n```\n\nIf we only care about some of the values, we don’t have to give them all names:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nlet point = Point { x: 2, y: 3 };\n\nmatch point {\n    Point { x, .. } => println!(\"x is {}\", x),\n}\n```\n\nThis prints `x is 2`.\n\nYou can do this kind of match on any member, not only the first:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nlet point = Point { x: 2, y: 3 };\n\nmatch point {\n    Point { y, .. } => println!(\"y is {}\", y),\n}\n```\n\nThis prints `y is 3`.\n\nThis ‘destructuring’ behavior works on any compound data type, like\n[tuples][tuples] or [enums][enums].\n\n[tuples]: primitive-types.html#tuples\n[enums]: enums.html\n\n# Ignoring bindings\n\nYou can use `_` in a pattern to disregard the type and value.\nFor example, here’s a `match` against a `Result<T, E>`:\n\n```rust\n# let some_value: Result<i32, &'static str> = Err(\"There was an error\");\nmatch some_value {\n    Ok(value) => println!(\"got a value: {}\", value),\n    Err(_) => println!(\"an error occurred\"),\n}\n```\n\nIn the first arm, we bind the value inside the `Ok` variant to `value`. But\nin the `Err` arm, we use `_` to disregard the specific error, and print\na general error message.\n\n`_` is valid in any pattern that creates a binding. This can be useful to\nignore parts of a larger structure:\n\n```rust\nfn coordinate() -> (i32, i32, i32) {\n    // generate and return some sort of triple tuple\n# (1, 2, 3)\n}\n\nlet (x, _, z) = coordinate();\n```\n\nHere, we bind the first and last element of the tuple to `x` and `z`, but\nignore the middle element.\n\nIt’s worth noting that using `_` never binds the value in the first place,\nwhich means that the value does not move:\n\n```rust\nlet tuple: (u32, String) = (5, String::from(\"five\"));\n\n// Here, tuple is moved, because the String moved:\nlet (x, _s) = tuple;\n\n// The next line would give \"error: use of partially moved value: `tuple`\"\n// println!(\"Tuple is: {:?}\", tuple);\n\n// However,\n\nlet tuple = (5, String::from(\"five\"));\n\n// Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy:\nlet (x, _) = tuple;\n\n// That means this works:\nprintln!(\"Tuple is: {:?}\", tuple);\n```\n\nThis also means that any temporary variables will be dropped at the end of the\nstatement:\n\n```rust\n// Here, the String created will be dropped immediately, as it’s not bound:\n\nlet _ = String::from(\"  hello  \").trim();\n```\n\nYou can also use `..` in a pattern to disregard multiple values:\n\n```rust\nenum OptionalTuple {\n    Value(i32, i32, i32),\n    Missing,\n}\n\nlet x = OptionalTuple::Value(5, -2, 3);\n\nmatch x {\n    OptionalTuple::Value(..) => println!(\"Got a tuple!\"),\n    OptionalTuple::Missing => println!(\"No such luck.\"),\n}\n```\n\nThis prints `Got a tuple!`.\n\n# ref and ref mut\n\nIf you want to get a [reference][ref], use the `ref` keyword:\n\n```rust\nlet x = 5;\n\nmatch x {\n    ref r => println!(\"Got a reference to {}\", r),\n}\n```\n\nThis prints `Got a reference to 5`.\n\n[ref]: references-and-borrowing.html\n\nHere, the `r` inside the `match` has the type `&i32`. In other words, the `ref`\nkeyword _creates_ a reference, for use in the pattern. If you need a mutable\nreference, `ref mut` will work in the same way:\n\n```rust\nlet mut x = 5;\n\nmatch x {\n    ref mut mr => println!(\"Got a mutable reference to {}\", mr),\n}\n```\n\n# Ranges\n\nYou can match a range of values with `...`:\n\n```rust\nlet x = 1;\n\nmatch x {\n    1 ... 5 => println!(\"one through five\"),\n    _ => println!(\"anything\"),\n}\n```\n\nThis prints `one through five`.\n\nRanges are mostly used with integers and `char`s:\n\n```rust\nlet x = '💅';\n\nmatch x {\n    'a' ... 'j' => println!(\"early letter\"),\n    'k' ... 'z' => println!(\"late letter\"),\n    _ => println!(\"something else\"),\n}\n```\n\nThis prints `something else`.\n\n# Bindings\n\nYou can bind values to names with `@`:\n\n```rust\nlet x = 1;\n\nmatch x {\n    e @ 1 ... 5 => println!(\"got a range element {}\", e),\n    _ => println!(\"anything\"),\n}\n```\n\nThis prints `got a range element 1`. This is useful when you want to\ndo a complicated match of part of a data structure:\n\n```rust\n#[derive(Debug)]\nstruct Person {\n    name: Option<String>,\n}\n\nlet name = \"Steve\".to_string();\nlet x: Option<Person> = Some(Person { name: Some(name) });\nmatch x {\n    Some(Person { name: ref a @ Some(_), .. }) => println!(\"{:?}\", a),\n    _ => {}\n}\n```\n\nThis prints `Some(\"Steve\")`: we’ve bound the inner `name` to `a`.\n\nIf you use `@` with `|`, you need to make sure the name is bound in each part\nof the pattern:\n\n```rust\nlet x = 5;\n\nmatch x {\n    e @ 1 ... 5 | e @ 8 ... 10 => println!(\"got a range element {}\", e),\n    _ => println!(\"anything\"),\n}\n```\n\n# Guards\n\nYou can introduce ‘match guards’ with `if`:\n\n```rust\nenum OptionalInt {\n    Value(i32),\n    Missing,\n}\n\nlet x = OptionalInt::Value(5);\n\nmatch x {\n    OptionalInt::Value(i) if i > 5 => println!(\"Got an int bigger than five!\"),\n    OptionalInt::Value(..) => println!(\"Got an int!\"),\n    OptionalInt::Missing => println!(\"No such luck.\"),\n}\n```\n\nThis prints `Got an int!`.\n\nIf you’re using `if` with multiple patterns, the `if` applies to both sides:\n\n```rust\nlet x = 4;\nlet y = false;\n\nmatch x {\n    4 | 5 if y => println!(\"yes\"),\n    _ => println!(\"no\"),\n}\n```\n\nThis prints `no`, because the `if` applies to the whole of `4 | 5`, and not to\nonly the `5`. In other words, the precedence of `if` behaves like this:\n\n```text\n(4 | 5) if y => ...\n```\n\nnot this:\n\n```text\n4 | (5 if y) => ...\n```\n\n# Mix and Match\n\nWhew! That’s a lot of different ways to match things, and they can all be\nmixed and matched, depending on what you’re doing:\n\n```rust,ignore\nmatch x {\n    Foo { x: Some(ref name), y: None } => ...\n}\n```\n\nPatterns are very powerful. Make good use of them.\n"
  },
  {
    "path": "trpl/primitive-types.md",
    "content": "% Primitive Types\n\nThe Rust language has a number of types that are considered ‘primitive’. This\nmeans that they’re built-in to the language. Rust is structured in such a way\nthat the standard library also provides a number of useful types built on top\nof these ones, as well, but these are the most primitive.\n\n# Booleans\n\nRust has a built-in boolean type, named `bool`. It has two values, `true` and `false`:\n\n```rust\nlet x = true;\n\nlet y: bool = false;\n```\n\nA common use of booleans is in [`if` conditionals][if].\n\n[if]: if.html\n\nYou can find more documentation for `bool`s [in the standard library\ndocumentation][bool].\n\n[bool]: ../std/primitive.bool.html\n\n# `char`\n\nThe `char` type represents a single Unicode scalar value. You can create `char`s\nwith a single tick: (`'`)\n\n```rust\nlet x = 'x';\nlet two_hearts = '💕';\n```\n\nUnlike some other languages, this means that Rust’s `char` is not a single byte,\nbut four.\n\nYou can find more documentation for `char`s [in the standard library\ndocumentation][char].\n\n[char]: ../std/primitive.char.html\n\n# Numeric types\n\nRust has a variety of numeric types in a few categories: signed and unsigned,\nfixed and variable, floating-point and integer.\n\nThese types consist of two parts: the category, and the size. For example,\n`u16` is an unsigned type with sixteen bits of size. More bits lets you have\nbigger numbers.\n\nIf a number literal has nothing to cause its type to be inferred, it defaults:\n\n```rust\nlet x = 42; // x has type i32\n\nlet y = 1.0; // y has type f64\n```\n\nHere’s a list of the different numeric types, with links to their documentation\nin the standard library:\n\n* [i8](../std/primitive.i8.html)\n* [i16](../std/primitive.i16.html)\n* [i32](../std/primitive.i32.html)\n* [i64](../std/primitive.i64.html)\n* [u8](../std/primitive.u8.html)\n* [u16](../std/primitive.u16.html)\n* [u32](../std/primitive.u32.html)\n* [u64](../std/primitive.u64.html)\n* [isize](../std/primitive.isize.html)\n* [usize](../std/primitive.usize.html)\n* [f32](../std/primitive.f32.html)\n* [f64](../std/primitive.f64.html)\n\nLet’s go over them by category:\n\n## Signed and Unsigned\n\nInteger types come in two varieties: signed and unsigned. To understand the\ndifference, let’s consider a number with four bits of size. A signed, four-bit\nnumber would let you store numbers from `-8` to `+7`. Signed numbers use\n“two’s complement representation”. An unsigned four bit number, since it does\nnot need to store negatives, can store values from `0` to `+15`.\n\nUnsigned types use a `u` for their category, and signed types use `i`. The `i`\nis for ‘integer’. So `u8` is an eight-bit unsigned number, and `i8` is an\neight-bit signed number.\n\n## Fixed-size types\n\nFixed-size types have a specific number of bits in their representation. Valid\nbit sizes are `8`, `16`, `32`, and `64`. So, `u32` is an unsigned, 32-bit integer,\nand `i64` is a signed, 64-bit integer.\n\n## Variable-size types\n\nRust also provides types whose particular size depends on the underlying machine\narchitecture. Their range is sufficient to express the size of any collection, so\nthese types have ‘size’ as the category. They come in signed and unsigned varieties\nwhich account for two types: `isize` and `usize`.\n\n## Floating-point types\n\nRust also has two floating point types: `f32` and `f64`. These correspond to\nIEEE-754 single and double precision numbers.\n\n# Arrays\n\nLike many programming languages, Rust has list types to represent a sequence of\nthings. The most basic is the *array*, a fixed-size list of elements of the\nsame type. By default, arrays are immutable.\n\n```rust\nlet a = [1, 2, 3]; // a: [i32; 3]\nlet mut m = [1, 2, 3]; // m: [i32; 3]\n```\n\nArrays have type `[T; N]`. We’ll talk about this `T` notation [in the generics\nsection][generics]. The `N` is a compile-time constant, for the length of the\narray.\n\nThere’s a shorthand for initializing each element of an array to the same\nvalue. In this example, each element of `a` will be initialized to `0`:\n\n```rust\nlet a = [0; 20]; // a: [i32; 20]\n```\n\nYou can get the number of elements in an array `a` with `a.len()`:\n\n```rust\nlet a = [1, 2, 3];\n\nprintln!(\"a has {} elements\", a.len());\n```\n\nYou can access a particular element of an array with *subscript notation*:\n\n```rust\nlet names = [\"Graydon\", \"Brian\", \"Niko\"]; // names: [&str; 3]\n\nprintln!(\"The second name is: {}\", names[1]);\n```\n\nSubscripts start at zero, like in most programming languages, so the first name\nis `names[0]` and the second name is `names[1]`. The above example prints\n`The second name is: Brian`. If you try to use a subscript that is not in the\narray, you will get an error: array access is bounds-checked at run-time. Such\nerrant access is the source of many bugs in other systems programming\nlanguages.\n\nYou can find more documentation for `array`s [in the standard library\ndocumentation][array].\n\n[array]: ../std/primitive.array.html\n\n# Slices\n\nA ‘slice’ is a reference to (or “view” into) another data structure. They are\nuseful for allowing safe, efficient access to a portion of an array without\ncopying. For example, you might want to reference only one line of a file read\ninto memory. By nature, a slice is not created directly, but from an existing\nvariable binding. Slices have a defined length, and can be mutable or immutable.\n\nInternally, slices are represented as a pointer to the beginning of the data\nand a length.\n\n## Slicing syntax\n\nYou can use a combo of `&` and `[]` to create a slice from various things. The\n`&` indicates that slices are similar to [references], which we will cover in\ndetail later in this section. The `[]`s, with a range, let you define the\nlength of the slice:\n\n```rust\nlet a = [0, 1, 2, 3, 4];\nlet complete = &a[..]; // A slice containing all of the elements in a\nlet middle = &a[1..4]; // A slice of a: only the elements 1, 2, and 3\n```\n\nSlices have type `&[T]`. We’ll talk about that `T` when we cover\n[generics][generics].\n\n[generics]: generics.html\n\nYou can find more documentation for slices [in the standard library\ndocumentation][slice].\n\n[slice]: ../std/primitive.slice.html\n\n# `str`\n\nRust’s `str` type is the most primitive string type. As an [unsized type][dst],\nit’s not very useful by itself, but becomes useful when placed behind a\nreference, like `&str`. We'll elaborate further when we cover\n[Strings][strings] and [references].\n\n[dst]: unsized-types.html\n[strings]: strings.html\n[references]: references-and-borrowing.html\n\nYou can find more documentation for `str` [in the standard library\ndocumentation][str].\n\n[str]: ../std/primitive.str.html\n\n# Tuples\n\nA tuple is an ordered list of fixed size. Like this:\n\n```rust\nlet x = (1, \"hello\");\n```\n\nThe parentheses and commas form this two-length tuple. Here’s the same code, but\nwith the type annotated:\n\n```rust\nlet x: (i32, &str) = (1, \"hello\");\n```\n\nAs you can see, the type of a tuple looks like the tuple, but with each\nposition having a type name rather than the value. Careful readers will also\nnote that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple.\nIn systems programming languages, strings are a bit more complex than in other\nlanguages. For now, read `&str` as a *string slice*, and we’ll learn more\nsoon.\n\nYou can assign one tuple into another, if they have the same contained types\nand [arity]. Tuples have the same arity when they have the same length.\n\n[arity]: glossary.html#arity\n\n```rust\nlet mut x = (1, 2); // x: (i32, i32)\nlet y = (2, 3); // y: (i32, i32)\n\nx = y;\n```\n\nYou can access the fields in a tuple through a *destructuring let*. Here’s\nan example:\n\n```rust\nlet (x, y, z) = (1, 2, 3);\n\nprintln!(\"x is {}\", x);\n```\n\nRemember [before][let] when I said the left-hand side of a `let` statement was more\npowerful than assigning a binding? Here we are. We can put a pattern on\nthe left-hand side of the `let`, and if it matches up to the right-hand side,\nwe can assign multiple bindings at once. In this case, `let` “destructures”\nor “breaks up” the tuple, and assigns the bits to three bindings.\n\n[let]: variable-bindings.html\n\nThis pattern is very powerful, and we’ll see it repeated more later.\n\nYou can disambiguate a single-element tuple from a value in parentheses with a\ncomma:\n\n```rust\n(0,); // single-element tuple\n(0); // zero in parentheses\n```\n\n## Tuple Indexing\n\nYou can also access fields of a tuple with indexing syntax:\n\n\n```rust\nlet tuple = (1, 2, 3);\n\nlet x = tuple.0;\nlet y = tuple.1;\nlet z = tuple.2;\n\nprintln!(\"x is {}\", x);\n```\n\nLike array indexing, it starts at zero, but unlike array indexing, it uses a\n`.`, rather than `[]`s.\n\nYou can find more documentation for tuples [in the standard library\ndocumentation][tuple].\n\n[tuple]: ../std/primitive.tuple.html\n\n# Functions\n\nFunctions also have a type! They look like this:\n\n```rust\nfn foo(x: i32) -> i32 { x }\n\nlet x: fn(i32) -> i32 = foo;\n```\n\nIn this case, `x` is a ‘function pointer’ to a function that takes an `i32` and\nreturns an `i32`.\n"
  },
  {
    "path": "trpl/raw-pointers.md",
    "content": "% Raw Pointers\n\nRust has a number of different smart pointer types in its standard library, but\nthere are two types that are extra-special. Much of Rust’s safety comes from\ncompile-time checks, but raw pointers don’t have such guarantees, and are\n[unsafe][unsafe] to use.\n\n`*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when\nwriting certain kinds of libraries, you’ll need to get around Rust’s safety\nguarantees for some reason. In this case, you can use raw pointers to implement\nyour library, while exposing a safe interface for your users. For example, `*`\npointers are allowed to alias, allowing them to be used to write\nshared-ownership types, and even thread-safe shared memory types (the `Rc<T>`\nand `Arc<T>` types are both implemented entirely in Rust).\n\nHere are some things to remember about raw pointers that are different than\nother pointer types. They:\n\n- are not guaranteed to point to valid memory and are not even\n  guaranteed to be non-NULL (unlike both `Box` and `&`);\n- do not have any automatic clean-up, unlike `Box`, and so require\n  manual resource management;\n- are plain-old-data, that is, they don't move ownership, again unlike\n  `Box`, hence the Rust compiler cannot protect against bugs like\n  use-after-free;\n- lack any form of lifetimes, unlike `&`, and so the compiler cannot\n  reason about dangling pointers; and\n- have no guarantees about aliasing or mutability other than mutation\n  not being allowed directly through a `*const T`.\n\n# Basics\n\nCreating a raw pointer is perfectly safe:\n\n```rust\nlet x = 5;\nlet raw = &x as *const i32;\n\nlet mut y = 10;\nlet raw_mut = &mut y as *mut i32;\n```\n\nHowever, dereferencing one is not. This won’t work:\n\n```rust,ignore\nlet x = 5;\nlet raw = &x as *const i32;\n\nprintln!(\"raw points at {}\", *raw);\n```\n\nIt gives this error:\n\n```text\nerror: dereference of raw pointer requires unsafe function or block [E0133]\n     println!(\"raw points at {}\", *raw);\n                                  ^~~~\n```\n\nWhen you dereference a raw pointer, you’re taking responsibility that it’s not\npointing somewhere that would be incorrect. As such, you need `unsafe`:\n\n```rust\nlet x = 5;\nlet raw = &x as *const i32;\n\nlet points_at = unsafe { *raw };\n\nprintln!(\"raw points at {}\", points_at);\n```\n\nFor more operations on raw pointers, see [their API documentation][rawapi].\n\n[unsafe]: unsafe.html\n[rawapi]: ../std/primitive.pointer.html\n\n# FFI\n\nRaw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to\nC’s `const T*` and `T*`, respectively. For more about this use, consult the\n[FFI chapter][ffi].\n\n[ffi]: ffi.html\n\n# References and raw pointers\n\nAt runtime, a raw pointer `*` and a reference pointing to the same piece of\ndata have an identical representation. In fact, an `&T` reference will\nimplicitly coerce to an `*const T` raw pointer in safe code and similarly for\nthe `mut` variants (both coercions can be performed explicitly with,\nrespectively, `value as *const T` and `value as *mut T`).\n\nGoing the opposite direction, from `*const` to a reference `&`, is not safe. A\n`&T` is always valid, and so, at a minimum, the raw pointer `*const T` has to\npoint to a valid instance of type `T`. Furthermore, the resulting pointer must\nsatisfy the aliasing and mutability laws of references. The compiler assumes\nthese properties are true for any references, no matter how they are created,\nand so any conversion from raw pointers is asserting that they hold. The\nprogrammer *must* guarantee this.\n\nThe recommended method for the conversion is:\n\n```rust\n// explicit cast\nlet i: u32 = 1;\nlet p_imm: *const u32 = &i as *const u32;\n\n// implicit coercion\nlet mut m: u32 = 2;\nlet p_mut: *mut u32 = &mut m;\n\nunsafe {\n    let ref_imm: &u32 = &*p_imm;\n    let ref_mut: &mut u32 = &mut *p_mut;\n}\n```\n\nThe `&*x` dereferencing style is preferred to using a `transmute`. The latter\nis far more powerful than necessary, and the more restricted operation is\nharder to use incorrectly; for example, it requires that `x` is a pointer\n(unlike `transmute`).\n"
  },
  {
    "path": "trpl/references-and-borrowing.md",
    "content": "% References and Borrowing\n\nThis is the second of three sections presenting Rust’s ownership system. This is one of\nRust’s most distinct and compelling features, with which Rust developers should\nbecome quite acquainted. Ownership is how Rust achieves its largest goal,\nmemory safety. There are a few distinct concepts, each with its own\nchapter:\n\n* [ownership][ownership], the key concept\n* borrowing, which you’re reading now\n* [lifetimes][lifetimes], an advanced concept of borrowing\n\nThese three chapters are related, and in order. You’ll need all three to fully\nunderstand the ownership system.\n\n[ownership]: ownership.html\n[lifetimes]: lifetimes.html\n\n# Meta\n\nBefore we get to the details, two important notes about the ownership system.\n\nRust has a focus on safety and speed. It accomplishes these goals through many\n‘zero-cost abstractions’, which means that in Rust, abstractions cost as little\nas possible in order to make them work. The ownership system is a prime example\nof a zero-cost abstraction. All of the analysis we’ll talk about in this guide\nis _done at compile time_. You do not pay any run-time cost for any of these\nfeatures.\n\nHowever, this system does have a certain cost: learning curve. Many new users\nto Rust experience something we like to call ‘fighting with the borrow\nchecker’, where the Rust compiler refuses to compile a program that the author\nthinks is valid. This often happens because the programmer’s mental model of\nhow ownership should work doesn’t match the actual rules that Rust implements.\nYou probably will experience similar things at first. There is good news,\nhowever: more experienced Rust developers report that once they work with the\nrules of the ownership system for a period of time, they fight the borrow\nchecker less and less.\n\nWith that in mind, let’s learn about borrowing.\n\n# Borrowing\n\nAt the end of the [ownership][ownership] section, we had a nasty function that looked\nlike this:\n\n```rust\nfn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {\n    // do stuff with v1 and v2\n\n    // hand back ownership, and the result of our function\n    (v1, v2, 42)\n}\n\nlet v1 = vec![1, 2, 3];\nlet v2 = vec![1, 2, 3];\n\nlet (v1, v2, answer) = foo(v1, v2);\n```\n\nThis is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s\nthe first step:\n\n```rust\nfn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {\n    // do stuff with v1 and v2\n\n    // return the answer\n    42\n}\n\nlet v1 = vec![1, 2, 3];\nlet v2 = vec![1, 2, 3];\n\nlet answer = foo(&v1, &v2);\n\n// we can use v1 and v2 here!\n```\n\nA more concrete example:\n\n```rust\nfn main() {\n    // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.\n    fn sum_vec(v: &Vec<i32>) -> i32 {\n        return v.iter().fold(0, |a, &b| a + b);\n    }\n    // Borrow two vectors and sum them.\n    // This kind of borrowing does not allow mutation to the borrowed.\n    fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {\n        // do stuff with v1 and v2\n        let s1 = sum_vec(v1);\n        let s2 = sum_vec(v2);\n        // return the answer\n        s1 + s2\n    }\n\n    let v1 = vec![1, 2, 3];\n    let v2 = vec![4, 5, 6];\n\n    let answer = foo(&v1, &v2);\n    println!(\"{}\", answer);\n}\n```\n\nInstead of taking `Vec<i32>`s as our arguments, we take a reference:\n`&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and\n`&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource,\nit borrows ownership. A binding that borrows something does not deallocate the\nresource when it goes out of scope. This means that after the call to `foo()`,\nwe can use our original bindings again.\n\nReferences are immutable, like bindings. This means that inside of `foo()`,\nthe vectors can’t be changed at all:\n\n```rust,ignore\nfn foo(v: &Vec<i32>) {\n     v.push(5);\n}\n\nlet v = vec![];\n\nfoo(&v);\n```\n\nwill give us this error:\n\n```text\nerror: cannot borrow immutable borrowed content `*v` as mutable\nv.push(5);\n^\n```\n\nPushing a value mutates the vector, and so we aren’t allowed to do it.\n\n# &mut references\n\nThere’s a second kind of reference: `&mut T`. A ‘mutable reference’ allows you\nto mutate the resource you’re borrowing. For example:\n\n```rust\nlet mut x = 5;\n{\n    let y = &mut x;\n    *y += 1;\n}\nprintln!(\"{}\", x);\n```\n\nThis will print `6`. We make `y` a mutable reference to `x`, then add one to\nthe thing `y` points at. You’ll notice that `x` had to be marked `mut` as well.\nIf it wasn’t, we couldn’t take a mutable borrow to an immutable value.\n\nYou'll also notice we added an asterisk (`*`) in front of `y`, making it `*y`,\nthis is because `y` is a `&mut` reference. You'll need to use astrisks to\naccess the contents of a reference as well.\n\nOtherwise, `&mut` references are like references. There _is_ a large\ndifference between the two, and how they interact, though. You can tell\nsomething is fishy in the above example, because we need that extra scope, with\nthe `{` and `}`. If we remove them, we get an error:\n\n```text\nerror: cannot borrow `x` as immutable because it is also borrowed as mutable\n    println!(\"{}\", x);\n                   ^\nnote: previous borrow of `x` occurs here; the mutable borrow prevents\nsubsequent moves, borrows, or modification of `x` until the borrow ends\n        let y = &mut x;\n                     ^\nnote: previous borrow ends here\nfn main() {\n\n}\n^\n```\n\nAs it turns out, there are rules.\n\n# The Rules\n\nHere are the rules for borrowing in Rust:\n\nFirst, any borrow must last for a scope no greater than that of the owner.\nSecond, you may have one or the other of these two kinds of borrows, but not\nboth at the same time:\n\n* one or more references (`&T`) to a resource,\n* exactly one mutable reference (`&mut T`).\n\n\nYou may notice that this is very similar to, though not exactly the same as,\nthe definition of a data race:\n\n> There is a ‘data race’ when two or more pointers access the same memory\n> location at the same time, where at least one of them is writing, and the\n> operations are not synchronized.\n\nWith references, you may have as many as you’d like, since none of them are\nwriting. However, as we can only have one `&mut` at a time, it is impossible to\nhave a data race. This is how Rust prevents data races at compile time: we’ll\nget errors if we break the rules.\n\nWith this in mind, let’s consider our example again.\n\n## Thinking in scopes\n\nHere’s the code:\n\n```rust,ignore\nfn main() {\n    let mut x = 5;\n    let y = &mut x;\n\n    *y += 1;\n\n    println!(\"{}\", x);\n}\n```\n\nThis code gives us this error:\n\n```text\nerror: cannot borrow `x` as immutable because it is also borrowed as mutable\n    println!(\"{}\", x);\n                   ^\n```\n\nThis is because we’ve violated the rules: we have a `&mut T` pointing to `x`,\nand so we aren’t allowed to create any `&T`s. It's one or the other. The note\nhints at how to think about this problem:\n\n```text\nnote: previous borrow ends here\nfn main() {\n\n}\n^\n```\n\nIn other words, the mutable borrow is held through the rest of our example. What\nwe want is for the mutable borrow by `y` to end so that the resource can be\nreturned to the owner, `x`. `x` can then provide a immutable borrow to `println!`.\nIn Rust, borrowing is tied to the scope that the borrow is valid for. And our\nscopes look like this:\n\n```rust,ignore\nfn main() {\n    let mut x = 5;\n\n    let y = &mut x;    // -+ &mut borrow of x starts here\n                       //  |\n    *y += 1;           //  |\n                       //  |\n    println!(\"{}\", x); // -+ - try to borrow x here\n}                      // -+ &mut borrow of x ends here\n                       \n```\n\nThe scopes conflict: we can’t make an `&x` while `y` is in scope.\n\nSo when we add the curly braces:\n\n```rust\nlet mut x = 5;\n\n{\n    let y = &mut x; // -+ &mut borrow starts here\n    *y += 1;        //  |\n}                   // -+ ... and ends here\n\nprintln!(\"{}\", x);  // <- try to borrow x here\n```\n\nThere’s no problem. Our mutable borrow goes out of scope before we create an\nimmutable one. So scope is the key to seeing how long a borrow lasts for.\n\n## Issues borrowing prevents\n\nWhy have these restrictive rules? Well, as we noted, these rules prevent data\nraces. What kinds of issues do data races cause? Here are a few.\n\n### Iterator invalidation\n\nOne example is ‘iterator invalidation’, which happens when you try to mutate a\ncollection that you’re iterating over. Rust’s borrow checker prevents this from\nhappening:\n\n```rust\nlet mut v = vec![1, 2, 3];\n\nfor i in &v {\n    println!(\"{}\", i);\n}\n```\n\nThis prints out one through three. As we iterate through the vector, we’re\nonly given references to the elements. And `v` is itself borrowed as immutable,\nwhich means we can’t change it while we’re iterating:\n\n```rust,ignore\nlet mut v = vec![1, 2, 3];\n\nfor i in &v {\n    println!(\"{}\", i);\n    v.push(34);\n}\n```\n\nHere’s the error:\n\n```text\nerror: cannot borrow `v` as mutable because it is also borrowed as immutable\n    v.push(34);\n    ^\nnote: previous borrow of `v` occurs here; the immutable borrow prevents\nsubsequent moves or mutable borrows of `v` until the borrow ends\nfor i in &v {\n          ^\nnote: previous borrow ends here\nfor i in &v {\n    println!(“{}”, i);\n    v.push(34);\n}\n^\n```\n\nWe can’t modify `v` because it’s borrowed by the loop.\n\n### Use after free\n\nReferences must not live longer than the resource they refer to. Rust will\ncheck the scopes of your references to ensure that this is true.\n\nIf Rust didn’t check this property, we could accidentally use a reference\nwhich was invalid. For example:\n\n```rust,ignore\nlet y: &i32;\n{\n    let x = 5;\n    y = &x;\n}\n\nprintln!(\"{}\", y);\n```\n\nWe get this error:\n\n```text\nerror: `x` does not live long enough\n    y = &x;\n         ^\nnote: reference must be valid for the block suffix following statement 0 at\n2:16...\nlet y: &i32;\n{\n    let x = 5;\n    y = &x;\n}\n\nnote: ...but borrowed value is only valid for the block suffix following\nstatement 0 at 4:18\n    let x = 5;\n    y = &x;\n}\n```\n\nIn other words, `y` is only valid for the scope where `x` exists. As soon as\n`x` goes away, it becomes invalid to refer to it. As such, the error says that\nthe borrow ‘doesn’t live long enough’ because it’s not valid for the right\namount of time.\n\nThe same problem occurs when the reference is declared _before_ the variable it\nrefers to. This is because resources within the same scope are freed in the\nopposite order they were declared:\n\n```rust,ignore\nlet y: &i32;\nlet x = 5;\ny = &x;\n\nprintln!(\"{}\", y);\n```\n\nWe get this error:\n\n```text\nerror: `x` does not live long enough\ny = &x;\n     ^\nnote: reference must be valid for the block suffix following statement 0 at\n2:16...\n    let y: &i32;\n    let x = 5;\n    y = &x;\n\n    println!(\"{}\", y);\n}\n\nnote: ...but borrowed value is only valid for the block suffix following\nstatement 1 at 3:14\n    let x = 5;\n    y = &x;\n\n    println!(\"{}\", y);\n}\n```\n\nIn the above example, `y` is declared before `x`, meaning that `y` lives longer\nthan `x`, which is not allowed.\n"
  },
  {
    "path": "trpl/release-channels.md",
    "content": "% Release Channels\n\nThe Rust project uses a concept called ‘release channels’ to manage releases.\nIt’s important to understand this process to choose which version of Rust\nyour project should use.\n\n# Overview\n\nThere are three channels for Rust releases:\n\n* Nightly\n* Beta\n* Stable\n\nNew nightly releases are created once a day. Every six weeks, the latest\nnightly release is promoted to ‘Beta’. At that point, it will only receive\npatches to fix serious errors. Six weeks later, the beta is promoted to\n‘Stable’, and becomes the next release of `1.x`.\n\nThis process happens in parallel. So every six weeks, on the same day,\nnightly goes to beta, beta goes to stable. When `1.x` is released, at\nthe same time, `1.(x + 1)-beta` is released, and the nightly becomes the\nfirst version of `1.(x + 2)-nightly`.\n\n# Choosing a version\n\nGenerally speaking, unless you have a specific reason, you should be using the\nstable release channel. These releases are intended for a general audience.\n\nHowever, depending on your interest in Rust, you may choose to use nightly\ninstead. The basic tradeoff is this: in the nightly channel, you can use\nunstable, new Rust features. However, unstable features are subject to change,\nand so any new nightly release may break your code. If you use the stable\nrelease, you cannot use experimental features, but the next release of Rust\nwill not cause significant issues through breaking changes.\n\n# Helping the ecosystem through CI\n\nWhat about beta? We encourage all Rust users who use the stable release channel\nto also test against the beta channel in their continuous integration systems.\nThis will help alert the team in case there’s an accidental regression.\n\nAdditionally, testing against nightly can catch regressions even sooner, and so\nif you don’t mind a third build, we’d appreciate testing against all channels.\n\nAs an example, many Rust programmers use [Travis](https://travis-ci.org/) to\ntest their crates, which is free for open source projects. Travis [supports\nRust directly][travis], and you can use a `.travis.yml` file like this to\ntest on all channels:\n\n```yaml\nlanguage: rust\nrust:\n  - nightly\n  - beta\n  - stable\n\nmatrix:\n  allow_failures:\n    - rust: nightly\n```\n\n[travis]: http://docs.travis-ci.com/user/languages/rust/\n\nWith this configuration, Travis will test all three channels, but if something\nbreaks on nightly, it won’t fail your build. A similar configuration is\nrecommended for any CI system, check the documentation of the one you’re\nusing for more details.\n"
  },
  {
    "path": "trpl/slice-patterns.md",
    "content": "% Slice patterns\n\nIf you want to match against a slice or array, you can use `&` with the\n`slice_patterns` feature:\n\n```rust\n#![feature(slice_patterns)]\n\nfn main() {\n    let v = vec![\"match_this\", \"1\"];\n\n    match &v[..] {\n        &[\"match_this\", second] => println!(\"The second element is {}\", second),\n        _ => {},\n    }\n}\n```\n\nThe `advanced_slice_patterns` gate lets you use `..` to indicate any number of\nelements inside a pattern matching a slice. This wildcard can only be used once\nfor a given array. If there's an identifier before the `..`, the result of the\nslice will be bound to that name. For example:\n\n```rust\n#![feature(advanced_slice_patterns, slice_patterns)]\n\nfn is_symmetric(list: &[u32]) -> bool {\n    match list {\n        &[] | &[_] => true,\n        &[x, ref inside.., y] if x == y => is_symmetric(inside),\n        _ => false\n    }\n}\n\nfn main() {\n    let sym = &[0, 1, 4, 2, 4, 1, 0];\n    assert!(is_symmetric(sym));\n\n    let not_sym = &[0, 1, 7, 2, 4, 1, 0];\n    assert!(!is_symmetric(not_sym));\n}\n```\n"
  },
  {
    "path": "trpl/strings.md",
    "content": "% Strings\n\nStrings are an important concept for any programmer to master. Rust’s string\nhandling system is a bit different from other languages, due to its systems\nfocus. Any time you have a data structure of variable size, things can get\ntricky, and strings are a re-sizable data structure. That being said, Rust’s\nstrings also work differently than in some other systems languages, such as C.\n\nLet’s dig into the details. A ‘string’ is a sequence of Unicode scalar values\nencoded as a stream of UTF-8 bytes. All strings are guaranteed to be a valid\nencoding of UTF-8 sequences. Additionally, unlike some systems languages,\nstrings are not NUL-terminated and can contain NUL bytes.\n\nRust has two main types of strings: `&str` and `String`. Let’s talk about\n`&str` first. These are called ‘string slices’. A string slice has a fixed\nsize, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.\n\n```rust\nlet greeting = \"Hello there.\"; // greeting: &'static str\n```\n\n`\"Hello there.\"` is a string literal and its type is `&'static str`. A string\nliteral is a string slice that is statically allocated, meaning that it’s saved\ninside our compiled program, and exists for the entire duration it runs. The\n`greeting` binding is a reference to this statically allocated string. Any\nfunction expecting a string slice will also accept a string literal.\n\nString literals can span multiple lines. There are two forms. The first will\ninclude the newline and the leading spaces:\n\n```rust\nlet s = \"foo\n    bar\";\n\nassert_eq!(\"foo\\n    bar\", s);\n```\n\nThe second, with a `\\`, trims the spaces and the newline:\n\n```rust\nlet s = \"foo\\\n    bar\";\n\nassert_eq!(\"foobar\", s);\n```\n\nNote that you normally cannot access a `str` directly, but only through a `&str`\nreference. This is because `str` is an unsized type which requires additional\nruntime information to be usable. For more information see the chapter on\n[unsized types][ut].\n\nRust has more than only `&str`s though. A `String` is a heap-allocated string.\nThis string is growable, and is also guaranteed to be UTF-8. `String`s are\ncommonly created by converting from a string slice using the `to_string`\nmethod.\n\n```rust\nlet mut s = \"Hello\".to_string(); // mut s: String\nprintln!(\"{}\", s);\n\ns.push_str(\", world.\");\nprintln!(\"{}\", s);\n```\n\n`String`s will coerce into `&str` with an `&`:\n\n```rust\nfn takes_slice(slice: &str) {\n    println!(\"Got: {}\", slice);\n}\n\nfn main() {\n    let s = \"Hello\".to_string();\n    takes_slice(&s);\n}\n```\n\nThis coercion does not happen for functions that accept one of `&str`’s traits\ninstead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter\nof type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly\nconverted using `&*`.\n\n```rust,no_run\nuse std::net::TcpStream;\n\nTcpStream::connect(\"192.168.0.1:3000\"); // &str parameter\n\nlet addr_string = \"192.168.0.1:3000\".to_string();\nTcpStream::connect(&*addr_string); // convert addr_string to &str\n```\n\nViewing a `String` as a `&str` is cheap, but converting the `&str` to a\n`String` involves allocating memory. No reason to do that unless you have to!\n\n## Indexing\n\nBecause strings are valid UTF-8, they do not support indexing:\n\n```rust,ignore\nlet s = \"hello\";\n\nprintln!(\"The first letter of s is {}\", s[0]); // ERROR!!!\n```\n\nUsually, access to a vector with `[]` is very fast. But, because each character\nin a UTF-8 encoded string can be multiple bytes, you have to walk over the\nstring to find the nᵗʰ letter of a string. This is a significantly more\nexpensive operation, and we don’t want to be misleading. Furthermore, ‘letter’\nisn’t something defined in Unicode, exactly. We can choose to look at a string as\nindividual bytes, or as codepoints:\n\n```rust\nlet hachiko = \"忠犬ハチ公\";\n\nfor b in hachiko.as_bytes() {\n    print!(\"{}, \", b);\n}\n\nprintln!(\"\");\n\nfor c in hachiko.chars() {\n    print!(\"{}, \", c);\n}\n\nprintln!(\"\");\n```\n\nThis prints:\n\n```text\n229, 191, 160, 231, 138, 172, 227, 131, 143, 227, 131, 129, 229, 133, 172,\n忠, 犬, ハ, チ, 公,\n```\n\nAs you can see, there are more bytes than `char`s.\n\nYou can get something similar to an index like this:\n\n```rust\n# let hachiko = \"忠犬ハチ公\";\nlet dog = hachiko.chars().nth(1); // kinda like hachiko[1]\n```\n\nThis emphasizes that we have to walk from the beginning of the list of `chars`.\n\n## Slicing\n\nYou can get a slice of a string with slicing syntax:\n\n```rust\nlet dog = \"hachiko\";\nlet hachi = &dog[0..5];\n```\n\nBut note that these are _byte_ offsets, not _character_ offsets. So\nthis will fail at runtime:\n\n```rust,should_panic\nlet dog = \"忠犬ハチ公\";\nlet hachi = &dog[0..2];\n```\n\nwith this error:\n\n```text\nthread 'main' panicked at 'index 0 and/or 2 in `忠犬ハチ公` do not lie on\ncharacter boundary'\n```\n\n## Concatenation\n\nIf you have a `String`, you can concatenate a `&str` to the end of it:\n\n```rust\nlet hello = \"Hello \".to_string();\nlet world = \"world!\";\n\nlet hello_world = hello + world;\n```\n\nBut if you have two `String`s, you need an `&`:\n\n```rust\nlet hello = \"Hello \".to_string();\nlet world = \"world!\".to_string();\n\nlet hello_world = hello + &world;\n```\n\nThis is because `&String` can automatically coerce to a `&str`. This is a\nfeature called ‘[`Deref` coercions][dc]’.\n\n[ut]: unsized-types.html\n[dc]: deref-coercions.html\n[connect]: ../std/net/struct.TcpStream.html#method.connect\n"
  },
  {
    "path": "trpl/structs.md",
    "content": "% Structs\n\n`struct`s are a way of creating more complex data types. For example, if we were\ndoing calculations involving coordinates in 2D space, we would need both an `x`\nand a `y` value:\n\n```rust\nlet origin_x = 0;\nlet origin_y = 0;\n```\n\nA `struct` lets us combine these two into a single, unified datatype with `x`\nand `y` as field labels:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nfn main() {\n    let origin = Point { x: 0, y: 0 }; // origin: Point\n\n    println!(\"The origin is at ({}, {})\", origin.x, origin.y);\n}\n```\n\nThere’s a lot going on here, so let’s break it down. We declare a `struct` with\nthe `struct` keyword, and then with a name. By convention, `struct`s begin with\na capital letter and are camel cased: `PointInSpace`, not `Point_In_Space`.\n\nWe can create an instance of our `struct` via `let`, as usual, but we use a `key:\nvalue` style syntax to set each field. The order doesn’t need to be the same as\nin the original declaration.\n\nFinally, because fields have names, we can access them through dot\nnotation: `origin.x`.\n\nThe values in `struct`s are immutable by default, like other bindings in Rust.\nUse `mut` to make them mutable:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nfn main() {\n    let mut point = Point { x: 0, y: 0 };\n\n    point.x = 5;\n\n    println!(\"The point is at ({}, {})\", point.x, point.y);\n}\n```\n\nThis will print `The point is at (5, 0)`.\n\nRust does not support field mutability at the language level, so you cannot\nwrite something like this:\n\n```rust,ignore\nstruct Point {\n    mut x: i32,\n    y: i32,\n}\n```\n\nMutability is a property of the binding, not of the structure itself. If you’re\nused to field-level mutability, this may seem strange at first, but it\nsignificantly simplifies things. It even lets you make things mutable on a temporary\nbasis:\n\n```rust,ignore\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nfn main() {\n    let mut point = Point { x: 0, y: 0 };\n\n    point.x = 5;\n\n    let point = point; // now immutable\n\n    point.y = 6; // this causes an error\n}\n```\n\nYour structure can still contain `&mut` pointers, which will let\nyou do some kinds of mutation:\n\n```rust\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nstruct PointRef<'a> {\n    x: &'a mut i32,\n    y: &'a mut i32,\n}\n\nfn main() {\n    let mut point = Point { x: 0, y: 0 };\n\n    {\n        let r = PointRef { x: &mut point.x, y: &mut point.y };\n\n        *r.x = 5;\n        *r.y = 6;\n    }\n\n    assert_eq!(5, point.x);\n    assert_eq!(6, point.y);\n}\n```\n\n# Update syntax\n\nA `struct` can include `..` to indicate that you want to use a copy of some\nother `struct` for some of the values. For example:\n\n```rust\nstruct Point3d {\n    x: i32,\n    y: i32,\n    z: i32,\n}\n\nlet mut point = Point3d { x: 0, y: 0, z: 0 };\npoint = Point3d { y: 1, .. point };\n```\n\nThis gives `point` a new `y`, but keeps the old `x` and `z` values. It doesn’t\nhave to be the same `struct` either, you can use this syntax when making new\nones, and it will copy the values you don’t specify:\n\n```rust\n# struct Point3d {\n#     x: i32,\n#     y: i32,\n#     z: i32,\n# }\nlet origin = Point3d { x: 0, y: 0, z: 0 };\nlet point = Point3d { z: 1, x: 2, .. origin };\n```\n\n# Tuple structs\n\nRust has another data type that’s like a hybrid between a [tuple][tuple] and a\n`struct`, called a ‘tuple struct’. Tuple structs have a name, but their fields\ndon't. They are declared with the `struct` keyword, and then with a name\nfollowed by a tuple:\n\n[tuple]: primitive-types.html#tuples\n\n```rust\nstruct Color(i32, i32, i32);\nstruct Point(i32, i32, i32);\n\nlet black = Color(0, 0, 0);\nlet origin = Point(0, 0, 0);\n```\n\nHere, `black` and `origin` are not the same type, even though they contain the\nsame values.\n\nThe members of a tuple struct may be accessed by dot notation or destructuring\n`let`, just like regular tuples:\n\n```rust\n# struct Color(i32, i32, i32);\n# struct Point(i32, i32, i32);\n# let black = Color(0, 0, 0);\n# let origin = Point(0, 0, 0);\nlet black_r = black.0;\nlet Point(_, origin_y, origin_z) = origin;\n```\n\nPatterns like `Point(_, origin_y, origin_z)` are also used in\n[match expressions][match].\n\nOne case when a tuple struct is very useful is when it has only one element.\nWe call this the ‘newtype’ pattern, because it allows you to create a new type\nthat is distinct from its contained value and also expresses its own semantic\nmeaning:\n\n```rust\nstruct Inches(i32);\n\nlet length = Inches(10);\n\nlet Inches(integer_length) = length;\nprintln!(\"length is {} inches\", integer_length);\n```\n\nAs above, you can extract the inner integer type through a destructuring `let`.\nIn this case, the `let Inches(integer_length)` assigns `10` to `integer_length`.\nWe could have used dot notation to do the same thing:\n\n```rust\n# struct Inches(i32);\n# let length = Inches(10);\nlet integer_length = length.0;\n```\n\nIt's always possible to use a `struct` instead of a tuple struct, and can be\nclearer. We could write `Color` and `Point` like this instead:\n\n```rust\nstruct Color {\n    red: i32,\n    blue: i32,\n    green: i32,\n}\n\nstruct Point {\n    x: i32,\n    y: i32,\n    z: i32,\n}\n```\n\nGood names are important, and while values in a tuple struct can be\nreferenced with dot notation as well, a `struct` gives us actual names,\nrather than positions.\n\n[match]: match.html\n\n# Unit-like structs\n\nYou can define a `struct` with no members at all:\n\n```rust\nstruct Electron {} // use empty braces...\nstruct Proton;     // ...or just a semicolon\n\n// whether you declared the struct with braces or not, do the same when creating one\nlet x = Electron {};\nlet y = Proton;\n```\n\nSuch a `struct` is called ‘unit-like’ because it resembles the empty\ntuple, `()`, sometimes called ‘unit’. Like a tuple struct, it defines a\nnew type.\n\nThis is rarely useful on its own (although sometimes it can serve as a\nmarker type), but in combination with other features, it can become\nuseful. For instance, a library may ask you to create a structure that\nimplements a certain [trait][trait] to handle events. If you don’t have\nany data you need to store in the structure, you can create a\nunit-like `struct`.\n\n[trait]: traits.html\n"
  },
  {
    "path": "trpl/syntax-and-semantics.md",
    "content": "% Syntax and Semantics\n\nThis chapter breaks Rust down into small chunks, one for each concept.\n\nIf you’d like to learn Rust from the bottom up, reading this in order is a\ngreat way to do that.\n\nThese sections also form a reference for each concept, so if you’re reading\nanother tutorial and find something confusing, you can find it explained\nsomewhere in here.\n"
  },
  {
    "path": "trpl/syntax-index.md",
    "content": "% Syntax Index\n\n## Keywords\n\n* `as`: primitive casting, or disambiguating the specific trait containing an item.  See [Casting Between Types (`as`)], [Universal Function Call Syntax (Angle-bracket Form)], [Associated Types].\n* `break`: break out of loop.  See [Loops (Ending Iteration Early)].\n* `const`: constant items and constant raw pointers.  See [`const` and `static`], [Raw Pointers].\n* `continue`: continue to next loop iteration.  See [Loops (Ending Iteration Early)].\n* `crate`: external crate linkage.  See [Crates and Modules (Importing External Crates)].\n* `else`: fallback for `if` and `if let` constructs.  See [`if`], [`if let`].\n* `enum`: defining enumeration.  See [Enums].\n* `extern`: external crate, function, and variable linkage.  See [Crates and Modules (Importing External Crates)], [Foreign Function Interface].\n* `false`: boolean false literal.  See [Primitive Types (Booleans)].\n* `fn`: function definition and function pointer types.  See [Functions].\n* `for`: iterator loop, part of trait `impl` syntax, and higher-ranked lifetime syntax.  See [Loops (`for`)], [Method Syntax].\n* `if`: conditional branching.  See [`if`], [`if let`].\n* `impl`: inherent and trait implementation blocks.  See [Method Syntax].\n* `in`: part of `for` loop syntax.  See [Loops (`for`)].\n* `let`: variable binding.  See [Variable Bindings].\n* `loop`: unconditional, infinite loop.  See [Loops (`loop`)].\n* `match`: pattern matching.  See [Match].\n* `mod`: module declaration.  See [Crates and Modules (Defining Modules)].\n* `move`: part of closure syntax.  See [Closures (`move` closures)].\n* `mut`: denotes mutability in pointer types and pattern bindings.  See [Mutability].\n* `pub`: denotes public visibility in `struct` fields, `impl` blocks, and modules.  See [Crates and Modules (Exporting a Public Interface)].\n* `ref`: by-reference binding.  See [Patterns (`ref` and `ref mut`)].\n* `return`: return from function.  See [Functions (Early Returns)].\n* `Self`: implementor type alias.  See [Traits].\n* `self`: method subject.  See [Method Syntax (Method Calls)].\n* `static`: global variable.  See [`const` and `static` (`static`)].\n* `struct`: structure definition.  See [Structs].\n* `trait`: trait definition.  See [Traits].\n* `true`: boolean true literal.  See [Primitive Types (Booleans)].\n* `type`: type alias, and associated type definition.  See [`type` Aliases], [Associated Types].\n* `unsafe`: denotes unsafe code, functions, traits, and implementations.  See [Unsafe].\n* `use`: import symbols into scope.  See [Crates and Modules (Importing Modules with `use`)].\n* `where`: type constraint clauses.  See [Traits (`where` clause)].\n* `while`: conditional loop.  See [Loops (`while`)].\n\n## Operators and Symbols\n\n* `!` (`ident!(…)`, `ident!{…}`, `ident![…]`): denotes macro expansion.  See [Macros].\n* `!` (`!expr`): bitwise or logical complement.  Overloadable (`Not`).\n* `!=` (`var != expr`): nonequality comparison.  Overloadable (`PartialEq`).\n* `%` (`expr % expr`): arithmetic remainder.  Overloadable (`Rem`).\n* `%=` (`var %= expr`): arithmetic remainder & assignment. Overloadable (`RemAssign`).\n* `&` (`expr & expr`): bitwise and.  Overloadable (`BitAnd`).\n* `&` (`&expr`): borrow.  See [References and Borrowing].\n* `&` (`&type`, `&mut type`, `&'a type`, `&'a mut type`): borrowed pointer type.  See [References and Borrowing].\n* `&=` (`var &= expr`): bitwise and & assignment. Overloadable (`BitAndAssign`).\n* `&&` (`expr && expr`): logical and.\n* `*` (`expr * expr`): arithmetic multiplication.  Overloadable (`Mul`).\n* `*` (`*expr`): dereference.\n* `*` (`*const type`, `*mut type`): raw pointer.  See [Raw Pointers].\n* `*=` (`var *= expr`): arithmetic multiplication & assignment. Overloadable (`MulAssign`).\n* `+` (`expr + expr`): arithmetic addition.  Overloadable (`Add`).\n* `+` (`trait + trait`, `'a + trait`): compound type constraint.  See [Traits (Multiple Trait Bounds)].\n* `+=` (`var += expr`): arithmetic addition & assignment. Overloadable (`AddAssign`).\n* `,`: argument and element separator.  See [Attributes], [Functions], [Structs], [Generics], [Match], [Closures], [Crates and Modules (Importing Modules with `use`)].\n* `-` (`expr - expr`): arithmetic subtraction.  Overloadable (`Sub`).\n* `-` (`- expr`): arithmetic negation.  Overloadable (`Neg`).\n* `-=` (`var -= expr`): arithmetic subtraction & assignment. Overloadable (`SubAssign`).\n* `->` (`fn(…) -> type`, `|…| -> type`): function and closure return type.  See [Functions], [Closures].\n* `-> !` (`fn(…) -> !`, `|…| -> !`): diverging function or closure. See [Diverging Functions].\n* `.` (`expr.ident`): member access.  See [Structs], [Method Syntax].\n* `..` (`..`, `expr..`, `..expr`, `expr..expr`): right-exclusive range literal.\n* `..` (`..expr`): struct literal update syntax.  See [Structs (Update syntax)].\n* `..` (`variant(x, ..)`, `struct_type { x, .. }`): \"and the rest\" pattern binding.  See [Patterns (Ignoring bindings)].\n* `...` (`...expr`, `expr...expr`) *in an expression*: inclusive range expression. See [Iterators].\n* `...` (`expr...expr`) *in a pattern*: inclusive range pattern.  See [Patterns (Ranges)].\n* `/` (`expr / expr`): arithmetic division.  Overloadable (`Div`).\n* `/=` (`var /= expr`): arithmetic division & assignment. Overloadable (`DivAssign`).\n* `:` (`pat: type`, `ident: type`): constraints.  See [Variable Bindings], [Functions], [Structs], [Traits].\n* `:` (`ident: expr`): struct field initializer.  See [Structs].\n* `:` (`'a: loop {…}`): loop label.  See [Loops (Loops Labels)].\n* `;`: statement and item terminator.\n* `;` (`[…; len]`): part of fixed-size array syntax.  See [Primitive Types (Arrays)].\n* `<<` (`expr << expr`): left-shift.  Overloadable (`Shl`).\n* `<<=` (`var <<= expr`): left-shift & assignment. Overloadable (`ShlAssign`).\n* `<` (`expr < expr`): less-than comparison.  Overloadable (`PartialOrd`).\n* `<=` (`var <= expr`): less-than or equal-to comparison.  Overloadable (`PartialOrd`).\n* `=` (`var = expr`, `ident = type`): assignment/equivalence.  See [Variable Bindings], [`type` Aliases], generic parameter defaults.\n* `==` (`var == expr`): equality comparison.  Overloadable (`PartialEq`).\n* `=>` (`pat => expr`): part of match arm syntax.  See [Match].\n* `>` (`expr > expr`): greater-than comparison.  Overloadable (`PartialOrd`).\n* `>=` (`var >= expr`): greater-than or equal-to comparison.  Overloadable (`PartialOrd`).\n* `>>` (`expr >> expr`): right-shift.  Overloadable (`Shr`).\n* `>>=` (`var >>= expr`): right-shift & assignment. Overloadable (`ShrAssign`).\n* `@` (`ident @ pat`): pattern binding.  See [Patterns (Bindings)].\n* `^` (`expr ^ expr`): bitwise exclusive or.  Overloadable (`BitXor`).\n* `^=` (`var ^= expr`): bitwise exclusive or & assignment. Overloadable (`BitXorAssign`).\n* `|` (`expr | expr`): bitwise or.  Overloadable (`BitOr`).\n* `|` (`pat | pat`): pattern alternatives.  See [Patterns (Multiple patterns)].\n* `|` (`|…| expr`): closures.  See [Closures].\n* `|=` (`var |= expr`): bitwise or & assignment. Overloadable (`BitOrAssign`).\n* `||` (`expr || expr`): logical or.\n* `_`: \"ignored\" pattern binding (see [Patterns (Ignoring bindings)]). Also used to make integer-literals readable (see [Reference (Integer literals)]).\n\n## Other Syntax\n\n<!-- Various bits of standalone stuff. -->\n\n* `'ident`: named lifetime or loop label.  See [Lifetimes], [Loops (Loops Labels)].\n* `…u8`, `…i32`, `…f64`, `…usize`, …: numeric literal of specific type.\n* `\"…\"`: string literal.  See [Strings].\n* `r\"…\"`, `r#\"…\"#`, `r##\"…\"##`, …: raw string literal, escape characters are not processed. See [Reference (Raw String Literals)].\n* `b\"…\"`: byte string literal, constructs a `[u8]` instead of a string. See [Reference (Byte String Literals)].\n* `br\"…\"`, `br#\"…\"#`, `br##\"…\"##`, …: raw byte string literal, combination of raw and byte string literal. See [Reference (Raw Byte String Literals)].\n* `'…'`: character literal.  See [Primitive Types (`char`)].\n* `b'…'`: ASCII byte literal.\n* `|…| expr`: closure.  See [Closures].\n\n<!-- Path-related syntax -->\n\n* `ident::ident`: path.  See [Crates and Modules (Defining Modules)].\n* `::path`: path relative to the crate root (*i.e.* an explicitly absolute path).  See [Crates and Modules (Re-exporting with `pub use`)].\n* `self::path`: path relative to the current module (*i.e.* an explicitly relative path).  See [Crates and Modules (Re-exporting with `pub use`)].\n* `super::path`: path relative to the parent of the current module.  See [Crates and Modules (Re-exporting with `pub use`)].\n* `type::ident`, `<type as trait>::ident`: associated constants, functions, and types.  See [Associated Types].\n* `<type>::…`: associated item for a type which cannot be directly named (*e.g.* `<&T>::…`, `<[T]>::…`, *etc.*).  See [Associated Types].\n* `trait::method(…)`: disambiguating a method call by naming the trait which defines it. See [Universal Function Call Syntax].\n* `type::method(…)`: disambiguating a method call by naming the type for which it's defined. See [Universal Function Call Syntax].\n* `<type as trait>::method(…)`: disambiguating a method call by naming the trait _and_ type. See [Universal Function Call Syntax (Angle-bracket Form)].\n\n<!-- Generics -->\n\n* `path<…>` (*e.g.* `Vec<u8>`): specifies parameters to generic type *in a type*.  See [Generics].\n* `path::<…>`, `method::<…>` (*e.g.* `\"42\".parse::<i32>()`): specifies parameters to generic type, function, or method *in an expression*.\n* `fn ident<…> …`: define generic function.  See [Generics].\n* `struct ident<…> …`: define generic structure.  See [Generics].\n* `enum ident<…> …`: define generic enumeration.  See [Generics].\n* `impl<…> …`: define generic implementation.\n* `for<…> type`: higher-ranked lifetime bounds.\n* `type<ident=type>` (*e.g.* `Iterator<Item=T>`): a generic type where one or more associated types have specific assignments.  See [Associated Types].\n\n<!-- Constraints -->\n\n* `T: U`: generic parameter `T` constrained to types that implement `U`.  See [Traits].\n* `T: 'a`: generic type `T` must outlive lifetime `'a`. When we say that a type 'outlives' the lifetime, we mean that it cannot transitively contain any references with lifetimes shorter than `'a`.\n* `T : 'static`: The generic type `T` contains no borrowed references other than `'static` ones.\n* `'b: 'a`: generic lifetime `'b` must outlive lifetime `'a`.\n* `T: ?Sized`: allow generic type parameter to be a dynamically-sized type.  See [Unsized Types (`?Sized`)].\n* `'a + trait`, `trait + trait`: compound type constraint.  See [Traits (Multiple Trait Bounds)].\n\n<!-- Macros and attributes -->\n\n* `#[meta]`: outer attribute.  See [Attributes].\n* `#![meta]`: inner attribute.  See [Attributes].\n* `$ident`: macro substitution.  See [Macros].\n* `$ident:kind`: macro capture.  See [Macros].\n* `$(…)…`: macro repetition.  See [Macros].\n\n<!-- Comments -->\n\n* `//`: line comment.  See [Comments].\n* `//!`: inner line doc comment.  See [Comments].\n* `///`: outer line doc comment.  See [Comments].\n* `/*…*/`: block comment.  See [Comments].\n* `/*!…*/`: inner block doc comment.  See [Comments].\n* `/**…*/`: outer block doc comment.  See [Comments].\n\n<!-- Various things involving parens and tuples -->\n\n* `()`: empty tuple (*a.k.a.* unit), both literal and type.\n* `(expr)`: parenthesized expression.\n* `(expr,)`: single-element tuple expression.  See [Primitive Types (Tuples)].\n* `(type,)`: single-element tuple type.  See [Primitive Types (Tuples)].\n* `(expr, …)`: tuple expression.  See [Primitive Types (Tuples)].\n* `(type, …)`: tuple type.  See [Primitive Types (Tuples)].\n* `expr(expr, …)`: function call expression.  Also used to initialize tuple `struct`s and tuple `enum` variants.  See [Functions].\n* `ident!(…)`, `ident!{…}`, `ident![…]`: macro invocation.  See [Macros].\n* `expr.0`, `expr.1`, …: tuple indexing.  See [Primitive Types (Tuple Indexing)].\n\n<!-- Bracey things -->\n\n* `{…}`: block expression.\n* `Type {…}`: `struct` literal.  See [Structs].\n\n<!-- Brackety things -->\n\n* `[…]`: array literal.  See [Primitive Types (Arrays)].\n* `[expr; len]`: array literal containing `len` copies of `expr`.  See [Primitive Types (Arrays)].\n* `[type; len]`: array type containing `len` instances of `type`.  See [Primitive Types (Arrays)].\n* `expr[expr]`: collection indexing.  Overloadable (`Index`, `IndexMut`).\n* `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`: collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, `RangeFull` as the \"index\".\n\n[`const` and `static` (`static`)]: const-and-static.html#static\n[`const` and `static`]: const-and-static.html\n[`if let`]: if-let.html\n[`if`]: if.html\n[`type` Aliases]: type-aliases.html\n[Associated Types]: associated-types.html\n[Attributes]: attributes.html\n[Casting Between Types (`as`)]: casting-between-types.html#as\n[Closures (`move` closures)]: closures.html#move-closures\n[Closures]: closures.html\n[Comments]: comments.html\n[Crates and Modules (Defining Modules)]: crates-and-modules.html#defining-modules\n[Crates and Modules (Exporting a Public Interface)]: crates-and-modules.html#exporting-a-public-interface\n[Crates and Modules (Importing External Crates)]: crates-and-modules.html#importing-external-crates\n[Crates and Modules (Importing Modules with `use`)]: crates-and-modules.html#importing-modules-with-use\n[Crates and Modules (Re-exporting with `pub use`)]: crates-and-modules.html#re-exporting-with-pub-use\n[Diverging Functions]: functions.html#diverging-functions\n[Enums]: enums.html\n[Foreign Function Interface]: ffi.html\n[Functions (Early Returns)]: functions.html#early-returns\n[Functions]: functions.html\n[Generics]: generics.html\n[Iterators]: iterators.html\n[Lifetimes]: lifetimes.html\n[Loops (`for`)]: loops.html#for\n[Loops (`loop`)]: loops.html#loop\n[Loops (`while`)]: loops.html#while\n[Loops (Ending Iteration Early)]: loops.html#ending-iteration-early\n[Loops (Loops Labels)]: loops.html#loop-labels\n[Macros]: macros.html\n[Match]: match.html\n[Method Syntax (Method Calls)]: method-syntax.html#method-calls\n[Method Syntax]: method-syntax.html\n[Mutability]: mutability.html\n[Operators and Overloading]: operators-and-overloading.html\n[Patterns (`ref` and `ref mut`)]: patterns.html#ref-and-ref-mut\n[Patterns (Bindings)]: patterns.html#bindings\n[Patterns (Ignoring bindings)]: patterns.html#ignoring-bindings\n[Patterns (Multiple patterns)]: patterns.html#multiple-patterns\n[Patterns (Ranges)]: patterns.html#ranges\n[Primitive Types (`char`)]: primitive-types.html#char\n[Primitive Types (Arrays)]: primitive-types.html#arrays\n[Primitive Types (Booleans)]: primitive-types.html#booleans\n[Primitive Types (Tuple Indexing)]: primitive-types.html#tuple-indexing\n[Primitive Types (Tuples)]: primitive-types.html#tuples\n[Raw Pointers]: raw-pointers.html\n[Reference (Byte String Literals)]: ../reference.html#byte-string-literals\n[Reference (Integer literals)]: ../reference.html#integer-literals\n[Reference (Raw Byte String Literals)]: ../reference.html#raw-byte-string-literals\n[Reference (Raw String Literals)]: ../reference.html#raw-string-literals\n[References and Borrowing]: references-and-borrowing.html\n[Strings]: strings.html\n[Structs (Update syntax)]: structs.html#update-syntax\n[Structs]: structs.html\n[Traits (`where` clause)]: traits.html#where-clause\n[Traits (Multiple Trait Bounds)]: traits.html#multiple-trait-bounds\n[Traits]: traits.html\n[Universal Function Call Syntax]: ufcs.html\n[Universal Function Call Syntax (Angle-bracket Form)]: ufcs.html#angle-bracket-form\n[Unsafe]: unsafe.html\n[Unsized Types (`?Sized`)]: unsized-types.html#sized\n[Variable Bindings]: variable-bindings.html\n"
  },
  {
    "path": "trpl/testing.md",
    "content": "% Testing\n\n> Program testing can be a very effective way to show the presence of bugs, but\n> it is hopelessly inadequate for showing their absence.\n>\n> Edsger W. Dijkstra, \"The Humble Programmer\" (1972)\n\nLet's talk about how to test Rust code. What we will not be talking about is\nthe right way to test Rust code. There are many schools of thought regarding\nthe right and wrong way to write tests. All of these approaches use the same\nbasic tools, and so we'll show you the syntax for using them.\n\n# The `test` attribute\n\nAt its simplest, a test in Rust is a function that's annotated with the `test`\nattribute. Let's make a new project with Cargo called `adder`:\n\n```bash\n$ cargo new adder\n$ cd adder\n```\n\nCargo will automatically generate a simple test when you make a new project.\nHere's the contents of `src/lib.rs`:\n\n```rust\n# fn main() {}\n#[test]\nfn it_works() {\n}\n```\n\nNote the `#[test]`. This attribute indicates that this is a test function. It\ncurrently has no body. That's good enough to pass! We can run the tests with\n`cargo test`:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nCargo compiled and ran our tests. There are two sets of output here: one\nfor the test we wrote, and another for documentation tests. We'll talk about\nthose later. For now, see this line:\n\n```text\ntest it_works ... ok\n```\n\nNote the `it_works`. This comes from the name of our function:\n\n```rust\nfn it_works() {\n# }\n```\n\nWe also get a summary line:\n\n```text\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n```\n\nSo why does our do-nothing test pass? Any test which doesn't `panic!` passes,\nand any test that does `panic!` fails. Let's make our test fail:\n\n```rust\n# fn main() {}\n#[test]\nfn it_works() {\n    assert!(false);\n}\n```\n\n`assert!` is a macro provided by Rust which takes one argument: if the argument\nis `true`, nothing happens. If the argument is `false`, it will `panic!`. Let's\nrun our tests again:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest it_works ... FAILED\n\nfailures:\n\n---- it_works stdout ----\n        thread 'it_works' panicked at 'assertion failed: false', /home/steve/tmp/adder/src/lib.rs:3\n\n\n\nfailures:\n    it_works\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured\n\nthread 'main' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247\n```\n\nRust indicates that our test failed:\n\n```text\ntest it_works ... FAILED\n```\n\nAnd that's reflected in the summary line:\n\n```text\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured\n```\n\nWe also get a non-zero status code. We can use `$?` on OS X and Linux:\n\n```bash\n$ echo $?\n101\n```\n\nOn Windows, if you’re using `cmd`:\n\n```bash\n> echo %ERRORLEVEL%\n```\n\nAnd if you’re using PowerShell:\n\n```bash\n> echo $LASTEXITCODE # the code itself\n> echo $? # a boolean, fail or succeed\n```\n\nThis is useful if you want to integrate `cargo test` into other tooling.\n\nWe can invert our test's failure with another attribute: `should_panic`:\n\n```rust\n# fn main() {}\n#[test]\n#[should_panic]\nfn it_works() {\n    assert!(false);\n}\n```\n\nThis test will now succeed if we `panic!` and fail if we complete. Let's try it:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nRust provides another macro, `assert_eq!`, that compares two arguments for\nequality:\n\n```rust\n# fn main() {}\n#[test]\n#[should_panic]\nfn it_works() {\n    assert_eq!(\"Hello\", \"world\");\n}\n```\n\nDoes this test pass or fail? Because of the `should_panic` attribute, it\npasses:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\n`should_panic` tests can be fragile, as it's hard to guarantee that the test\ndidn't fail for an unexpected reason. To help with this, an optional `expected`\nparameter can be added to the `should_panic` attribute. The test harness will\nmake sure that the failure message contains the provided text. A safer version\nof the example above would be:\n\n```rust\n# fn main() {}\n#[test]\n#[should_panic(expected = \"assertion failed\")]\nfn it_works() {\n    assert_eq!(\"Hello\", \"world\");\n}\n```\n\nThat's all there is to the basics! Let's write one 'real' test:\n\n```rust,ignore\n# fn main() {}\npub fn add_two(a: i32) -> i32 {\n    a + 2\n}\n\n#[test]\nfn it_works() {\n    assert_eq!(4, add_two(2));\n}\n```\n\nThis is a very common use of `assert_eq!`: call some function with\nsome known arguments and compare it to the expected output.\n\n# The `ignore` attribute\n\nSometimes a few specific tests can be very time-consuming to execute. These\ncan be disabled by default by using the `ignore` attribute:\n\n```rust\n# fn main() {}\n#[test]\nfn it_works() {\n    assert_eq!(4, add_two(2));\n}\n\n#[test]\n#[ignore]\nfn expensive_test() {\n    // code that takes an hour to run\n}\n```\n\nNow we run our tests and see that `it_works` is run, but `expensive_test` is\nnot:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest expensive_test ... ignored\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 1 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nThe expensive tests can be run explicitly using `cargo test -- --ignored`:\n\n```bash\n$ cargo test -- --ignored\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest expensive_test ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nThe `--ignored` argument is an argument to the test binary, and not to Cargo,\nwhich is why the command is `cargo test -- --ignored`.\n\n# The `tests` module\n\nThere is one way in which our existing example is not idiomatic: it's\nmissing the `tests` module. The idiomatic way of writing our example\nlooks like this:\n\n```rust,ignore\n# fn main() {}\npub fn add_two(a: i32) -> i32 {\n    a + 2\n}\n\n#[cfg(test)]\nmod tests {\n    use super::add_two;\n\n    #[test]\n    fn it_works() {\n        assert_eq!(4, add_two(2));\n    }\n}\n```\n\nThere's a few changes here. The first is the introduction of a `mod tests` with\na `cfg` attribute. The module allows us to group all of our tests together, and\nto also define helper functions if needed, that don't become a part of the rest\nof our crate. The `cfg` attribute only compiles our test code if we're\ncurrently trying to run the tests. This can save compile time, and also ensures\nthat our tests are entirely left out of a normal build.\n\nThe second change is the `use` declaration. Because we're in an inner module,\nwe need to bring our test function into scope. This can be annoying if you have\na large module, and so this is a common use of globs. Let's change our\n`src/lib.rs` to make use of it:\n\n```rust,ignore\n# fn main() {}\npub fn add_two(a: i32) -> i32 {\n    a + 2\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn it_works() {\n        assert_eq!(4, add_two(2));\n    }\n}\n```\n\nNote the different `use` line. Now we run our tests:\n\n```bash\n$ cargo test\n    Updating registry `https://github.com/rust-lang/crates.io-index`\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nIt works!\n\nThe current convention is to use the `tests` module to hold your \"unit-style\"\ntests. Anything that tests one small bit of functionality makes sense to\ngo here. But what about \"integration-style\" tests instead? For that, we have\nthe `tests` directory.\n\n# The `tests` directory\n\nEach file in `tests/*.rs` directory is treated as individual crate.\nSo, to write an integration test, let's make a `tests` directory, and\nput a `tests/integration_test.rs` file inside, with this as its contents:\n\n```rust,ignore\nextern crate adder;\n\n# fn main() {}\n#[test]\nfn it_works() {\n    assert_eq!(4, adder::add_two(2));\n}\n```\n\nThis looks similar to our previous tests, but slightly different. We now have\nan `extern crate adder` at the top. This is because each test in the `tests`\ndirectory is an entirely separate crate, and so we need to import our library.\nThis is also why `tests` is a suitable place to write integration-style tests:\nthey use the library like any other consumer of it would.\n\nLet's run them:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/you/projects/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n     Running target/lib-c18e7d3494509e74\n\nrunning 1 test\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured\n```\n\nNow we have three sections: our previous test is also run, as well as our new\none.\n\nCargo will ignore files in subdirectories of the `tests/` directory.\nTherefore shared modules in integrations tests are possible.\nFor example `tests/common/mod.rs` is not separately compiled by cargo but can\nbe imported in every test with `mod common;`\n\nThat's all there is to the `tests` directory. The `tests` module isn't needed\nhere, since the whole thing is focused on tests.\n\nLet's finally check out that third section: documentation tests.\n\n# Documentation tests\n\nNothing is better than documentation with examples. Nothing is worse than\nexamples that don't actually work, because the code has changed since the\ndocumentation has been written. To this end, Rust supports automatically\nrunning examples in your documentation (**note:** this only works in library\ncrates, not binary crates). Here's a fleshed-out `src/lib.rs` with examples:\n\n```rust,ignore\n# fn main() {}\n//! The `adder` crate provides functions that add numbers to other numbers.\n//!\n//! # Examples\n//!\n//! ```\n//! assert_eq!(4, adder::add_two(2));\n//! ```\n\n/// This function adds two to its argument.\n///\n/// # Examples\n///\n/// ```\n/// use adder::add_two;\n///\n/// assert_eq!(4, add_two(2));\n/// ```\npub fn add_two(a: i32) -> i32 {\n    a + 2\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn it_works() {\n        assert_eq!(4, add_two(2));\n    }\n}\n```\n\nNote the module-level documentation with `//!` and the function-level\ndocumentation with `///`. Rust's documentation supports Markdown in comments,\nand so triple graves mark code blocks. It is conventional to include the\n`# Examples` section, exactly like that, with examples following.\n\nLet's run the tests again:\n\n```bash\n$ cargo test\n   Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n     Running target/adder-91b3e234d4ed382a\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n     Running target/lib-c18e7d3494509e74\n\nrunning 1 test\ntest it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured\n\n   Doc-tests adder\n\nrunning 2 tests\ntest add_two_0 ... ok\ntest _0 ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured\n```\n\nNow we have all three kinds of tests running! Note the names of the\ndocumentation tests: the `_0` is generated for the module test, and `add_two_0`\nfor the function test. These will auto increment with names like `add_two_1` as\nyou add more examples.\n\nWe haven’t covered all of the details with writing documentation tests. For more,\nplease see the [Documentation chapter](documentation.html).\n"
  },
  {
    "path": "trpl/the-stack-and-the-heap.md",
    "content": "% The Stack and the Heap\n\nAs a systems language, Rust operates at a low level. If you’re coming from a\nhigh-level language, there are some aspects of systems programming that you may\nnot be familiar with. The most important one is how memory works, with a stack\nand a heap. If you’re familiar with how C-like languages use stack allocation,\nthis chapter will be a refresher. If you’re not, you’ll learn about this more\ngeneral concept, but with a Rust-y focus.\n\nAs with most things, when learning about them, we’ll use a simplified model to\nstart. This lets you get a handle on the basics, without getting bogged down\nwith details which are, for now, irrelevant. The examples we’ll use aren’t 100%\naccurate, but are representative for the level we’re trying to learn at right\nnow. Once you have the basics down, learning more about how allocators are\nimplemented, virtual memory, and other advanced topics will reveal the leaks in\nthis particular abstraction.\n\n# Memory management\n\nThese two terms are about memory management. The stack and the heap are\nabstractions that help you determine when to allocate and deallocate memory.\n\nHere’s a high-level comparison:\n\nThe stack is very fast, and is where memory is allocated in Rust by default.\nBut the allocation is local to a function call, and is limited in size. The\nheap, on the other hand, is slower, and is explicitly allocated by your\nprogram. But it’s effectively unlimited in size, and is globally accessible.\nNote this meaning of heap, which allocates arbitrary-sized blocks of memory in arbitrary\norder, is quite different from the heap data structure.  \n\n# The Stack\n\nLet’s talk about this Rust program:\n\n```rust\nfn main() {\n    let x = 42;\n}\n```\n\nThis program has one variable binding, `x`. This memory needs to be allocated\nfrom somewhere. Rust ‘stack allocates’ by default, which means that basic\nvalues ‘go on the stack’. What does that mean?\n\nWell, when a function gets called, some memory gets allocated for all of its\nlocal variables and some other information. This is called a ‘stack frame’, and\nfor the purpose of this tutorial, we’re going to ignore the extra information\nand only consider the local variables we’re allocating. So in this case, when\n`main()` is run, we’ll allocate a single 32-bit integer for our stack frame.\nThis is automatically handled for you, as you can see; we didn’t have to write\nany special Rust code or anything.\n\nWhen the function exits, its stack frame gets deallocated. This happens\nautomatically as well.\n\nThat’s all there is for this simple program. The key thing to understand here\nis that stack allocation is very, very fast. Since we know all the local\nvariables we have ahead of time, we can grab the memory all at once. And since\nwe’ll throw them all away at the same time as well, we can get rid of it very\nfast too.\n\nThe downside is that we can’t keep values around if we need them for longer\nthan a single function. We also haven’t talked about what the word, ‘stack’,\nmeans. To do that, we need a slightly more complicated example:\n\n```rust\nfn foo() {\n    let y = 5;\n    let z = 100;\n}\n\nfn main() {\n    let x = 42;\n\n    foo();\n}\n```\n\nThis program has three variables total: two in `foo()`, one in `main()`. Just\nas before, when `main()` is called, a single integer is allocated for its stack\nframe. But before we can show what happens when `foo()` is called, we need to\nvisualize what’s going on with memory. Your operating system presents a view of\nmemory to your program that’s pretty simple: a huge list of addresses, from 0\nto a large number, representing how much RAM your computer has. For example, if\nyou have a gigabyte of RAM, your addresses go from `0` to `1,073,741,823`. That\nnumber comes from 2<sup>30</sup>, the number of bytes in a gigabyte. [^gigabyte]\n\n[^gigabyte]: ‘Gigabyte’ can mean two things: 10^9, or 2^30. The SI standard resolved this by stating that ‘gigabyte’ is 10^9, and ‘gibibyte’ is 2^30. However, very few people use this terminology, and rely on context to differentiate. We follow in that tradition here.\n\nThis memory is kind of like a giant array: addresses start at zero and go\nup to the final number. So here’s a diagram of our first stack frame:\n\n| Address | Name | Value |\n|---------|------|-------|\n| 0       | x    | 42    |\n\nWe’ve got `x` located at address `0`, with the value `42`.\n\nWhen `foo()` is called, a new stack frame is allocated:\n\n| Address | Name | Value |\n|---------|------|-------|\n| 2       | z    | 100   |\n| 1       | y    | 5     |\n| 0       | x    | 42    |\n\nBecause `0` was taken by the first frame, `1` and `2` are used for `foo()`’s\nstack frame. It grows upward, the more functions we call.\n\n\nThere are some important things we have to take note of here. The numbers 0, 1,\nand 2 are all solely for illustrative purposes, and bear no relationship to the\naddress values the computer will use in reality. In particular, the series of\naddresses are in reality going to be separated by some number of bytes that\nseparate each address, and that separation may even exceed the size of the\nvalue being stored.\n\nAfter `foo()` is over, its frame is deallocated:\n\n| Address | Name | Value |\n|---------|------|-------|\n| 0       | x    | 42    |\n\nAnd then, after `main()`, even this last value goes away. Easy!\n\nIt’s called a ‘stack’ because it works like a stack of dinner plates: the first\nplate you put down is the last plate to pick back up. Stacks are sometimes\ncalled ‘last in, first out queues’ for this reason, as the last value you put\non the stack is the first one you retrieve from it.\n\nLet’s try a three-deep example:\n\n```rust\nfn italic() {\n    let i = 6;\n}\n\nfn bold() {\n    let a = 5;\n    let b = 100;\n    let c = 1;\n\n    italic();\n}\n\nfn main() {\n    let x = 42;\n\n    bold();\n}\n```\n\nWe have some kooky function names to make the diagrams clearer.\n\nOkay, first, we call `main()`:\n\n| Address | Name | Value |\n|---------|------|-------|\n| 0       | x    | 42    |\n\nNext up, `main()` calls `bold()`:\n\n| Address | Name | Value |\n|---------|------|-------|\n| **3**   | **c**|**1**  |\n| **2**   | **b**|**100**|\n| **1**   | **a**| **5** |\n| 0       | x    | 42    |\n\nAnd then `bold()` calls `italic()`:\n\n| Address | Name | Value |\n|---------|------|-------|\n| *4*     | *i*  | *6*   |\n| **3**   | **c**|**1**  |\n| **2**   | **b**|**100**|\n| **1**   | **a**| **5** |\n| 0       | x    | 42    |\n\nWhew! Our stack is growing tall.\n\nAfter `italic()` is over, its frame is deallocated, leaving only `bold()` and\n`main()`:\n\n| Address | Name | Value |\n|---------|------|-------|\n| **3**   | **c**|**1**  |\n| **2**   | **b**|**100**|\n| **1**   | **a**| **5** |\n| 0       | x    | 42    |\n\nAnd then `bold()` ends, leaving only `main()`:\n\n| Address | Name | Value |\n|---------|------|-------|\n| 0       | x    | 42    |\n\nAnd then we’re done. Getting the hang of it? It’s like piling up dishes: you\nadd to the top, you take away from the top.\n\n# The Heap\n\nNow, this works pretty well, but not everything can work like this. Sometimes,\nyou need to pass some memory between different functions, or keep it alive for\nlonger than a single function’s execution. For this, we can use the heap.\n\nIn Rust, you can allocate memory on the heap with the [`Box<T>` type][box].\nHere’s an example:\n\n```rust\nfn main() {\n    let x = Box::new(5);\n    let y = 42;\n}\n```\n\n[box]: ../std/boxed/index.html\n\nHere’s what happens in memory when `main()` is called:\n\n| Address | Name | Value  |\n|---------|------|--------|\n| 1       | y    | 42     |\n| 0       | x    | ?????? |\n\nWe allocate space for two variables on the stack. `y` is `42`, as it always has\nbeen, but what about `x`? Well, `x` is a `Box<i32>`, and boxes allocate memory\non the heap. The actual value of the box is a structure which has a pointer to\n‘the heap’. When we start executing the function, and `Box::new()` is called,\nit allocates some memory for the heap, and puts `5` there. The memory now looks\nlike this:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 5                      |\n| ...                  | ...  | ...                    |\n| 1                    | y    | 42                     |\n| 0                    | x    | → (2<sup>30</sup>) - 1 |\n\nWe have (2<sup>30</sup>) - 1 addresses in our hypothetical computer with 1GB of RAM. And since\nour stack grows from zero, the easiest place to allocate memory is from the\nother end. So our first value is at the highest place in memory. And the value\nof the struct at `x` has a [raw pointer][rawpointer] to the place we’ve\nallocated on the heap, so the value of `x` is (2<sup>30</sup>) - 1, the memory\nlocation we’ve asked for.\n\n[rawpointer]: raw-pointers.html\n\nWe haven’t really talked too much about what it actually means to allocate and\ndeallocate memory in these contexts. Getting into very deep detail is out of\nthe scope of this tutorial, but what’s important to point out here is that\nthe heap isn’t a stack that grows from the opposite end. We’ll have an\nexample of this later in the book, but because the heap can be allocated and\nfreed in any order, it can end up with ‘holes’. Here’s a diagram of the memory\nlayout of a program which has been running for a while now:\n\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 5                      |\n| (2<sup>30</sup>) - 2 |      |                        |\n| (2<sup>30</sup>) - 3 |      |                        |\n| (2<sup>30</sup>) - 4 |      | 42                     |\n| ...                  | ...  | ...                    |\n| 2                    | z    | → (2<sup>30</sup>) - 4 |\n| 1                    | y    | 42                     |\n| 0                    | x    | → (2<sup>30</sup>) - 1 |\n\nIn this case, we’ve allocated four things on the heap, but deallocated two of\nthem. There’s a gap between (2<sup>30</sup>) - 1 and (2<sup>30</sup>) - 4 which isn’t\ncurrently being used. The specific details of how and why this happens depends\non what kind of strategy you use to manage the heap. Different programs can use\ndifferent ‘memory allocators’, which are libraries that manage this for you.\nRust programs use [jemalloc][jemalloc] for this purpose.\n\n[jemalloc]: http://www.canonware.com/jemalloc/\n\nAnyway, back to our example. Since this memory is on the heap, it can stay\nalive longer than the function which allocates the box. In this case, however,\nit doesn’t.[^moving] When the function is over, we need to free the stack frame\nfor `main()`. `Box<T>`, though, has a trick up its sleeve: [Drop][drop]. The\nimplementation of `Drop` for `Box` deallocates the memory that was allocated\nwhen it was created. Great! So when `x` goes away, it first frees the memory\nallocated on the heap:\n\n| Address | Name | Value  |\n|---------|------|--------|\n| 1       | y    | 42     |\n| 0       | x    | ?????? |\n\n[drop]: drop.html\n[^moving]: We can make the memory live longer by transferring ownership,\n           sometimes called ‘moving out of the box’. More complex examples will\n           be covered later.\n\n\nAnd then the stack frame goes away, freeing all of our memory.\n\n# Arguments and borrowing\n\nWe’ve got some basic examples with the stack and the heap going, but what about\nfunction arguments and borrowing? Here’s a small Rust program:\n\n```rust\nfn foo(i: &i32) {\n    let z = 42;\n}\n\nfn main() {\n    let x = 5;\n    let y = &x;\n\n    foo(y);\n}\n```\n\nWhen we enter `main()`, memory looks like this:\n\n| Address | Name | Value  |\n|---------|------|--------|\n| 1       | y    | → 0    |\n| 0       | x    | 5      |\n\n`x` is a plain old `5`, and `y` is a reference to `x`. So its value is the\nmemory location that `x` lives at, which in this case is `0`.\n\nWhat about when we call `foo()`, passing `y` as an argument?\n\n| Address | Name | Value  |\n|---------|------|--------|\n| 3       | z    | 42     |\n| 2       | i    | → 0    |\n| 1       | y    | → 0    |\n| 0       | x    | 5      |\n\nStack frames aren’t only for local bindings, they’re for arguments too. So in\nthis case, we need to have both `i`, our argument, and `z`, our local variable\nbinding. `i` is a copy of the argument, `y`. Since `y`’s value is `0`, so is\n`i`’s.\n\nThis is one reason why borrowing a variable doesn’t deallocate any memory: the\nvalue of a reference is a pointer to a memory location. If we got rid of\nthe underlying memory, things wouldn’t work very well.\n\n# A complex example\n\nOkay, let’s go through this complex program step-by-step:\n\n```rust\nfn foo(x: &i32) {\n    let y = 10;\n    let z = &y;\n\n    baz(z);\n    bar(x, z);\n}\n\nfn bar(a: &i32, b: &i32) {\n    let c = 5;\n    let d = Box::new(5);\n    let e = &d;\n\n    baz(e);\n}\n\nfn baz(f: &i32) {\n    let g = 100;\n}\n\nfn main() {\n    let h = 3;\n    let i = Box::new(20);\n    let j = &h;\n\n    foo(j);\n}\n```\n\nFirst, we call `main()`:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nWe allocate memory for `j`, `i`, and `h`. `i` is on the heap, and so has a\nvalue pointing there.\n\nNext, at the end of `main()`, `foo()` gets called:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nSpace gets allocated for `x`, `y`, and `z`. The argument `x` has the same value\nas `j`, since that’s what we passed it in. It’s a pointer to the `0` address,\nsince `j` points at `h`.\n\nNext, `foo()` calls `baz()`, passing `z`:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 7                    | g    | 100                    |\n| 6                    | f    | → 4                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nWe’ve allocated memory for `f` and `g`. `baz()` is very short, so when it’s\nover, we get rid of its stack frame:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nNext, `foo()` calls `bar()` with `x` and `z`:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| (2<sup>30</sup>) - 2 |      | 5                      |\n| ...                  | ...  | ...                    |\n| 10                   | e    | → 9                    |\n| 9                    | d    | → (2<sup>30</sup>) - 2 |\n| 8                    | c    | 5                      |\n| 7                    | b    | → 4                    |\n| 6                    | a    | → 0                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nWe end up allocating another value on the heap, and so we have to subtract one\nfrom (2<sup>30</sup>) - 1. It’s easier to write that than `1,073,741,822`. In any\ncase, we set up the variables as usual.\n\nAt the end of `bar()`, it calls `baz()`:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| (2<sup>30</sup>) - 2 |      | 5                      |\n| ...                  | ...  | ...                    |\n| 12                   | g    | 100                    |\n| 11                   | f    | → (2<sup>30</sup>) - 2 |\n| 10                   | e    | → 9                    |\n| 9                    | d    | → (2<sup>30</sup>) - 2 |\n| 8                    | c    | 5                      |\n| 7                    | b    | → 4                    |\n| 6                    | a    | → 0                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nWith this, we’re at our deepest point! Whew! Congrats for following along this\nfar.\n\nAfter `baz()` is over, we get rid of `f` and `g`:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| (2<sup>30</sup>) - 2 |      | 5                      |\n| ...                  | ...  | ...                    |\n| 10                   | e    | → 9                    |\n| 9                    | d    | → (2<sup>30</sup>) - 2 |\n| 8                    | c    | 5                      |\n| 7                    | b    | → 4                    |\n| 6                    | a    | → 0                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nNext, we return from `bar()`. `d` in this case is a `Box<T>`, so it also frees\nwhat it points to: (2<sup>30</sup>) - 2.\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 5                    | z    | → 4                    |\n| 4                    | y    | 10                     |\n| 3                    | x    | → 0                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nAnd after that, `foo()` returns:\n\n| Address              | Name | Value                  |\n|----------------------|------|------------------------|\n| (2<sup>30</sup>) - 1 |      | 20                     |\n| ...                  | ...  | ...                    |\n| 2                    | j    | → 0                    |\n| 1                    | i    | → (2<sup>30</sup>) - 1 |\n| 0                    | h    | 3                      |\n\nAnd then, finally, `main()`, which cleans the rest up. When `i` is `Drop`ped,\nit will clean up the last of the heap too.\n\n# What do other languages do?\n\nMost languages with a garbage collector heap-allocate by default. This means\nthat every value is boxed. There are a number of reasons why this is done, but\nthey’re out of scope for this tutorial. There are some possible optimizations\nthat don’t make it true 100% of the time, too. Rather than relying on the stack\nand `Drop` to clean up memory, the garbage collector deals with the heap\ninstead.\n\n# Which to use?\n\nSo if the stack is faster and easier to manage, why do we need the heap? A big\nreason is that Stack-allocation alone means you only have 'Last In First Out (LIFO)' semantics for\nreclaiming storage. Heap-allocation is strictly more general, allowing storage\nto be taken from and returned to the pool in arbitrary order, but at a\ncomplexity cost.\n\nGenerally, you should prefer stack allocation, and so, Rust stack-allocates by\ndefault. The LIFO model of the stack is simpler, at a fundamental level. This\nhas two big impacts: runtime efficiency and semantic impact.\n\n## Runtime Efficiency\n\nManaging the memory for the stack is trivial: The machine\nincrements or decrements a single value, the so-called “stack pointer”.\nManaging memory for the heap is non-trivial: heap-allocated memory is freed at\narbitrary points, and each block of heap-allocated memory can be of arbitrary\nsize, so the memory manager must generally work much harder to\nidentify memory for reuse.\n\nIf you’d like to dive into this topic in greater detail, [this paper][wilson]\nis a great introduction.\n\n[wilson]: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.143.4688\n\n## Semantic impact\n\nStack-allocation impacts the Rust language itself, and thus the developer’s\nmental model. The LIFO semantics is what drives how the Rust language handles\nautomatic memory management. Even the deallocation of a uniquely-owned\nheap-allocated box can be driven by the stack-based LIFO semantics, as\ndiscussed throughout this chapter. The flexibility (i.e. expressiveness) of non\nLIFO-semantics means that in general the compiler cannot automatically infer at\ncompile-time where memory should be freed; it has to rely on dynamic protocols,\npotentially from outside the language itself, to drive deallocation (reference\ncounting, as used by `Rc<T>` and `Arc<T>`, is one example of this).\n\nWhen taken to the extreme, the increased expressive power of heap allocation\ncomes at the cost of either significant runtime support (e.g. in the form of a\ngarbage collector) or significant programmer effort (in the form of explicit\nmemory management calls that require verification not provided by the Rust\ncompiler).\n"
  },
  {
    "path": "trpl/trait-objects.md",
    "content": "% Trait Objects\n\nWhen code involves polymorphism, there needs to be a mechanism to determine\nwhich specific version is actually run. This is called ‘dispatch’. There are\ntwo major forms of dispatch: static dispatch and dynamic dispatch. While Rust\nfavors static dispatch, it also supports dynamic dispatch through a mechanism\ncalled ‘trait objects’.\n\n## Background\n\nFor the rest of this chapter, we’ll need a trait and some implementations.\nLet’s make a simple one, `Foo`. It has one method that is expected to return a\n`String`.\n\n```rust\ntrait Foo {\n    fn method(&self) -> String;\n}\n```\n\nWe’ll also implement this trait for `u8` and `String`:\n\n```rust\n# trait Foo { fn method(&self) -> String; }\nimpl Foo for u8 {\n    fn method(&self) -> String { format!(\"u8: {}\", *self) }\n}\n\nimpl Foo for String {\n    fn method(&self) -> String { format!(\"string: {}\", *self) }\n}\n```\n\n\n## Static dispatch\n\nWe can use this trait to perform static dispatch with trait bounds:\n\n```rust\n# trait Foo { fn method(&self) -> String; }\n# impl Foo for u8 { fn method(&self) -> String { format!(\"u8: {}\", *self) } }\n# impl Foo for String { fn method(&self) -> String { format!(\"string: {}\", *self) } }\nfn do_something<T: Foo>(x: T) {\n    x.method();\n}\n\nfn main() {\n    let x = 5u8;\n    let y = \"Hello\".to_string();\n\n    do_something(x);\n    do_something(y);\n}\n```\n\nRust uses ‘monomorphization’ to perform static dispatch here. This means that\nRust will create a special version of `do_something()` for both `u8` and\n`String`, and then replace the call sites with calls to these specialized\nfunctions. In other words, Rust generates something like this:\n\n```rust\n# trait Foo { fn method(&self) -> String; }\n# impl Foo for u8 { fn method(&self) -> String { format!(\"u8: {}\", *self) } }\n# impl Foo for String { fn method(&self) -> String { format!(\"string: {}\", *self) } }\nfn do_something_u8(x: u8) {\n    x.method();\n}\n\nfn do_something_string(x: String) {\n    x.method();\n}\n\nfn main() {\n    let x = 5u8;\n    let y = \"Hello\".to_string();\n\n    do_something_u8(x);\n    do_something_string(y);\n}\n```\n\nThis has a great upside: static dispatch allows function calls to be\ninlined because the callee is known at compile time, and inlining is\nthe key to good optimization. Static dispatch is fast, but it comes at\na tradeoff: ‘code bloat’, due to many copies of the same function\nexisting in the binary, one for each type.\n\nFurthermore, compilers aren’t perfect and may “optimize” code to become slower.\nFor example, functions inlined too eagerly will bloat the instruction cache\n(cache rules everything around us). This is part of the reason that `#[inline]`\nand `#[inline(always)]` should be used carefully, and one reason why using a\ndynamic dispatch is sometimes more efficient.\n\nHowever, the common case is that it is more efficient to use static dispatch,\nand one can always have a thin statically-dispatched wrapper function that does\na dynamic dispatch, but not vice versa, meaning static calls are more flexible.\nThe standard library tries to be statically dispatched where possible for this\nreason.\n\n## Dynamic dispatch\n\nRust provides dynamic dispatch through a feature called ‘trait objects’. Trait\nobjects, like `&Foo` or `Box<Foo>`, are normal values that store a value of\n*any* type that implements the given trait, where the precise type can only be\nknown at runtime.\n\nA trait object can be obtained from a pointer to a concrete type that\nimplements the trait by *casting* it (e.g. `&x as &Foo`) or *coercing* it\n(e.g. using `&x` as an argument to a function that takes `&Foo`).\n\nThese trait object coercions and casts also work for pointers like `&mut T` to\n`&mut Foo` and `Box<T>` to `Box<Foo>`, but that’s all at the moment. Coercions\nand casts are identical.\n\nThis operation can be seen as ‘erasing’ the compiler’s knowledge about the\nspecific type of the pointer, and hence trait objects are sometimes referred to\nas ‘type erasure’.\n\nComing back to the example above, we can use the same trait to perform dynamic\ndispatch with trait objects by casting:\n\n```rust\n# trait Foo { fn method(&self) -> String; }\n# impl Foo for u8 { fn method(&self) -> String { format!(\"u8: {}\", *self) } }\n# impl Foo for String { fn method(&self) -> String { format!(\"string: {}\", *self) } }\nfn do_something(x: &Foo) {\n    x.method();\n}\n\nfn main() {\n    let x = 5u8;\n    do_something(&x as &Foo);\n}\n```\n\nor by coercing:\n\n```rust\n# trait Foo { fn method(&self) -> String; }\n# impl Foo for u8 { fn method(&self) -> String { format!(\"u8: {}\", *self) } }\n# impl Foo for String { fn method(&self) -> String { format!(\"string: {}\", *self) } }\nfn do_something(x: &Foo) {\n    x.method();\n}\n\nfn main() {\n    let x = \"Hello\".to_string();\n    do_something(&x);\n}\n```\n\nA function that takes a trait object is not specialized to each of the types\nthat implements `Foo`: only one copy is generated, often (but not always)\nresulting in less code bloat. However, this comes at the cost of requiring\nslower virtual function calls, and effectively inhibiting any chance of\ninlining and related optimizations from occurring.\n\n### Why pointers?\n\nRust does not put things behind a pointer by default, unlike many managed\nlanguages, so types can have different sizes. Knowing the size of the value at\ncompile time is important for things like passing it as an argument to a\nfunction, moving it about on the stack and allocating (and deallocating) space\non the heap to store it.\n\nFor `Foo`, we would need to have a value that could be at least either a\n`String` (24 bytes) or a `u8` (1 byte), as well as any other type for which\ndependent crates may implement `Foo` (any number of bytes at all). There’s no\nway to guarantee that this last point can work if the values are stored without\na pointer, because those other types can be arbitrarily large.\n\nPutting the value behind a pointer means the size of the value is not relevant\nwhen we are tossing a trait object around, only the size of the pointer itself.\n\n### Representation\n\nThe methods of the trait can be called on a trait object via a special record\nof function pointers traditionally called a ‘vtable’ (created and managed by\nthe compiler).\n\nTrait objects are both simple and complicated: their core representation and\nlayout is quite straight-forward, but there are some curly error messages and\nsurprising behaviors to discover.\n\nLet’s start simple, with the runtime representation of a trait object. The\n`std::raw` module contains structs with layouts that are the same as the\ncomplicated built-in types, [including trait objects][stdraw]:\n\n```rust\n# mod foo {\npub struct TraitObject {\n    pub data: *mut (),\n    pub vtable: *mut (),\n}\n# }\n```\n\n[stdraw]: ../std/raw/struct.TraitObject.html\n\nThat is, a trait object like `&Foo` consists of a ‘data’ pointer and a ‘vtable’\npointer.\n\nThe data pointer addresses the data (of some unknown type `T`) that the trait\nobject is storing, and the vtable pointer points to the vtable (‘virtual method\ntable’) corresponding to the implementation of `Foo` for `T`.\n\n\nA vtable is essentially a struct of function pointers, pointing to the concrete\npiece of machine code for each method in the implementation. A method call like\n`trait_object.method()` will retrieve the correct pointer out of the vtable and\nthen do a dynamic call of it. For example:\n\n```rust,ignore\nstruct FooVtable {\n    destructor: fn(*mut ()),\n    size: usize,\n    align: usize,\n    method: fn(*const ()) -> String,\n}\n\n// u8:\n\nfn call_method_on_u8(x: *const ()) -> String {\n    // the compiler guarantees that this function is only called\n    // with `x` pointing to a u8\n    let byte: &u8 = unsafe { &*(x as *const u8) };\n\n    byte.method()\n}\n\nstatic Foo_for_u8_vtable: FooVtable = FooVtable {\n    destructor: /* compiler magic */,\n    size: 1,\n    align: 1,\n\n    // cast to a function pointer\n    method: call_method_on_u8 as fn(*const ()) -> String,\n};\n\n\n// String:\n\nfn call_method_on_String(x: *const ()) -> String {\n    // the compiler guarantees that this function is only called\n    // with `x` pointing to a String\n    let string: &String = unsafe { &*(x as *const String) };\n\n    string.method()\n}\n\nstatic Foo_for_String_vtable: FooVtable = FooVtable {\n    destructor: /* compiler magic */,\n    // values for a 64-bit computer, halve them for 32-bit ones\n    size: 24,\n    align: 8,\n\n    method: call_method_on_String as fn(*const ()) -> String,\n};\n```\n\nThe `destructor` field in each vtable points to a function that will clean up\nany resources of the vtable’s type: for `u8` it is trivial, but for `String` it\nwill free the memory. This is necessary for owning trait objects like\n`Box<Foo>`, which need to clean-up both the `Box` allocation as well as the\ninternal type when they go out of scope. The `size` and `align` fields store\nthe size of the erased type, and its alignment requirements; these are\nessentially unused at the moment since the information is embedded in the\ndestructor, but will be used in the future, as trait objects are progressively\nmade more flexible.\n\nSuppose we’ve got some values that implement `Foo`. The explicit form of\nconstruction and use of `Foo` trait objects might look a bit like (ignoring the\ntype mismatches: they’re all pointers anyway):\n\n```rust,ignore\nlet a: String = \"foo\".to_string();\nlet x: u8 = 1;\n\n// let b: &Foo = &a;\nlet b = TraitObject {\n    // store the data\n    data: &a,\n    // store the methods\n    vtable: &Foo_for_String_vtable\n};\n\n// let y: &Foo = x;\nlet y = TraitObject {\n    // store the data\n    data: &x,\n    // store the methods\n    vtable: &Foo_for_u8_vtable\n};\n\n// b.method();\n(b.vtable.method)(b.data);\n\n// y.method();\n(y.vtable.method)(y.data);\n```\n\n## Object Safety\n\nNot every trait can be used to make a trait object. For example, vectors implement\n`Clone`, but if we try to make a trait object:\n\n```rust,ignore\nlet v = vec![1, 2, 3];\nlet o = &v as &Clone;\n```\n\nWe get an error:\n\n```text\nerror: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]\nlet o = &v as &Clone;\n        ^~\nnote: the trait cannot require that `Self : Sized`\nlet o = &v as &Clone;\n        ^~\n```\n\nThe error says that `Clone` is not ‘object-safe’. Only traits that are\nobject-safe can be made into trait objects. A trait is object-safe if both of\nthese are true:\n\n* the trait does not require that `Self: Sized`\n* all of its methods are object-safe\n\nSo what makes a method object-safe? Each method must require that `Self: Sized`\nor all of the following:\n\n* must not have any type parameters\n* must not use `Self`\n\nWhew! As we can see, almost all of these rules talk about `Self`. A good intuition\nis “except in special circumstances, if your trait’s method uses `Self`, it is not\nobject-safe.”\n"
  },
  {
    "path": "trpl/traits.md",
    "content": "% Traits\n\nA trait is a language feature that tells the Rust compiler about\nfunctionality a type must provide.\n\nRecall the `impl` keyword, used to call a function with [method\nsyntax][methodsyntax]:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n}\n```\n\n[methodsyntax]: method-syntax.html\n\nTraits are similar, except that we first define a trait with a method\nsignature, then implement the trait for a type. In this example, we implement the trait `HasArea` for `Circle`:\n\n```rust\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\ntrait HasArea {\n    fn area(&self) -> f64;\n}\n\nimpl HasArea for Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n}\n```\n\nAs you can see, the `trait` block looks very similar to the `impl` block,\nbut we don’t define a body, only a type signature. When we `impl` a trait,\nwe use `impl Trait for Item`, rather than only `impl Item`.\n\n## Trait bounds on generic functions\n\nTraits are useful because they allow a type to make certain promises about its\nbehavior. Generic functions can exploit this to constrain, or [bound][bounds], the types they\naccept. Consider this function, which does not compile:\n\n[bounds]: glossary.html#bounds\n\n```rust,ignore\nfn print_area<T>(shape: T) {\n    println!(\"This shape has an area of {}\", shape.area());\n}\n```\n\nRust complains:\n\n```text\nerror: no method named `area` found for type `T` in the current scope\n```\n\nBecause `T` can be any type, we can’t be sure that it implements the `area`\nmethod. But we can add a trait bound to our generic `T`, ensuring\nthat it does:\n\n```rust\n# trait HasArea {\n#     fn area(&self) -> f64;\n# }\nfn print_area<T: HasArea>(shape: T) {\n    println!(\"This shape has an area of {}\", shape.area());\n}\n```\n\nThe syntax `<T: HasArea>` means “any type that implements the `HasArea` trait.”\nBecause traits define function type signatures, we can be sure that any type\nwhich implements `HasArea` will have an `.area()` method.\n\nHere’s an extended example of how this works:\n\n```rust\ntrait HasArea {\n    fn area(&self) -> f64;\n}\n\nstruct Circle {\n    x: f64,\n    y: f64,\n    radius: f64,\n}\n\nimpl HasArea for Circle {\n    fn area(&self) -> f64 {\n        std::f64::consts::PI * (self.radius * self.radius)\n    }\n}\n\nstruct Square {\n    x: f64,\n    y: f64,\n    side: f64,\n}\n\nimpl HasArea for Square {\n    fn area(&self) -> f64 {\n        self.side * self.side\n    }\n}\n\nfn print_area<T: HasArea>(shape: T) {\n    println!(\"This shape has an area of {}\", shape.area());\n}\n\nfn main() {\n    let c = Circle {\n        x: 0.0f64,\n        y: 0.0f64,\n        radius: 1.0f64,\n    };\n\n    let s = Square {\n        x: 0.0f64,\n        y: 0.0f64,\n        side: 1.0f64,\n    };\n\n    print_area(c);\n    print_area(s);\n}\n```\n\nThis program outputs:\n\n```text\nThis shape has an area of 3.141593\nThis shape has an area of 1\n```\n\nAs you can see, `print_area` is now generic, but also ensures that we have\npassed in the correct types. If we pass in an incorrect type:\n\n```rust,ignore\nprint_area(5);\n```\n\nWe get a compile-time error:\n\n```text\nerror: the trait bound `_ : HasArea` is not satisfied [E0277]\n```\n\n## Trait bounds on generic structs\n\nYour generic structs can also benefit from trait bounds. All you need to\ndo is append the bound when you declare type parameters. Here is a new\ntype `Rectangle<T>` and its operation `is_square()`:\n\n```rust\nstruct Rectangle<T> {\n    x: T,\n    y: T,\n    width: T,\n    height: T,\n}\n\nimpl<T: PartialEq> Rectangle<T> {\n    fn is_square(&self) -> bool {\n        self.width == self.height\n    }\n}\n\nfn main() {\n    let mut r = Rectangle {\n        x: 0,\n        y: 0,\n        width: 47,\n        height: 47,\n    };\n\n    assert!(r.is_square());\n\n    r.height = 42;\n    assert!(!r.is_square());\n}\n```\n\n`is_square()` needs to check that the sides are equal, so the sides must be of\na type that implements the [`core::cmp::PartialEq`][PartialEq] trait:\n\n```rust,ignore\nimpl<T: PartialEq> Rectangle<T> { ... }\n```\n\nNow, a rectangle can be defined in terms of any type that can be compared for\nequality.\n\n[PartialEq]: ../core/cmp/trait.PartialEq.html\n\nHere we defined a new struct `Rectangle` that accepts numbers of any\nprecision—really, objects of pretty much any type—as long as they can be\ncompared for equality. Could we do the same for our `HasArea` structs, `Square`\nand `Circle`? Yes, but they need multiplication, and to work with that we need\nto know more about [operator traits][operators-and-overloading].\n\n[operators-and-overloading]: operators-and-overloading.html\n\n# Rules for implementing traits\n\nSo far, we’ve only added trait implementations to structs, but you can\nimplement a trait for any type. So technically, we _could_ implement `HasArea`\nfor `i32`:\n\n```rust\ntrait HasArea {\n    fn area(&self) -> f64;\n}\n\nimpl HasArea for i32 {\n    fn area(&self) -> f64 {\n        println!(\"this is silly\");\n\n        *self as f64\n    }\n}\n\n5.area();\n```\n\nIt is considered poor style to implement methods on such primitive types, even\nthough it is possible.\n\nThis may seem like the Wild West, but there are two restrictions around\nimplementing traits that prevent this from getting out of hand. The first is\nthat if the trait isn’t defined in your scope, it doesn’t apply. Here’s an\nexample: the standard library provides a [`Write`][write] trait which adds\nextra functionality to `File`s, for doing file I/O. By default, a `File`\nwon’t have its methods:\n\n[write]: ../std/io/trait.Write.html\n\n```rust,ignore\nlet mut f = std::fs::File::open(\"foo.txt\").expect(\"Couldn’t open foo.txt\");\nlet buf = b\"whatever\"; // byte string literal. buf: &[u8; 8]\nlet result = f.write(buf);\n# result.unwrap(); // ignore the error\n```\n\nHere’s the error:\n\n```text\nerror: type `std::fs::File` does not implement any method in scope named `write`\nlet result = f.write(buf);\n               ^~~~~~~~~~\n```\n\nWe need to `use` the `Write` trait first:\n\n```rust,ignore\nuse std::io::Write;\n\nlet mut f = std::fs::File::open(\"foo.txt\").expect(\"Couldn’t open foo.txt\");\nlet buf = b\"whatever\";\nlet result = f.write(buf);\n# result.unwrap(); // ignore the error\n```\n\nThis will compile without error.\n\nThis means that even if someone does something bad like add methods to `i32`,\nit won’t affect you, unless you `use` that trait.\n\nThere’s one more restriction on implementing traits: either the trait\nor the type you’re implementing it for must be defined by you. Or more\nprecisely, one of them must be defined in the same crate as the `impl`\nyou're writing. For more on Rust's module and package system, see the\nchapter on [crates and modules][cm].\n\nSo, we could implement the `HasArea` type for `i32`, because we defined\n`HasArea` in our code. But if we tried to implement `ToString`, a trait\nprovided by Rust, for `i32`, we could not, because neither the trait nor\nthe type are defined in our crate.\n\nOne last thing about traits: generic functions with a trait bound use\n‘monomorphization’ (mono: one, morph: form), so they are statically dispatched.\nWhat’s that mean? Check out the chapter on [trait objects][to] for more details.\n\n[cm]: crates-and-modules.html\n[to]: trait-objects.html\n\n# Multiple trait bounds\n\nYou’ve seen that you can bound a generic type parameter with a trait:\n\n```rust\nfn foo<T: Clone>(x: T) {\n    x.clone();\n}\n```\n\nIf you need more than one bound, you can use `+`:\n\n```rust\nuse std::fmt::Debug;\n\nfn foo<T: Clone + Debug>(x: T) {\n    x.clone();\n    println!(\"{:?}\", x);\n}\n```\n\n`T` now needs to be both `Clone` as well as `Debug`.\n\n# Where clause\n\nWriting functions with only a few generic types and a small number of trait\nbounds isn’t too bad, but as the number increases, the syntax gets increasingly\nawkward:\n\n```rust\nuse std::fmt::Debug;\n\nfn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {\n    x.clone();\n    y.clone();\n    println!(\"{:?}\", y);\n}\n```\n\nThe name of the function is on the far left, and the parameter list is on the\nfar right. The bounds are getting in the way.\n\nRust has a solution, and it’s called a ‘`where` clause’:\n\n```rust\nuse std::fmt::Debug;\n\nfn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {\n    x.clone();\n    y.clone();\n    println!(\"{:?}\", y);\n}\n\nfn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {\n    x.clone();\n    y.clone();\n    println!(\"{:?}\", y);\n}\n\nfn main() {\n    foo(\"Hello\", \"world\");\n    bar(\"Hello\", \"world\");\n}\n```\n\n`foo()` uses the syntax we showed earlier, and `bar()` uses a `where` clause.\nAll you need to do is leave off the bounds when defining your type parameters,\nand then add `where` after the parameter list. For longer lists, whitespace can\nbe added:\n\n```rust\nuse std::fmt::Debug;\n\nfn bar<T, K>(x: T, y: K)\n    where T: Clone,\n          K: Clone + Debug {\n\n    x.clone();\n    y.clone();\n    println!(\"{:?}\", y);\n}\n```\n\nThis flexibility can add clarity in complex situations.\n\n`where` is also more powerful than the simpler syntax. For example:\n\n```rust\ntrait ConvertTo<Output> {\n    fn convert(&self) -> Output;\n}\n\nimpl ConvertTo<i64> for i32 {\n    fn convert(&self) -> i64 { *self as i64 }\n}\n\n// can be called with T == i32\nfn normal<T: ConvertTo<i64>>(x: &T) -> i64 {\n    x.convert()\n}\n\n// can be called with T == i64\nfn inverse<T>(x: i32) -> T\n        // this is using ConvertTo as if it were \"ConvertTo<i64>\"\n        where i32: ConvertTo<T> {\n    x.convert()\n}\n```\n\nThis shows off the additional feature of `where` clauses: they allow bounds\non the left-hand side not only of type parameters `T`, but also of types (`i32` in this case). In this example, `i32` must implement\n`ConvertTo<T>`. Rather than defining what `i32` is (since that's obvious), the\n`where` clause here constrains `T`.\n\n# Default methods\n\nA default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, `is_invalid()` is defined as the opposite of `is_valid()`:\n\n```rust\ntrait Foo {\n    fn is_valid(&self) -> bool;\n\n    fn is_invalid(&self) -> bool { !self.is_valid() }\n}\n```\n\nImplementors of the `Foo` trait need to implement `is_valid()` but not `is_invalid()` due to the added default behavior. This default behavior can still be overridden as in:\n\n```rust\n# trait Foo {\n#     fn is_valid(&self) -> bool;\n#\n#     fn is_invalid(&self) -> bool { !self.is_valid() }\n# }\nstruct UseDefault;\n\nimpl Foo for UseDefault {\n    fn is_valid(&self) -> bool {\n        println!(\"Called UseDefault.is_valid.\");\n        true\n    }\n}\n\nstruct OverrideDefault;\n\nimpl Foo for OverrideDefault {\n    fn is_valid(&self) -> bool {\n        println!(\"Called OverrideDefault.is_valid.\");\n        true\n    }\n\n    fn is_invalid(&self) -> bool {\n        println!(\"Called OverrideDefault.is_invalid!\");\n        true // overrides the expected value of is_invalid()\n    }\n}\n\nlet default = UseDefault;\nassert!(!default.is_invalid()); // prints \"Called UseDefault.is_valid.\"\n\nlet over = OverrideDefault;\nassert!(over.is_invalid()); // prints \"Called OverrideDefault.is_invalid!\"\n```\n\n# Inheritance\n\nSometimes, implementing a trait requires implementing another trait:\n\n```rust\ntrait Foo {\n    fn foo(&self);\n}\n\ntrait FooBar : Foo {\n    fn foobar(&self);\n}\n```\n\nImplementors of `FooBar` must also implement `Foo`, like this:\n\n```rust\n# trait Foo {\n#     fn foo(&self);\n# }\n# trait FooBar : Foo {\n#     fn foobar(&self);\n# }\nstruct Baz;\n\nimpl Foo for Baz {\n    fn foo(&self) { println!(\"foo\"); }\n}\n\nimpl FooBar for Baz {\n    fn foobar(&self) { println!(\"foobar\"); }\n}\n```\n\nIf we forget to implement `Foo`, Rust will tell us:\n\n```text\nerror: the trait bound `main::Baz : main::Foo` is not satisfied [E0277]\n```\n\n# Deriving\n\nImplementing traits like `Debug` and `Default` repeatedly can become\nquite tedious. For that reason, Rust provides an [attribute][attributes] that\nallows you to let Rust automatically implement traits for you:\n\n```rust\n#[derive(Debug)]\nstruct Foo;\n\nfn main() {\n    println!(\"{:?}\", Foo);\n}\n```\n\n[attributes]: attributes.html\n\nHowever, deriving is limited to a certain set of traits:\n\n- [`Clone`](../core/clone/trait.Clone.html)\n- [`Copy`](../core/marker/trait.Copy.html)\n- [`Debug`](../core/fmt/trait.Debug.html)\n- [`Default`](../core/default/trait.Default.html)\n- [`Eq`](../core/cmp/trait.Eq.html)\n- [`Hash`](../core/hash/trait.Hash.html)\n- [`Ord`](../core/cmp/trait.Ord.html)\n- [`PartialEq`](../core/cmp/trait.PartialEq.html)\n- [`PartialOrd`](../core/cmp/trait.PartialOrd.html)\n"
  },
  {
    "path": "trpl/type-aliases.md",
    "content": "% `type` Aliases\n\nThe `type` keyword lets you declare an alias of another type:\n\n```rust\ntype Name = String;\n```\n\nYou can then use this type as if it were a real type:\n\n```rust\ntype Name = String;\n\nlet x: Name = \"Hello\".to_string();\n```\n\nNote, however, that this is an _alias_, not a new type entirely. In other\nwords, because Rust is strongly typed, you’d expect a comparison between two\ndifferent types to fail:\n\n```rust,ignore\nlet x: i32 = 5;\nlet y: i64 = 5;\n\nif x == y {\n   // ...\n}\n```\n\nthis gives\n\n```text\nerror: mismatched types:\n expected `i32`,\n    found `i64`\n(expected i32,\n    found i64) [E0308]\n     if x == y {\n             ^\n```\n\nBut, if we had an alias:\n\n```rust\ntype Num = i32;\n\nlet x: i32 = 5;\nlet y: Num = 5;\n\nif x == y {\n   // ...\n}\n```\n\nThis compiles without error. Values of a `Num` type are the same as a value of\ntype `i32`, in every way. You can use [tuple struct] to really get a new type.\n\n[tuple struct]: structs.html#tuple-structs\n\nYou can also use type aliases with generics:\n\n```rust\nuse std::result;\n\nenum ConcreteError {\n    Foo,\n    Bar,\n}\n\ntype Result<T> = result::Result<T, ConcreteError>;\n```\n\nThis creates a specialized version of the `Result` type, which always has a\n`ConcreteError` for the `E` part of `Result<T, E>`. This is commonly used\nin the standard library to create custom errors for each subsection. For\nexample, [io::Result][ioresult].\n\n[ioresult]: ../std/io/type.Result.html\n"
  },
  {
    "path": "trpl/ufcs.md",
    "content": "% Universal Function Call Syntax\n\nSometimes, functions can have the same names. Consider this code:\n\n```rust\ntrait Foo {\n    fn f(&self);\n}\n\ntrait Bar {\n    fn f(&self);\n}\n\nstruct Baz;\n\nimpl Foo for Baz {\n    fn f(&self) { println!(\"Baz’s impl of Foo\"); }\n}\n\nimpl Bar for Baz {\n    fn f(&self) { println!(\"Baz’s impl of Bar\"); }\n}\n\nlet b = Baz;\n```\n\nIf we were to try to call `b.f()`, we’d get an error:\n\n```text\nerror: multiple applicable methods in scope [E0034]\nb.f();\n  ^~~\nnote: candidate #1 is defined in an impl of the trait `main::Foo` for the type\n`main::Baz`\n    fn f(&self) { println!(\"Baz’s impl of Foo\"); }\n    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nnote: candidate #2 is defined in an impl of the trait `main::Bar` for the type\n`main::Baz`\n    fn f(&self) { println!(\"Baz’s impl of Bar\"); }\n    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n```\n\nWe need a way to disambiguate which method we need. This feature is called\n‘universal function call syntax’, and it looks like this:\n\n```rust\n# trait Foo {\n#     fn f(&self);\n# }\n# trait Bar {\n#     fn f(&self);\n# }\n# struct Baz;\n# impl Foo for Baz {\n#     fn f(&self) { println!(\"Baz’s impl of Foo\"); }\n# }\n# impl Bar for Baz {\n#     fn f(&self) { println!(\"Baz’s impl of Bar\"); }\n# }\n# let b = Baz;\nFoo::f(&b);\nBar::f(&b);\n```\n\nLet’s break it down.\n\n```rust,ignore\nFoo::\nBar::\n```\n\nThese halves of the invocation are the types of the two traits: `Foo` and\n`Bar`. This is what ends up actually doing the disambiguation between the two:\nRust calls the one from the trait name you use.\n\n```rust,ignore\nf(&b)\n```\n\nWhen we call a method like `b.f()` using [method syntax][methodsyntax], Rust\nwill automatically borrow `b` if `f()` takes `&self`. In this case, Rust will\nnot, and so we need to pass an explicit `&b`.\n\n[methodsyntax]: method-syntax.html\n\n# Angle-bracket Form\n\nThe form of UFCS we just talked about:\n\n```rust,ignore\nTrait::method(args);\n```\n\nIs a short-hand. There’s an expanded form of this that’s needed in some\nsituations:\n\n```rust,ignore\n<Type as Trait>::method(args);\n```\n\nThe `<>::` syntax is a means of providing a type hint. The type goes inside\nthe `<>`s. In this case, the type is `Type as Trait`, indicating that we want\n`Trait`’s version of `method` to be called here. The `as Trait` part is\noptional if it’s not ambiguous. Same with the angle brackets, hence the\nshorter form.\n\nHere’s an example of using the longer form.\n\n```rust\ntrait Foo {\n    fn foo() -> i32;\n}\n\nstruct Bar;\n\nimpl Bar {\n    fn foo() -> i32 {\n        20\n    }\n}\n\nimpl Foo for Bar {\n    fn foo() -> i32 {\n        10\n    }\n}\n\nfn main() {\n    assert_eq!(10, <Bar as Foo>::foo());\n    assert_eq!(20, Bar::foo());\n}\n```\n\nUsing the angle bracket syntax lets you call the trait method instead of the\ninherent one.\n"
  },
  {
    "path": "trpl/unsafe.md",
    "content": "% Unsafe\n\nRust’s main draw is its powerful static guarantees about behavior. But safety\nchecks are conservative by nature: there are some programs that are actually\nsafe, but the compiler is not able to verify this is true. To write these kinds\nof programs, we need to tell the compiler to relax its restrictions a bit. For\nthis, Rust has a keyword, `unsafe`. Code using `unsafe` has fewer restrictions\nthan normal code does.\n\nLet’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in\nfour contexts. The first one is to mark a function as unsafe:\n\n```rust\nunsafe fn danger_will_robinson() {\n    // scary stuff\n}\n```\n\nAll functions called from [FFI][ffi] must be marked as `unsafe`, for example.\nThe second use of `unsafe` is an unsafe block:\n\n[ffi]: ffi.html\n\n```rust\nunsafe {\n    // scary stuff\n}\n```\n\nThe third is for unsafe traits:\n\n```rust\nunsafe trait Scary { }\n```\n\nAnd the fourth is for `impl`ementing one of those traits:\n\n```rust\n# unsafe trait Scary { }\nunsafe impl Scary for i32 {}\n```\n\nIt’s important to be able to explicitly delineate code that may have bugs that\ncause big problems. If a Rust program segfaults, you can be sure the cause is\nrelated to something marked `unsafe`.\n\n# What does ‘safe’ mean?\n\nSafe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also\nimportant to know that there are certain behaviors that are probably not\ndesirable in your code, but are expressly _not_ unsafe:\n\n* Deadlocks\n* Leaks of memory or other resources\n* Exiting without calling destructors\n* Integer overflow\n\nRust cannot prevent all kinds of software problems. Buggy code can and will be\nwritten in Rust. These things aren’t great, but they don’t qualify as `unsafe`\nspecifically.\n\nIn addition, the following are all undefined behaviors in Rust, and must be\navoided, even when writing `unsafe` code:\n\n* Data races\n* Dereferencing a NULL/dangling raw pointer\n* Reads of [undef][undef] (uninitialized) memory\n* Breaking the [pointer aliasing rules][aliasing] with raw pointers.\n* `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if\n  the `&T` contains an `UnsafeCell<U>`. Unsafe code must not violate these\n  aliasing guarantees.\n* Mutating an immutable value/reference without `UnsafeCell<U>`\n* Invoking undefined behavior via compiler intrinsics:\n  * Indexing outside of the bounds of an object with `std::ptr::offset`\n    (`offset` intrinsic), with\n    the exception of one byte past the end which is permitted.\n  * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`\n    intrinsics) on overlapping buffers\n* Invalid values in primitive types, even in private fields/locals:\n  * NULL/dangling references or boxes\n  * A value other than `false` (0) or `true` (1) in a `bool`\n  * A discriminant in an `enum` not included in its type definition\n  * A value in a `char` which is a surrogate or above `char::MAX`\n  * Non-UTF-8 byte sequences in a `str`\n* Unwinding into Rust from foreign code or unwinding from Rust into foreign\n  code.\n\n[noalias]: http://llvm.org/docs/LangRef.html#noalias\n[undef]: http://llvm.org/docs/LangRef.html#undefined-values\n[aliasing]: http://llvm.org/docs/LangRef.html#pointer-aliasing-rules\n\n# Unsafe Superpowers\n\nIn both unsafe functions and unsafe blocks, Rust will let you do three things\nthat you normally can not do. Just three. Here they are:\n\n1. Access or update a [static mutable variable][static].\n2. Dereference a raw pointer.\n3. Call unsafe functions. This is the most powerful ability.\n\nThat’s it. It’s important that `unsafe` does not, for example, ‘turn off the\nborrow checker’. Adding `unsafe` to some random Rust code doesn’t change its\nsemantics, it won’t start accepting anything. But it will let you write\nthings that _do_ break some of the rules.\n\nYou will also encounter the `unsafe` keyword when writing bindings to foreign\n(non-Rust) interfaces. You're encouraged to write a safe, native Rust interface\naround the methods provided by the library.\n\nLet’s go over the basic three abilities listed, in order.\n\n## Access or update a `static mut`\n\nRust has a feature called ‘`static mut`’ which allows for mutable global state.\nDoing so can cause a data race, and as such is inherently not safe. For more\ndetails, see the [static][static] section of the book.\n\n[static]: const-and-static.html#static\n\n## Dereference a raw pointer\n\nRaw pointers let you do arbitrary pointer arithmetic, and can cause a number of\ndifferent memory safety and security issues. In some senses, the ability to\ndereference an arbitrary pointer is one of the most dangerous things you can\ndo. For more on raw pointers, see [their section of the book][rawpointers].\n\n[rawpointers]: raw-pointers.html\n\n## Call unsafe functions\n\nThis last ability works with both aspects of `unsafe`: you can only call\nfunctions marked `unsafe` from inside an unsafe block.\n\nThis ability is powerful and varied. Rust exposes some [compiler\nintrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass\nsafety checks, trading safety for speed.\n\nI’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks\nand functions doesn’t mean you should. The compiler will act as though you’re\nupholding its invariants, so be careful!\n\n[intrinsics]: intrinsics.html\n"
  },
  {
    "path": "trpl/unsized-types.md",
    "content": "% Unsized Types\n\nMost types have a particular size, in bytes, that is knowable at compile time.\nFor example, an `i32` is thirty-two bits big, or four bytes. However, there are\nsome types which are useful to express, but do not have a defined size. These are\ncalled ‘unsized’ or ‘dynamically sized’ types. One example is `[T]`. This type\nrepresents a certain number of `T` in sequence. But we don’t know how many\nthere are, so the size is not known.\n\nRust understands a few of these types, but they have some restrictions. There\nare three:\n\n1. We can only manipulate an instance of an unsized type via a pointer. An\n   `&[T]` works fine, but a `[T]` does not.\n2. Variables and arguments cannot have dynamically sized types.\n3. Only the last field in a `struct` may have a dynamically sized type; the\n   other fields must not. Enum variants must not have dynamically sized types as\n   data.\n\nSo why bother? Well, because `[T]` can only be used behind a pointer, if we\ndidn’t have language support for unsized types, it would be impossible to write\nthis:\n\n```rust,ignore\nimpl Foo for str {\n```\n\nor\n\n```rust,ignore\nimpl<T> Foo for [T] {\n```\n\nInstead, you would have to write:\n\n```rust,ignore\nimpl Foo for &str {\n```\n\nMeaning, this implementation would only work for [references][ref], and not\nother types of pointers. With the `impl for str`, all pointers, including (at\nsome point, there are some bugs to fix first) user-defined custom smart\npointers, can use this `impl`.\n\n[ref]: references-and-borrowing.html\n\n# ?Sized\n\nIf you want to write a function that accepts a dynamically sized type, you\ncan use the special bound syntax, `?Sized`:\n\n```rust\nstruct Foo<T: ?Sized> {\n    f: T,\n}\n```\n\nThis `?Sized`, read as “T may or may not be `Sized`”, which allows us to match\nboth sized and unsized types. All generic type parameters implicitly\nhave the `Sized` bound, so the `?Sized` can be used to opt-out of the implicit\nbound.\n"
  },
  {
    "path": "trpl/using-rust-without-the-standard-library.md",
    "content": "% Using Rust Without the Standard Library\n\nRust’s standard library provides a lot of useful functionality, but assumes\nsupport for various features of its host system: threads, networking, heap\nallocation, and others. There are systems that do not have these features,\nhowever, and Rust can work with those too! To do so, we tell Rust that we\ndon’t want to use the standard library via an attribute: `#![no_std]`.\n\n> Note: This feature is technically stable, but there are some caveats. For\n> one, you can build a `#![no_std]` _library_ on stable, but not a _binary_.\n> For details on binaries without the standard library, see [the nightly\n> chapter on `#![no_std]`](no-stdlib.html)\n\nTo use `#![no_std]`, add it to your crate root:\n\n```rust\n#![no_std]\n\nfn plus_one(x: i32) -> i32 {\n    x + 1\n}\n```\n\nMuch of the functionality that’s exposed in the standard library is also\navailable via the [`core` crate](../core/index.html). When we’re using the\nstandard library, Rust automatically brings `std` into scope, allowing you to\nuse its features without an explicit import. By the same token, when using\n`#![no_std]`, Rust will bring `core` into scope for you, as well as [its\nprelude](../core/prelude/v1/index.html). This means that a lot of code will Just\nWork:\n\n```rust\n#![no_std]\n\nfn may_fail(failure: bool) -> Result<(), &'static str> {\n    if failure {\n        Err(\"this didn’t work!\")\n    } else {\n        Ok(())\n    }\n}\n```\n"
  },
  {
    "path": "trpl/variable-bindings.md",
    "content": "% Variable Bindings\n\nVirtually every non-'Hello World’ Rust program uses *variable bindings*. They\nbind some value to a name, so it can be used later. `let` is\nused to introduce a binding, like this:\n\n```rust\nfn main() {\n    let x = 5;\n}\n```\n\nPutting `fn main() {` in each example is a bit tedious, so we’ll leave that out\nin the future. If you’re following along, make sure to edit your `main()`\nfunction, rather than leaving it off. Otherwise, you’ll get an error.\n\n# Patterns\n\nIn many languages, a variable binding would be called a *variable*, but Rust’s\nvariable bindings have a few tricks up their sleeves. For example the\nleft-hand side of a `let` statement is a ‘[pattern][pattern]’, not a\nvariable name. This means we can do things like:\n\n```rust\nlet (x, y) = (1, 2);\n```\n\nAfter this statement is evaluated, `x` will be one, and `y` will be two.\nPatterns are really powerful, and have [their own section][pattern] in the\nbook. We don’t need those features for now, so we’ll keep this in the back\nof our minds as we go forward.\n\n[pattern]: patterns.html\n\n# Type annotations\n\nRust is a statically typed language, which means that we specify our types up\nfront, and they’re checked at compile time. So why does our first example\ncompile? Well, Rust has this thing called ‘type inference’. If it can figure\nout what the type of something is, Rust doesn’t require you to explicitly type\nit out.\n\nWe can add the type if we want to, though. Types come after a colon (`:`):\n\n```rust\nlet x: i32 = 5;\n```\n\nIf I asked you to read this out loud to the rest of the class, you’d say “`x`\nis a binding with the type `i32` and the value `five`.”\n\nIn this case we chose to represent `x` as a 32-bit signed integer. Rust has\nmany different primitive integer types. They begin with `i` for signed integers\nand `u` for unsigned integers. The possible integer sizes are 8, 16, 32, and 64\nbits.\n\nIn future examples, we may annotate the type in a comment. The examples will\nlook like this:\n\n```rust\nfn main() {\n    let x = 5; // x: i32\n}\n```\n\nNote the similarities between this annotation and the syntax you use with\n`let`. Including these kinds of comments is not idiomatic Rust, but we'll\noccasionally include them to help you understand what the types that Rust\ninfers are.\n\n# Mutability\n\nBy default, bindings are *immutable*. This code will not compile:\n\n```rust,ignore\nlet x = 5;\nx = 10;\n```\n\nIt will give you this error:\n\n```text\nerror: re-assignment of immutable variable `x`\n     x = 10;\n     ^~~~~~~\n```\n\nIf you want a binding to be mutable, you can use `mut`:\n\n```rust\nlet mut x = 5; // mut x: i32\nx = 10;\n```\n\nThere is no single reason that bindings are immutable by default, but we can\nthink about it through one of Rust’s primary focuses: safety. If you forget to\nsay `mut`, the compiler will catch it, and let you know that you have mutated\nsomething you may not have intended to mutate. If bindings were mutable by\ndefault, the compiler would not be able to tell you this. If you _did_ intend\nmutation, then the solution is quite easy: add `mut`.\n\nThere are other good reasons to avoid mutable state when possible, but they’re\nout of the scope of this guide. In general, you can often avoid explicit\nmutation, and so it is preferable in Rust. That said, sometimes, mutation is\nwhat you need, so it’s not verboten.\n\n# Initializing bindings\n\nRust variable bindings have one more aspect that differs from other languages:\nbindings are required to be initialized with a value before you're allowed to\nuse them.\n\nLet’s try it out. Change your `src/main.rs` file to look like this:\n\n```rust\nfn main() {\n    let x: i32;\n\n    println!(\"Hello world!\");\n}\n```\n\nYou can use `cargo build` on the command line to build it. You’ll get a\nwarning, but it will still print \"Hello, world!\":\n\n```text\n   Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)\nsrc/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)]\n   on by default\nsrc/main.rs:2     let x: i32;\n                      ^\n```\n\nRust warns us that we never use the variable binding, but since we never use\nit, no harm, no foul. Things change if we try to actually use this `x`,\nhowever. Let’s do that. Change your program to look like this:\n\n```rust,ignore\nfn main() {\n    let x: i32;\n\n    println!(\"The value of x is: {}\", x);\n}\n```\n\nAnd try to build it. You’ll get an error:\n\n```bash\n$ cargo build\n   Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)\nsrc/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`\nsrc/main.rs:4     println!(\"The value of x is: {}\", x);\n                                                    ^\nnote: in expansion of format_args!\n<std macros>:2:23: 2:77 note: expansion site\n<std macros>:1:1: 3:2 note: in expansion of println!\nsrc/main.rs:4:5: 4:42 note: expansion site\nerror: aborting due to previous error\nCould not compile `hello_world`.\n```\n\nRust will not let us use a value that has not been initialized.\n\nLet take a minute to talk about this stuff we've added to `println!`.\n\nIf you include two curly braces (`{}`, some call them moustaches...) in your\nstring to print, Rust will interpret this as a request to interpolate some sort\nof value. *String interpolation* is a computer science term that means \"stick\nin the middle of a string.\" We add a comma, and then `x`, to indicate that we\nwant `x` to be the value we’re interpolating. The comma is used to separate\narguments we pass to functions and macros, if you’re passing more than one.\n\nWhen you use the curly braces, Rust will attempt to display the value in a\nmeaningful way by checking out its type. If you want to specify the format in a\nmore detailed manner, there are a [wide number of options available][format].\nFor now, we'll stick to the default: integers aren't very complicated to\nprint.\n\n[format]: ../std/fmt/index.html\n\n# Scope and shadowing\n\nLet’s get back to bindings. Variable bindings have a scope - they are\nconstrained to live in a block they were defined in. A block is a collection\nof statements enclosed by `{` and `}`. Function definitions are also blocks!\nIn the following example we define two variable bindings, `x` and `y`, which\nlive in different blocks. `x` can be accessed from inside the `fn main() {}`\nblock, while `y` can be accessed only from inside the inner block:\n\n```rust,ignore\nfn main() {\n    let x: i32 = 17;\n    {\n        let y: i32 = 3;\n        println!(\"The value of x is {} and value of y is {}\", x, y);\n    }\n    println!(\"The value of x is {} and value of y is {}\", x, y); // This won't work\n}\n```\n\nThe first `println!` would print \"The value of x is 17 and the value of y is\n3\", but this example cannot be compiled successfully, because the second\n`println!` cannot access the value of `y`, since it is not in scope anymore.\nInstead we get this error:\n\n```bash\n$ cargo build\n   Compiling hello v0.1.0 (file:///home/you/projects/hello_world)\nmain.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425]\nmain.rs:7     println!(\"The value of x is {} and value of y is {}\", x, y); // This won't work\n                                                                       ^\nnote: in expansion of format_args!\n<std macros>:2:25: 2:56 note: expansion site\n<std macros>:1:1: 2:62 note: in expansion of print!\n<std macros>:3:1: 3:54 note: expansion site\n<std macros>:1:1: 3:58 note: in expansion of println!\nmain.rs:7:5: 7:65 note: expansion site\nmain.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation\nerror: aborting due to previous error\nCould not compile `hello`.\n\nTo learn more, run the command again with --verbose.\n```\n\nAdditionally, variable bindings can be shadowed. This means that a later\nvariable binding with the same name as another binding that is currently in\nscope will override the previous binding.\n\n```rust\nlet x: i32 = 8;\n{\n    println!(\"{}\", x); // Prints \"8\"\n    let x = 12;\n    println!(\"{}\", x); // Prints \"12\"\n}\nprintln!(\"{}\", x); // Prints \"8\"\nlet x =  42;\nprintln!(\"{}\", x); // Prints \"42\"\n```\n\nShadowing and mutable bindings may appear as two sides of the same coin, but\nthey are two distinct concepts that can't always be used interchangeably. For\none, shadowing enables us to rebind a name to a value of a different type. It\nis also possible to change the mutability of a binding. Note that shadowing a \nname does not alter or destroy the value it was bound to, and the value will\ncontinue to exist until it goes out of scope, even if it is no longer accessible\nby any means.\n\n```rust\nlet mut x: i32 = 1;\nx = 7;\nlet x = x; // x is now immutable and is bound to 7\n\nlet y = 4;\nlet y = \"I can also be bound to text!\"; // y is now of a different type\n```\n"
  },
  {
    "path": "trpl/vectors.md",
    "content": "% Vectors\n\nA ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard\nlibrary type [`Vec<T>`][vec]. The `T` means that we can have vectors\nof any type (see the chapter on [generics][generic] for more).\nVectors always allocate their data on the heap.\nYou can create them with the `vec!` macro:\n\n```rust\nlet v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>\n```\n\n(Notice that unlike the `println!` macro we’ve used in the past, we use square\nbrackets `[]` with `vec!` macro. Rust allows you to use either in either\nsituation, this is just convention.)\n\nThere’s an alternate form of `vec!` for repeating an initial value:\n\n```rust\nlet v = vec![0; 10]; // ten zeroes\n```\n\nVectors store their contents as contiguous arrays of `T` on the heap. This means\nthat they must be able to know the size of `T` at compile time (that is, how\nmany bytes are needed to store a `T`?). The size of some things can't be known\nat compile time. For these you'll have to store a pointer to that thing:\nthankfully, the [`Box`][box] type works perfectly for this.\n\n## Accessing elements\n\nTo get the value at a particular index in the vector, we use `[]`s:\n\n```rust\nlet v = vec![1, 2, 3, 4, 5];\n\nprintln!(\"The third element of v is {}\", v[2]);\n```\n\nThe indices count from `0`, so the third element is `v[2]`.\n\nIt’s also important to note that you must index with the `usize` type:\n\n```rust,ignore\nlet v = vec![1, 2, 3, 4, 5];\n\nlet i: usize = 0;\nlet j: i32 = 0;\n\n// works\nv[i];\n\n// doesn’t\nv[j];\n```\n\nIndexing with a non-`usize` type gives an error that looks like this:\n\n```text\nerror: the trait bound `collections::vec::Vec<_> : core::ops::Index<i32>`\nis not satisfied [E0277]\nv[j];\n^~~~\nnote: the type `collections::vec::Vec<_>` cannot be indexed by `i32`\nerror: aborting due to previous error\n```\n\nThere’s a lot of punctuation in that message, but the core of it makes sense:\nyou cannot index with an `i32`.\n\n## Out-of-bounds Access\n\nIf you try to access an index that doesn’t exist:\n\n```rust,ignore\nlet v = vec![1, 2, 3];\nprintln!(\"Item 7 is {}\", v[7]);\n```\n\nthen the current thread will [panic] with a message like this:\n\n```text\nthread 'main' panicked at 'index out of bounds: the len is 3 but the index is 7'\n```\n\nIf you want to handle out-of-bounds errors without panicking, you can use\nmethods like [`get`][get] or [`get_mut`][get_mut] that return `None` when\ngiven an invalid index:\n\n```rust\nlet v = vec![1, 2, 3];\nmatch v.get(7) {\n    Some(x) => println!(\"Item 7 is {}\", x),\n    None => println!(\"Sorry, this vector is too short.\")\n}\n```\n\n## Iterating\n\nOnce you have a vector, you can iterate through its elements with `for`. There\nare three versions:\n\n```rust\nlet mut v = vec![1, 2, 3, 4, 5];\n\nfor i in &v {\n    println!(\"A reference to {}\", i);\n}\n\nfor i in &mut v {\n    println!(\"A mutable reference to {}\", i);\n}\n\nfor i in v {\n    println!(\"Take ownership of the vector and its element {}\", i);\n}\n```\n\nNote: You cannot use the vector again once you have iterated by taking ownership of the vector.\nYou can iterate the vector multiple times by taking a reference to the vector whilst iterating.\nFor example, the following code does not compile.\n\n```rust,ignore\nlet v = vec![1, 2, 3, 4, 5];\n\nfor i in v {\n    println!(\"Take ownership of the vector and its element {}\", i);\n}\n\nfor i in v {\n    println!(\"Take ownership of the vector and its element {}\", i);\n}\n```\n\nWhereas the following works perfectly,\n\n```rust\nlet v = vec![1, 2, 3, 4, 5];\n\nfor i in &v {\n    println!(\"This is a reference to {}\", i);\n}\n\nfor i in &v {\n    println!(\"This is a reference to {}\", i);\n}\n```\n\nVectors have many more useful methods, which you can read about in [their\nAPI documentation][vec].\n\n[vec]: ../std/vec/index.html\n[box]: ../std/boxed/index.html\n[generic]: generics.html\n[panic]: concurrency.html#panics\n[get]: ../std/vec/struct.Vec.html#method.get\n[get_mut]: ../std/vec/struct.Vec.html#method.get_mut\n"
  },
  {
    "path": "trpl_meta.yml",
    "content": "---\ntitle: \"The Rust Programming Language\"\nauthor: \"The Rust Team\"\ndate: {release_date}\ndescription: \"This book will teach you about the Rust Programming Language. Rust is a modern systems programming language focusing on safety and speed. It accomplishes these goals by being memory safe without using garbage collection.\"\nlanguage: en\ndocumentclass: book\nlinks-as-notes: true\nverbatim-in-note: true\ntoc-depth: 2\nmonofont: \"DejaVu Sans Mono\"\n...\n"
  }
]